From 0690841c6b5d33bfcbf91be3b02f13e63c990ed1 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 10 Feb 2014 17:40:59 +0000 Subject: [PATCH 001/277] 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/277] 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/277] 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/277] 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/277] 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/277] 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/277] 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/277] 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/277] 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/277] 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 a8fbeb0d2883ccccd90ab68ad3ea218bbc3bfe7a Mon Sep 17 00:00:00 2001 From: Martin Poelstra Date: Mon, 14 Jul 2014 10:57:13 +0200 Subject: [PATCH 011/277] Expand typings for source-map-support. --- .../source-map-support-tests.ts | 36 ++++++++++++++++++ source-map-support/source-map-support.d.ts | 37 ++++++++++++++++++- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/source-map-support/source-map-support-tests.ts b/source-map-support/source-map-support-tests.ts index ddd6308cc..09a4fff45 100644 --- a/source-map-support/source-map-support-tests.ts +++ b/source-map-support/source-map-support-tests.ts @@ -3,3 +3,39 @@ import sms = require('source-map-support'); sms.install(); + +function retrieveFile(path: string): string { + return "foo"; +} + +function retrieveSourceMap(source: string): sms.UrlAndMap { + return { + url: "http://foo", + map: "foo" + }; +} + +var options: sms.Options = { + emptyCacheBetweenOperations: false, + handleUncaughtExceptions: false, + retrieveFile: retrieveFile, + retrieveSourceMap: retrieveSourceMap +}; + +sms.install(options); + +var stackFrame: any; // TODO: this should be a StackFrame, but it seems this would need to be defined elsewhere (in e.g. lib.d.ts) +stackFrame = sms.wrapCallSite(stackFrame); + +var s: string; +s = sms.getErrorSource(new Error("foo")); + +var p: sms.Position = { + column: 0, + line: 0, + source: "foo" +}; +p = sms.mapSourcePosition(p); + +var u: sms.UrlAndMap; +u = retrieveSourceMap("foo"); diff --git a/source-map-support/source-map-support.d.ts b/source-map-support/source-map-support.d.ts index 8d4e22579..b0de346a7 100644 --- a/source-map-support/source-map-support.d.ts +++ b/source-map-support/source-map-support.d.ts @@ -1,8 +1,41 @@ -// Type definitions for source-map-support 0.2.5 +// Type definitions for source-map-support 0.2.6 // Project: https://github.com/evanw/source-map-support // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'source-map-support' { - export function install(): any; + /** + * Output of retrieveSourceMap(). + */ + export interface UrlAndMap { + url: string; + map: any; // string or Buffer + } + + /** + * Options to install(). + */ + export interface Options { + handleUncaughtExceptions?: boolean; + emptyCacheBetweenOperations?: boolean; + retrieveFile?: (path: string) => string; + retrieveSourceMap?: (source: string) => UrlAndMap; + } + + export interface Position { + source: string; + line: number; + column: number; + } + + export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; + export function getErrorSource(error: Error): string; + export function mapSourcePosition(position: Position): Position; + export function retrieveSourceMap(source: string): UrlAndMap; + + /** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ + export function install(options?: Options): void; } From 4e6c9f190bf4237da0da5fb0804c888f28ff85f0 Mon Sep 17 00:00:00 2001 From: Georgie Date: Mon, 14 Jul 2014 14:05:30 -0700 Subject: [PATCH 012/277] ChartArea allows missing members --- google.visualization/google.visualization.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 11a1f780c..f45f3f6a3 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -244,10 +244,10 @@ declare module google { } export interface ChartArea { - top: any; - left: any; - width: any; - height: any; + top?: any; + left?: any; + width?: any; + height?: any; } export interface ChartLegend { From 56a71f88b0db9a2cd63759e10ba3155a2fde2613 Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Mon, 14 Jul 2014 14:11:51 -0700 Subject: [PATCH 013/277] 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 014/277] 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 6e579ac47196258f0fb59ab48f4288d276a8e9ec Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Tue, 15 Jul 2014 15:10:17 +1000 Subject: [PATCH 015/277] Update kineticjs.d.ts - `Line` has property `dashArray` not dash : http://kineticjs.com/docs/Kinetic.Line.html - there is no `remove` function on `Container` : http://kineticjs.com/docs/Kinetic.Container.html that takes a child - there is however a `remove` function on `Node` that removes an item from its parent. http://kineticjs.com/docs/Kinetic.Node.html This function exists in Container as well http://kineticjs.com/docs/Kinetic.Container.html (since container inherits from Node) --- kineticjs/kineticjs.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index ecfbbae1f..dc9219fe2 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -53,6 +53,7 @@ declare module Kinetic { moveUp(): void; name(): string; name(name: string): void; + remove(): any; rotate(theta: number): void; rotateDeg(deg: number): void; @@ -124,7 +125,6 @@ declare module Kinetic { getChildren(): INode[]; getIntersections(point: any): any; isAncestorOf(node: any): any; - remove(child: any): any; removeChildren(): any; } @@ -136,6 +136,7 @@ declare module Kinetic { add(layer: ILayer): any; clear(): any; getContainer(): HTMLElement; + getContent(): HTMLElement; getDOM(): HTMLElement; getHeight(): number; getIntersection(pos: any): any; @@ -481,7 +482,7 @@ declare module Kinetic { interface LineConfig extends DrawOptionsConfig, ObjectOptionsConfig { points: any; lineCap?: string; - dashArray?: any; + dash?: number[]; } interface PolygonConfig extends DrawOptionsConfig, ObjectOptionsConfig { From 436ecfdb3bdb97ae882c89128c0560e6928a651c Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 08:39:53 -0700 Subject: [PATCH 016/277] Added Rx.Observable.of. --- rx.js/rx-lite.d.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index ad30b6e94..5c20fd39d 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -391,6 +391,24 @@ declare module Rx { fromItreable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; never(): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * + * @example + * var res = Rx.Observable.of(1, 2, 3); + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + of(...values: T[]): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @param [scheduler] A scheduler to use for scheduling the arguments. + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + ofWithScheduler(scheduler?: IScheduler, ...values: T[]): Observable; range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; From b5c9860090ad5898d7e7a6d9473e3b97ff94ab97 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 08:51:27 -0700 Subject: [PATCH 017/277] Added `exclusive` operator. --- rx.js/rx-lite.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 5c20fd39d..3e5fa2b78 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -352,6 +352,16 @@ declare module Rx { * @returns An ES6 compatible promise with the last value from the observable sequence. */ toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }): IPromise; + + // Experimental Flattening + + /** + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @returns A exclusive observable with only the results that happen when subscribed. + */ + exclusive(): Observable; } interface ObservableStatic { From f3ed4c501ecca2304f98a58da7af321308598e7b Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:04:49 -0700 Subject: [PATCH 018/277] Added `exclusiveMap` operator. --- rx.js/rx-lite.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 3e5fa2b78..2e81da920 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -361,7 +361,17 @@ declare module Rx { * Can be applied on `Observable>` or `Observable>`. * @returns A exclusive observable with only the results that happen when subscribed. */ - exclusive(): Observable; + exclusive(): Observable; + + /** + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @param selector Selector to invoke for every item in the current subscription. + * @param [thisArg] An optional context to invoke with the selector parameter. + * @returns {An exclusive observable with only the results that happen when subscribed. + */ + exclusiveMap(selector: (value: I, index: number, source: Observable) => R, thisArg?: any): Observable; } interface ObservableStatic { From 3399c7e738d4121fbe034514daf2d6ec09f99e92 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:11:16 -0700 Subject: [PATCH 019/277] `shareReplay` moved to `rx.binding-lite.d.ts`. Removed `replayWhileObserved` from `rx.binding.d.ts` (replaced by `shareReplay`). --- rx.js/rx.binding-lite.d.ts | 1 + rx.js/rx.binding.d.ts | 6 ------ rx.js/rx.lite.d.ts | 4 ---- 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/rx.js/rx.binding-lite.d.ts b/rx.js/rx.binding-lite.d.ts index e1120e109..f896e260d 100644 --- a/rx.js/rx.binding-lite.d.ts +++ b/rx.js/rx.binding-lite.d.ts @@ -67,5 +67,6 @@ declare module Rx { shareValue(initialValue: T): Observable; replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable; // hack to catch first omitted parameter replay(selector: (source: ConnectableObservable) => Observable, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; + shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; } } diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts index cf089e43f..3adbcbe2b 100644 --- a/rx.js/rx.binding.d.ts +++ b/rx.js/rx.binding.d.ts @@ -6,12 +6,6 @@ /// /// -declare module Rx { - export interface Observable { - replayWhileObserved(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; - } -} - declare module "rx.binding" { export = Rx; } \ No newline at end of file diff --git a/rx.js/rx.lite.d.ts b/rx.js/rx.lite.d.ts index ddffc4a16..da2ddde3b 100644 --- a/rx.js/rx.lite.d.ts +++ b/rx.js/rx.lite.d.ts @@ -43,10 +43,6 @@ declare module Rx { schedulePeriodic(period: number, action: () => void): IDisposable; schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; } - - export interface Observable { - shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; // same as replayWhileObserved in rx.binding.d.ts - } } declare module "rx.lite" { From cfbd50bddb1ff9c65c7c966e9fbbba13fed6efc7 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:13:26 -0700 Subject: [PATCH 020/277] Added @since jsdoc attributes for new methods. --- rx.js/rx-lite.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 2e81da920..db4642372 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -359,6 +359,7 @@ declare module Rx { * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 * @returns A exclusive observable with only the results that happen when subscribed. */ exclusive(): Observable; @@ -367,6 +368,7 @@ declare module Rx { * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 * @param selector Selector to invoke for every item in the current subscription. * @param [thisArg] An optional context to invoke with the selector parameter. * @returns {An exclusive observable with only the results that happen when subscribed. @@ -417,6 +419,7 @@ declare module Rx { * * @example * var res = Rx.Observable.of(1, 2, 3); + * @since 2.2.28 * @returns The observable sequence whose elements are pulled from the given arguments. */ of(...values: T[]): Observable; @@ -425,6 +428,7 @@ declare module Rx { * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @since 2.2.28 * @param [scheduler] A scheduler to use for scheduling the arguments. * @returns The observable sequence whose elements are pulled from the given arguments. */ From aa37a6d4be12e148386df01bdd7f1873f6fd8320 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:17:13 -0700 Subject: [PATCH 021/277] Added alias `just` for `return`. --- rx.js/rx-lite.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index db4642372..2c65d950a 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -436,6 +436,7 @@ declare module Rx { range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; + just(value: T, scheduler?: IScheduler): Observable; // alias for return returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return throw(exception: Error, scheduler?: IScheduler): Observable; throw(exception: any, scheduler?: IScheduler): Observable; From a1fe5ce51b15f76b90ab0bf671efa930f82a3a56 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:29:06 -0700 Subject: [PATCH 022/277] Added `switchMap` alias for `selectSwitch`. --- rx.js/rx-lite.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/rx.js/rx-lite.d.ts b/rx.js/rx-lite.d.ts index 2c65d950a..c7a148137 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx.js/rx-lite.d.ts @@ -324,6 +324,16 @@ declare module Rx { * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @since 2.2.28 + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch skip(count: number): Observable; skipWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; @@ -436,6 +446,9 @@ declare module Rx { range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; + /** + * @since 2.2.28 + */ just(value: T, scheduler?: IScheduler): Observable; // alias for return returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return throw(exception: Error, scheduler?: IScheduler): Observable; From 2f5fb6d9e458763c0b096c2378166e4189ca23f5 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 09:33:03 -0700 Subject: [PATCH 023/277] Version bump to 2.2.28 --- rx.js/rx.aggregates.d.ts | 2 +- rx.js/rx.all.ts | 2 +- rx.js/rx.async.d.ts | 2 +- rx.js/rx.backpressure.d.ts | 2 +- rx.js/rx.binding.d.ts | 2 +- rx.js/rx.coincidence.d.ts | 2 +- rx.js/rx.d.ts | 2 +- rx.js/rx.experimental.d.ts | 2 +- rx.js/rx.joinpatterns.d.ts | 2 +- rx.js/rx.lite.d.ts | 2 +- rx.js/rx.testing.d.ts | 2 +- rx.js/rx.time.d.ts | 2 +- rx.js/rx.virtualtime.d.ts | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/rx.js/rx.aggregates.d.ts b/rx.js/rx.aggregates.d.ts index 4ab7355ed..001d1b993 100644 --- a/rx.js/rx.aggregates.d.ts +++ b/rx.js/rx.aggregates.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Aggregates v2.2.25 +// Type definitions for RxJS-Aggregates v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.all.ts b/rx.js/rx.all.ts index 608605fae..c546477b8 100644 --- a/rx.js/rx.all.ts +++ b/rx.js/rx.all.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-All v2.2.25 +// Type definitions for RxJS-All v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.async.d.ts b/rx.js/rx.async.d.ts index 14823b948..9370c828b 100644 --- a/rx.js/rx.async.d.ts +++ b/rx.js/rx.async.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Async v2.2.25 +// Type definitions for RxJS-Async v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: zoetrope , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.backpressure.d.ts b/rx.js/rx.backpressure.d.ts index 5f5013fe1..9c5e8abd5 100644 --- a/rx.js/rx.backpressure.d.ts +++ b/rx.js/rx.backpressure.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-BackPressure v2.2.25 +// Type definitions for RxJS-BackPressure v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts index 3adbcbe2b..b93411a52 100644 --- a/rx.js/rx.binding.d.ts +++ b/rx.js/rx.binding.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Binding v2.2.25 +// Type definitions for RxJS-Binding v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.coincidence.d.ts b/rx.js/rx.coincidence.d.ts index af7acd4de..87fa6a55b 100644 --- a/rx.js/rx.coincidence.d.ts +++ b/rx.js/rx.coincidence.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Coincidence v2.2.25 +// Type definitions for RxJS-Coincidence v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.d.ts b/rx.js/rx.d.ts index 967b5aefa..1f26a94a9 100644 --- a/rx.js/rx.d.ts +++ b/rx.js/rx.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS v2.2.25 +// Type definitions for RxJS v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.experimental.d.ts b/rx.js/rx.experimental.d.ts index 885630be2..60aec86e1 100644 --- a/rx.js/rx.experimental.d.ts +++ b/rx.js/rx.experimental.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Experimental v2.2.25 +// Type definitions for RxJS-Experimental v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.joinpatterns.d.ts b/rx.js/rx.joinpatterns.d.ts index 9d0d7244f..929c66a6f 100644 --- a/rx.js/rx.joinpatterns.d.ts +++ b/rx.js/rx.joinpatterns.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Join v2.2.25 +// Type definitions for RxJS-Join v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.lite.d.ts b/rx.js/rx.lite.d.ts index da2ddde3b..046ef527d 100644 --- a/rx.js/rx.lite.d.ts +++ b/rx.js/rx.lite.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Lite v2.2.25 +// Type definitions for RxJS-Lite v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.testing.d.ts b/rx.js/rx.testing.d.ts index 393061625..0adc83e50 100644 --- a/rx.js/rx.testing.d.ts +++ b/rx.js/rx.testing.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Testing v2.2.25 +// Type definitions for RxJS-Testing v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.time.d.ts b/rx.js/rx.time.d.ts index ae2408e85..6efd7d9cf 100644 --- a/rx.js/rx.time.d.ts +++ b/rx.js/rx.time.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Time v2.2.25 +// Type definitions for RxJS-Time v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rx.js/rx.virtualtime.d.ts b/rx.js/rx.virtualtime.d.ts index 04de75e94..50a1bb39b 100644 --- a/rx.js/rx.virtualtime.d.ts +++ b/rx.js/rx.virtualtime.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-VirtualTime v2.2.25 +// Type definitions for RxJS-VirtualTime v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped From 72ab7b498ae39b2cece7d0365f7011f2b380dc03 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Tue, 15 Jul 2014 12:41:50 -0700 Subject: [PATCH 024/277] Added AMD named module export definition for `rx.jquery`. --- rx.js/rx.jquery.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rx.js/rx.jquery.d.ts b/rx.js/rx.jquery.d.ts index 75202142e..ace0c5071 100644 --- a/rx.js/rx.jquery.d.ts +++ b/rx.js/rx.jquery.d.ts @@ -60,3 +60,7 @@ interface JQuery { slideToggleAsObservable(duration: number): Rx.Observable; toggleAsObservable(duration: number): Rx.Observable; } + +declare module "rx.jquery" { + export = Rx; +} \ No newline at end of file From 68dfa3453b17b5138ee57a39f341408c83ec0a63 Mon Sep 17 00:00:00 2001 From: Ian Sibner Date: Tue, 15 Jul 2014 20:02:31 -0400 Subject: [PATCH 025/277] Add definitions for angular-protractor 1.0.0-rc4 --- .../angular-protractor-tests.ts | 91 +- angular-protractor/angular-protractor.d.ts | 786 +++++++++------ .../legacy/angular-protractor-0.17.0-tests.ts | 244 +++++ .../legacy/angular-protractor-0.17.0.d.ts | 906 ++++++++++++++++++ 4 files changed, 1724 insertions(+), 303 deletions(-) create mode 100644 angular-protractor/legacy/angular-protractor-0.17.0-tests.ts create mode 100644 angular-protractor/legacy/angular-protractor-0.17.0.d.ts diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 37c9e49bc..62ed46177 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -153,21 +153,36 @@ function TestProtractor() { ptor.debugger(); + var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); + var promise: webdriver.promise.Promise; + promise = ptor.findElements(by.css('.class')); + promise = ptor.isElementPresent(by.css('.class')); + promise = ptor.isElementPresent(webElement); + ptor.clearMockModules(); ptor.addMockModule('name', 'script'); ptor.addMockModule('name', function() {}); + ptor.removeMockModule('name'); ptor.waitForAngular(); var elementFinder: protractor.ElementFinder; + var elementArrayFinder: protractor.ElementArrayFinder; elementFinder = ptor.element(by.id('ABC')); elementFinder = ptor.$('.class'); - var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); - - var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + elementArrayFinder = ptor.$$('.class'); var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + ptor.setLocation('webaddress.com'); + + promise = ptor.get('webaddress.com'); + promise = ptor.get('webdaddress.com', 45); + ptor.refresh(); + ptor.refresh(45); + var navigation: webdriver.WebDriverNavigation = ptor.navigate(); + ptor.pause(); + ptor.pause(8080); } function TestElement() { @@ -180,6 +195,7 @@ function TestElementFinder() { var promise: webdriver.promise.Promise; promise = elementFinder.click(); + promise = elementFinder.allowAnimations('string'); promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); promise = elementFinder.getTagName(); promise = elementFinder.getCssValue('display'); @@ -196,18 +212,45 @@ function TestElementFinder() { promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.findElements(by.className('class')); - promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); promise = elementFinder.isPresent(); var webElement: webdriver.WebElement; +} - webElement = elementFinder.$('.class'); - webElement = elementFinder.findElement(by.id('id')); - webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); - webElement = elementFinder.find(); +function TestElementArrayFinder() { + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); + var promise: webdriver.promise.Promise; + var elementFinder: protractor.ElementFinder; + + var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); + elementFinder = elementArrayFinder.get(42); + elementFinder = elementArrayFinder.first(); + elementFinder = elementArrayFinder.last(); + promise = elementArrayFinder.count(); + elementArrayFinder.each(function(element: protractor.ElementFinder){ + // nothing + }); + elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + // nothing + }); + elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + return element.getText().then((text: string) => { + return text === "foo"; + }); + }); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); } // This function tests the angular specific locator strategies. @@ -216,29 +259,19 @@ function TestLocatorStrategies() { var webElement: webdriver.WebElement; // Protractor Specific Locators + protractor.By.addLocator('customLocator', 'script'); + protractor.By.addLocator('customLocator2', function(){ + // nothing + }); webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.select('select')); - webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); - webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.textarea('textarea')); webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); webElement = ptor.findElement(protractor.By.buttonText('buttonText')); webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); -} - -// This function tests the methods that were added to the base WebElement class -function TestWebElements() { - var ptor: protractor.Protractor = protractor.getInstance(); - - var webElement: protractor.WebElement; - var promise: webdriver.promise.Promise; - - webElement = ptor.findElement(by.id('id')).$('.class'); - promise = ptor.findElement(by.id('id')).$$('.class'); - promise = ptor.findElement(by.id('id')).evaluate('something'); - - webElement = webElement.findElement(by.id('id')).$('.class'); - promise = webElement.findElement(by.id('id')).$$('.class'); - promise = webElement.findElement(by.id('id')).evaluate('something'); + webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); + webElement = ptor.findElement(protractor.By.options('options')); } diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 3c3c0981f..81eca975e 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Protractor 0.17.0 +// Type definitions for Angular Protractor 1.0.0-rc4 // Project: https://github.com/angular/protractor // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -25,71 +25,7 @@ declare module protractor { class CommandName extends webdriver.CommandName {} class Key extends webdriver.Key {} class UnhandledAlertError extends webdriver.UnhandledAlertError {} - - class WebElement extends webdriver.WebElement { - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - } + class WebElement extends webdriver.WebElement {} module command { class Command extends webdriver.Command {} @@ -273,13 +209,160 @@ declare module protractor { } //endregion - + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @param {ElementFinder=} opt_parentElementFinder The element finder previous + * to this. (i.e. opt_parentElementFinder.element(locator) => this) + * @param {webdriver.promise.Promise} opt_actionResult The promise which + * will be retrieved with then. Resolves to the latest action result, + * or null if no action has been called. + * @param {number=} opt_index The index of the element to retrieve. null means + * retrieve the only element, while -1 means retrieve the last element + * @return {ElementFinder} + */ interface Element { - (locator: webdriver.Locator): ElementFinder; - all(locator: webdriver.Locator): ElementArrayFinder; + (locator: webdriver.Locator, + opt_parentElementFinder?: protractor.ElementFinder, + opt_actionResult?: webdriver.promise.Promise, + opt_index?: number): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @param {ElementFinder=} opt_parentElementFinder The element finder previous to + * this. (i.e. opt_parentElementFinder.all(locator) => this) + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator, opt_parentElementFinder?: protractor.ElementFinder): ElementArrayFinder; } interface ElementFinder { + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} The descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} The descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).isPresent() + * Determine whether the element is present on the page. + * + * @return {protractor.ElementFinder} Which resolves to whether the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Return this ElementFinder's locator. + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Use as: element(locator).getWebElement() + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * If index is null, it makes sure that there is only one underlying WebElement + * described by the chain of locators and issues a warning otherwise. + * If index is not null, it retrieves the WebElement specified by the index.. + * @return {webdriver.WebElement} The WebElement represented by the ElementFinder. + */ + getWebElement(): webdriver.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Determine if animation is allowed on the current element. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): webdriver.promise.Promise; + + /** + * Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise. + * @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult. + * + * @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn. + */ + then(fn: IThenFunction): webdriver.promise.Promise; + /** * Schedules a command to click on this element. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -460,113 +543,128 @@ declare module protractor { getInnerHtml(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - find(): protractor.WebElement; - - isPresent(): webdriver.promise.Promise; + toWireValue(): webdriver.promise.Promise; } - interface ElementArrayFinder{ + interface IThenFunction { + (promise: webdriver.promise.Promise): any; + } + + + interface ElementArrayFinder { + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {Array.} Array of WebElements represented by this ElementArrayFinder + */ + getWebElements(): webdriver.WebElement[]; + + /** + * Use as: element.all(locator).get(index) + * Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element. + * + * @param {number} index Element index. + * + * @return {protractor.ElementFinder} Finder representing element at the given index + */ + get(index: number): protractor.ElementFinder; + + + /** + * Use as: element.all(locator).first() + * Get the first matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the first matching element + */ + first(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).last() + * Get the last matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the last matching element + */ + last(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder + */ count(): webdriver.promise.Promise; - get(index: number): protractor.WebElement; - first(): protractor.WebElement; - last(): protractor.WebElement; - then(fn: (value: any) => any): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).each(eachFunction) + * Calls the input function on each ElementFinder found by the locator. + * + * @param {function(ElementFinder)} fn Input function. + */ + each(fn: IEachFunction): void; + + /** + * Use as: element.all(locator).map(mapFunction) + * Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number)} mapFn Map function that will be applied to each element. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of values returned by the map function. + */ + map(mapFn: IMapFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).filter(filterFn) + * Apply a filter function to each element found using the locator. Returns promise of a new array with all elements that pass the filter function. The filter function receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function. + */ + filter(func: IFilterFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).reduce(reduceFn) + * Apply a reduce function against an accumulator and every element found using the locator (from left-to-right). + * The reduce function has to reduce every element into a single value (the accumulator). + * Returns promise of the accumulator. + * The reduce function receives the accumulator, current ElementFinder, the index, and the entire array of ElementFinders, respectively. + * + * @param {function(number, ElementFinder, number, Array.): webdriver.promise.Promise} reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * + * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. + */ + reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + } + + interface IEachFunction { + (element: protractor.ElementFinder): void; + } + + interface IMapFunction { + (element: ElementFinder, index: number): any; + } + + interface IFilterFunction { + (element: ElementFinder, index: number): webdriver.promise.Promise; + } + + interface IReductionFunction { + (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; } interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { @@ -587,69 +685,160 @@ declare module protractor { * Usage: * {{status}} * var status = element(by.binding('{{status}}')); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ binding(bindingDescriptor: string): webdriver.Locator; /** - * Usage: - * - * element(by.select("user")); + * Find an element by exact binding. + * + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ - select(model: string): webdriver.Locator; + exactBinding(bindingDescriptor: string): webdriver.Locator; /** + * + * Find an element by ng-model expression. + * * Usage: - * - * element(by.selectedOption("user")); - */ - selectedOption(model: string): webdriver.Locator; - - /** - * @DEPRECATED - use 'model' instead. - * Usage: - * - * element(by.input('user')); - */ - input(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.model('user')); + * + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + * @return {webdriver.Locator} */ model(model: string): webdriver.Locator; /** - * Usage: - * - * element(by.textarea("user")); - */ - textarea(model: string): webdriver.Locator; - - /** - * Usage: - *

- * {{cat.name}} - * {{cat.age}} - *
+ * Find a button by text. * - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater("cat in pets").row(2)); - * // Returns the SPAN for the first cat's name. - * var firstCatName = element( - * by.repeater("cat in pets").row(1).column("{{cat.name}}")); - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element( - * by.repeater("cat in pets").column("{{cat.age}}")); - * // Returns a promise that resolves to an array of WebElements containing - * // all rows of the repeater. - * var rows = element(by.repeater("cat in pets")); + * Usage: + * + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} */ - repeater(repeatDescriptor: string): webdriver.Locator; - buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * Usage: + * + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} + */ partialButtonText(searchText: string): webdriver.Locator; + + /** + * Find elements inside an ng-repeat. + * + * Usage: + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater('cat in pets').row(1)); + * + * // Returns the SPAN for the first cat's name. + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
    + *
  • Dog
  • + *
  • Cat
  • + *
+ * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + * + * @param cssSelector {string} + * @param searchText {string} + * @return {webdriver.Locator} + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * Usage: + * + * + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + * @return {webdriver.Locator} + */ + options(optionsDescriptor: string): webdriver.Locator; } var By: IProtractorLocatorStrategy; @@ -718,6 +907,43 @@ declare module protractor { //region Methods + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElement + * + * @param {webdriver.Locator} locator The locator used to find the element. + * @return {!webdriver.WebElement} + */ + findElement(locator: webdriver.Locator): protractor.WebElement; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElements + * + * @param {webdriver.Locator} locator The locator used to find the elements. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Tests if an element is present on the page. + * @see webdriver.WebDriver.isElementPresent + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + /** * Helper function for finding elements. * @@ -739,40 +965,71 @@ declare module protractor { */ $$(cssLocator: string): ElementArrayFinder; - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Wrap a webdriver.WebElement with protractor specific functionality. - * - * @param {webdriver.WebElement} element - * @return {protractor.WebElement} the wrapped web element. - */ - wrapWebElement(element: webdriver.WebElement): protractor.WebElement; - /** * Add a module to load before Angular whenever Protractor.get is called. * Modules will be registered after existing modules already on the page, * so any module registered here will override preexisting modules with the same * name. * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. + * @param {string} name The name of the module to load or override. + * @param {string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. */ - addMockModule(name: string, script: string): void; - addMockModule(name: string, script: any): void; + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: any, ...varArgs: any[]): void; /** * Clear the list of registered mock modules. */ clearMockModules(): void; + /** + * Remove a registered mock module. + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * See webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): void; + + /** + * Mixin navigation methods back into the navigation object so that + * they are invoked as before, i.e. driver.navigate().refresh() + */ + navigate(): webdriver.WebDriverNavigation; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + /** * Returns the current absolute url from AngularJS. */ @@ -799,43 +1056,14 @@ declare module protractor { debugger(): void; /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements - * are equivalent: - *

-         * var e1 = driver.findElement(By.id('foo'));
-         * var e2 = driver.findElement({id:'foo'});
-         * 
- * - *

When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual - * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. + * @param {=number} opt_debugPort Optional port to use for the debugging process */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + pause(opt_debugPort?: number): void; //endregion } @@ -863,9 +1091,19 @@ declare module protractor { } +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + declare var browser: protractor.Protractor; declare var by: protractor.IProtractorLocatorStrategy; declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; declare module 'protractor' { export = protractor; diff --git a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts new file mode 100644 index 000000000..dfd413d0e --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts @@ -0,0 +1,244 @@ +/// + +function TestWebDriverExports() { + var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); + var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; + + var button: protractor.Button = new protractor.Button(); + var baseButton: webdriver.Button = button; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); + var baseAlert: webdriver.Alert = alert; + + var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); + var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); + var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); + var baseLocator: webdriver.Locator = locator; + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + // logging module + + var levelName: string = protractor.logging.LevelName.ALL; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.Level = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + protractor.logging.Preferences = { a: 123 }; + + // promise module + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + protractor.promise.asap(promise, function(value: any){ return true; }); + protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(function() {}); + deferred = protractor.promise.defer(function(reason?: any) {}); + + promise = protractor.promise.delayed(123); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({a: 123}); + + promise = protractor.promise.fullyResolved({a: 123}); + + var isPromise: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({a: 123}); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + + // error module + + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; + + // process module + + var isNative: boolean = protractor.process.isNative(); + var value: string; + + value = protractor.process.getEnv('name'); + value = protractor.process.getEnv('name', 'default'); + + protractor.process.setEnv('name', 'value'); + protractor.process.setEnv('name', 123); + +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = new protractor.Protractor(driver); + ptor = new protractor.Protractor(driver, 'baseUrl'); + ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); + ptor = protractor.getInstance(); + protractor.setInstance(ptor); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + + ptor.debugger(); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); + + var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var promise: webdriver.promise.Promise; + + promise = elementFinder.click(); + promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + promise = elementFinder.getTagName(); + promise = elementFinder.getCssValue('display'); + promise = elementFinder.getAttribute('atribute'); + promise = elementFinder.getText(); + promise = elementFinder.getSize(); + promise = elementFinder.getLocation(); + promise = elementFinder.isEnabled(); + promise = elementFinder.isSelected(); + promise = elementFinder.submit(); + promise = elementFinder.clear(); + promise = elementFinder.isDisplayed(); + promise = elementFinder.getOuterHtml(); + promise = elementFinder.getInnerHtml(); + promise = elementFinder.isElementPresent(by.id('id')); + promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.findElements(by.className('class')); + promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$$('.class'); + promise = elementFinder.evaluate('expression'); + promise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement; + + webElement = elementFinder.$('.class'); + webElement = elementFinder.findElement(by.id('id')); + webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); + webElement = elementFinder.find(); +} + +// This function tests the angular specific locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = protractor.getInstance(); + var webElement: webdriver.WebElement; + + // Protractor Specific Locators + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.select('select')); + webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); + webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.textarea('textarea')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); +} + +// This function tests the methods that were added to the base WebElement class +function TestWebElements() { + var ptor: protractor.Protractor = protractor.getInstance(); + + var webElement: protractor.WebElement; + var promise: webdriver.promise.Promise; + + webElement = ptor.findElement(by.id('id')).$('.class'); + promise = ptor.findElement(by.id('id')).$$('.class'); + promise = ptor.findElement(by.id('id')).evaluate('something'); + + webElement = webElement.findElement(by.id('id')).$('.class'); + promise = webElement.findElement(by.id('id')).$$('.class'); + promise = webElement.findElement(by.id('id')).evaluate('something'); +} diff --git a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts new file mode 100644 index 000000000..38458b493 --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts @@ -0,0 +1,906 @@ +// Type definitions for Angular Protractor 0.17.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class AbstractBuilder extends webdriver.AbstractBuilder {} + class ActionSequence extends webdriver.ActionSequence {} + class Alert extends webdriver.Alert {} + class Builder extends webdriver.Builder {} + class Button extends webdriver.Button {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} + class Locator extends webdriver.Locator {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class Browser extends webdriver.Browser {} + class Capability extends webdriver.Capability {} + class CommandName extends webdriver.CommandName {} + class Key extends webdriver.Key {} + class UnhandledAlertError extends webdriver.UnhandledAlertError {} + + class WebElement extends webdriver.WebElement { + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + } + + module command { + class Command extends webdriver.Command {} + class CommandName extends webdriver.CommandName {} + } + + module error { + class Error extends webdriver.error.Error {} + class ErrorCode extends webdriver.error.ErrorCode {} + } + + module events { + class EventEmitter extends webdriver.EventEmitter {} + } + + module logging { + var Preferences: any; + + class LevelName extends webdriver.logging.LevelName {} + class Type extends webdriver.logging.Type {} + class Level extends webdriver.logging.Level {} + class Entry extends webdriver.logging.Entry {} + + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + } + + module promise { + class Promise extends webdriver.promise.Promise {} + class Deferred extends webdriver.promise.Deferred {} + class ControlFlow extends webdriver.promise.ControlFlow {} + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + //endregion + + interface Element { + (locator: webdriver.Locator): ElementFinder; + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder { + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} the descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} the descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + find(): protractor.WebElement; + + isPresent(): webdriver.promise.Promise; + } + + interface ElementArrayFinder{ + count(): webdriver.promise.Promise; + get(index: number): protractor.WebElement; + first(): protractor.WebElement; + last(): protractor.WebElement; + then(fn: (value: any) => any): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.()). + * + * @param {string} name + * @param {function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that begins with the element scoping the search, and then + * contains any args passed into the locator. It should return + * an array of elements. + */ + addLocator(name: string, script: any): void; + + /** + * Usage: + * {{status}} + * var status = element(by.binding('{{status}}')); + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.select("user")); + */ + select(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.selectedOption("user")); + */ + selectedOption(model: string): webdriver.Locator; + + /** + * @DEPRECATED - use 'model' instead. + * Usage: + * + * element(by.input('user')); + */ + input(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.model('user')); + */ + model(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.textarea("user")); + */ + textarea(model: string): webdriver.Locator; + + /** + * Usage: + *

+ * {{cat.name}} + * {{cat.age}} + *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater("cat in pets").row(2)); + * // Returns the SPAN for the first cat's name. + * var firstCatName = element( + * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element( + * by.repeater("cat in pets").column("{{cat.age}}")); + * // Returns a promise that resolves to an array of WebElements containing + * // all rows of the repeater. + * var rows = element(by.repeater("cat in pets")); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + buttonText(searchText: string): webdriver.Locator; + + partialButtonText(searchText: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + class Protractor extends webdriver.WebDriver { + + //region Constructors + + /** + * @param {webdriver.WebDriver} webdriver + * @param {string=} opt_baseUrl A base URL to run get requests against. + * @param {string=body} opt_rootElement Selector element that has an ng-app in + * scope. + * @constructor + */ + constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); + + //endregion + + //region Properties + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + //endregion + + //region Methods + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Helper function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(cssLocator: string): ElementFinder; + + /** + * Helper function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(cssLocator: string): ElementArrayFinder; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Wrap a webdriver.WebElement with protractor specific functionality. + * + * @param {webdriver.WebElement} element + * @return {protractor.WebElement} the wrapped web element. + */ + wrapWebElement(element: webdriver.WebElement): protractor.WebElement; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + */ + addMockModule(name: string, script: string): void; + addMockModule(name: string, script: any): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + + //endregion + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; + + /** + * Set a singleton instance of protractor. + * @param {Protractor} ptor + */ + function setInstance(ptor: Protractor): void; + + /** + * Get the singleton instance. + * @return {Protractor} + */ + function getInstance(): Protractor; + +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +declare var browser: protractor.Protractor; +declare var by: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssSelectorHelper; + +declare module 'protractor' { + export = protractor; +} From a5c374e96a57b59df69a78de61df0f4eac6c95f3 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Tue, 15 Jul 2014 17:09:59 -0700 Subject: [PATCH 026/277] Fix JQueryUI Slider definitions --- jqueryui/jqueryui.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 26492bf20..26e2d6cdc 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -609,11 +609,14 @@ declare module JQueryUI { orientation?: string; range?: any; // boolean or string step?: number; - // value?: number; - // values?: number[]; + value?: number; + values?: number[]; } interface SliderUIParams { + handle?: JQuery; + value?: number; + values?: number[]; } interface SliderEvent { From b41dc8fe9c5bb19d8bf0c1a7d5f187dccbd60c4e Mon Sep 17 00:00:00 2001 From: NewNotMoon Date: Wed, 16 Jul 2014 09:13:55 +0900 Subject: [PATCH 027/277] add jquery.pjax.falsandtru --- CONTRIBUTORS.md | 1 + jquery.pjax.falsandtru/jquery.pjax-tests.ts | 96 ++++++++++ jquery.pjax.falsandtru/jquery.pjax.d.ts | 189 ++++++++++++++++++++ 3 files changed, 286 insertions(+) create mode 100644 jquery.pjax.falsandtru/jquery.pjax-tests.ts create mode 100644 jquery.pjax.falsandtru/jquery.pjax.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 0fa132294..ef4467f22 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -164,6 +164,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](https://new.not-moon.net/)) * [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) * [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) * [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) diff --git a/jquery.pjax.falsandtru/jquery.pjax-tests.ts b/jquery.pjax.falsandtru/jquery.pjax-tests.ts new file mode 100644 index 000000000..fd8cbaecd --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax-tests.ts @@ -0,0 +1,96 @@ +/// +/// + +function test_pjax() { + $.pjax(); +} + +function test_pjax_selector() { + $('a').pjax(); +} + +function test_pjax_option() { + $.pjax({ + area: 'body', + load: { + head: 'base, meta, link', + css: true, + script: true + }, + cache: { click: true, submit: false, popstate: true }, + server: { query: null } + }); +} + +function test_pjax_event() { + $.pjax({ + wait: 1000 + }); + $(document).bind('pjax.request', function () { + $('div.loading').fadeIn(100); + }); + $(document).bind('pjax.render', function () { + $('div.loading').fadeOut(500); + }); +} + +function test_pjax_progressbar() { + $('body').append('

'); + $.pjax({ + area: 'div.pjax', + callbacks: { + before: function () { + $('div.loading').children().width(''); + $('div.loading').fadeIn(0); + }, + ajax: { + xhr: function () { + var xhr = jQuery.ajaxSettings.xhr(); + + $('div.loading').children().width('5%'); + if (xhr instanceof Object && 'onprogress' in xhr) { + xhr.addEventListener('progress', function (event) { + var percentage = event.total ? event.loaded / event.total : 0.4; + percentage = percentage * 90 + 5; + $('div.loading').children().width(percentage + '%'); + }, false); + xhr.addEventListener('load', function (event) { + $('div.loading').children().width('95%'); + }, false); + xhr.addEventListener('error', function (event) { + $('div.loading').children().css('background-color', '#00f'); + }, false); + } + return xhr; + } + }, + update: { + content: { + after: function () { + $('div.loading').children().width('96.25%'); + } + }, + css: { + after: function () { + $('div.loading').children().width('97.5%'); + } + }, + script: { + after: function () { + $('div.loading').children().width('98.75%'); + } + }, + render: { + after: function () { + $('div.loading').children().width('100%'); + $('div.loading').fadeOut(50); + } + } + } + }, + ajax: { timeout: 3000 }, + wait: 1000 + }); +} \ No newline at end of file diff --git a/jquery.pjax.falsandtru/jquery.pjax.d.ts b/jquery.pjax.falsandtru/jquery.pjax.d.ts new file mode 100644 index 000000000..07bc153df --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax.d.ts @@ -0,0 +1,189 @@ +// Type definitions for jquery.pjax.ts by falsandtru +// Project: https://github.com/falsandtru/jquery.pjax.js/ +// Definitions by: 新ゝ月 NewNotMoon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface PjaxSetting { + gns?: string; + ns?: string; + area?: any; // string, array, function( event, param, origUrl, destUrl ) + link?: string; + filter?: any; // string, function() + form?: string; + scope?: Object; + state?: any; // any, function(event, param, origUrl, destUrl ) + scrollTop?: any; // number, function( event, param, origUrl, destUrl ), null, false + scrollLeft?: any; // number, function( event, param, origUrl, destUrl ), null, false + scroll?: { + delay?: number; + record?: boolean //internal + queue?: number[] //internal + }; + ajax?: JQueryAjaxSettings; + contentType?: string; + load?: { + head?: string; + css?: boolean; + script?: boolean; + execute?: boolean; + reload?: string; + ignore?: string; + sync?: boolean; + ajax?: JQueryAjaxSettings; + rewrite?: (element: any) => any; + redirect?: boolean; + }; + interval?: number; + cache?: { + click?: boolean; + submit?: boolean; + popstate?: boolean; + get?: boolean; + post?: boolean; + page?: boolean; + size?: number; + mix?: number; + expires?: { + min?: number; + max?: number; + }; + }; + wait?: any; // number, function( event, param, origUrl, destUrl ): number + fallback?: any; // boolean, function( event, param, origUrl, destUrl ): boolean + fix?: { + location?: boolean; + history?: boolean; + scroll?: boolean; + reset?: boolean; + }; + database?: boolean; + server?: { + query?: any; // string, object + header?: { + area?: boolean; + head?: boolean; + css?: boolean; + script?: boolean; + }; + }; + callback?: (event: JQueryEventObject, param: any) => any; + callbacks?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + ajax?: { + xhr?: (event: JQueryEventObject, param: any) => any; + beforeSend?: (event: JQueryEventObject, param: any, data: any, ajaxSettings: any) => any; + dataFilter?: (event: JQueryEventObject, param: any, data: any, dataType: any) => any; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + complete?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + done?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + fail?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + always?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + }; + update?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + cache?: { + before?: (event: JQueryEventObject, param: any, cache: any) => any; + after?: (event: JQueryEventObject, param: any, cache: any) => any; + }; + redirect?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + url?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + title?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + head?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + content?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + scroll?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + css?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + script?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + render?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + verify?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + complete?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + param?: any; + + // internal + uuid?: string; + nss?: { + name?: string; + event?: string[]; + click?: string; + submit?: string; + popstate?: string; + scroll?: string; + data?: string; + class4html?: string; + requestHeader?: string; + }; + origLocation?: HTMLAnchorElement; + destLocation?: HTMLAnchorElement; + retry?: boolean; + speedcheck?: boolean; + disable?: boolean; + option?: any; + }; +} + +interface JQueryStatic { + pjax: { + (setting?: PjaxSetting): any; + enable(): any; + disable(): any; + click(url: string, attr: { href?: string; }): any; + click(url: HTMLAnchorElement, attr: { href?: string; }): any; + click(url: JQuery, attr: { href?: string; }): any; + click(url: any, attr: { href?: string; }): any; + submit(url: string, attr: { action?: string; method?: string; }, data: any): any; + submit(url: HTMLFormElement, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: JQuery, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: any, attr?: { action?: string; method?: string; }, data?: any): any; + follow(event: JQueryEventObject, ajax: JQueryXHR, timeStamp?: number): boolean; + setCache(): any; + setCache(url: string): any; + setCache(url: string, data: string): any; + setCache(url: string, data: string, textStatus: string, XMLHttpRequest: XMLHttpRequest): any; + getCache(): any; + getCache(url: string): any; + removeCache(url: string): any; + removeCache(): any; + clearCache(): any; + }; +} + +interface JQuery { + pjax(setting?: PjaxSetting): any; +} \ No newline at end of file From e65feae2035aa410b1462a51f5bb8fd54a57d9cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E3=82=9D=E6=9C=88?= Date: Wed, 16 Jul 2014 10:08:56 +0900 Subject: [PATCH 028/277] Update jquery.pjax-tests.ts --- jquery.pjax.falsandtru/jquery.pjax-tests.ts | 61 --------------------- 1 file changed, 61 deletions(-) diff --git a/jquery.pjax.falsandtru/jquery.pjax-tests.ts b/jquery.pjax.falsandtru/jquery.pjax-tests.ts index fd8cbaecd..18eae623c 100644 --- a/jquery.pjax.falsandtru/jquery.pjax-tests.ts +++ b/jquery.pjax.falsandtru/jquery.pjax-tests.ts @@ -33,64 +33,3 @@ function test_pjax_event() { $('div.loading').fadeOut(500); }); } - -function test_pjax_progressbar() { - $('body').append(''); - $.pjax({ - area: 'div.pjax', - callbacks: { - before: function () { - $('div.loading').children().width(''); - $('div.loading').fadeIn(0); - }, - ajax: { - xhr: function () { - var xhr = jQuery.ajaxSettings.xhr(); - - $('div.loading').children().width('5%'); - if (xhr instanceof Object && 'onprogress' in xhr) { - xhr.addEventListener('progress', function (event) { - var percentage = event.total ? event.loaded / event.total : 0.4; - percentage = percentage * 90 + 5; - $('div.loading').children().width(percentage + '%'); - }, false); - xhr.addEventListener('load', function (event) { - $('div.loading').children().width('95%'); - }, false); - xhr.addEventListener('error', function (event) { - $('div.loading').children().css('background-color', '#00f'); - }, false); - } - return xhr; - } - }, - update: { - content: { - after: function () { - $('div.loading').children().width('96.25%'); - } - }, - css: { - after: function () { - $('div.loading').children().width('97.5%'); - } - }, - script: { - after: function () { - $('div.loading').children().width('98.75%'); - } - }, - render: { - after: function () { - $('div.loading').children().width('100%'); - $('div.loading').fadeOut(50); - } - } - } - }, - ajax: { timeout: 3000 }, - wait: 1000 - }); -} \ No newline at end of file From 98077b3ab84ddfbb7be526bd7adb3a116ef58db0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E3=82=9D=E6=9C=88?= Date: Wed, 16 Jul 2014 22:11:18 +0900 Subject: [PATCH 029/277] Update CONTRIBUTORS.md Sorry, I was writing the wrong URL. --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ef4467f22..c01d01147 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -164,7 +164,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) -* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](https://new.not-moon.net/)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](http://new.not-moon.net/)) * [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) * [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) * [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) From ad8d43a73b3f5c2302abba8cb5666c8a3f7370fc Mon Sep 17 00:00:00 2001 From: Zalim Bashorov Date: Wed, 16 Jul 2014 23:39:39 +0400 Subject: [PATCH 030/277] Remove extra declaration of Em.Handlebars.compile in ember.d.ts --- ember/ember.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/ember/ember.d.ts b/ember/ember.d.ts index bbb555e8a..2a0b35e42 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -2235,7 +2235,6 @@ declare module Em { var print: typeof Ember.Handlebars.print; var logger: typeof Ember.Handlebars.logger; var log: typeof Ember.Handlebars.log; - var compile: typeof Ember.Handlebars.compile; } class HashLocation extends Ember.HashLocation { } class HistoryLocation extends Ember.HistoryLocation { } From 84f63e9cc3917650186dc88c996bad5436311405 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 16 Jul 2014 13:27:04 -0700 Subject: [PATCH 031/277] 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 213d8c7da7b69e6507659f96305ded3af66ffd28 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 15:31:44 -0700 Subject: [PATCH 032/277] Adding back Backbone.$ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit http://backbonejs.org/#Utility-Backbone-$ Also removed `setDomLibrary` Backbone change log 0.9.9 — Dec. 13, 2012: To set what library Backbone uses for DOM manipulation and Ajax calls, use `Backbone.$ = ...` instead of `setDomLibrary`. --- backbone/backbone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index db104f480..f23a4995a 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -359,7 +359,7 @@ declare module Backbone { // Utility function noConflict(): typeof Backbone; - function setDomLibrary(jQueryNew: any): any; + var $: JQueryStatic; } declare module "backbone" { From c743233ab0ae2955158f47f41fc231ec63dd69d0 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 16:08:00 -0700 Subject: [PATCH 033/277] Overloads for Collection.get method --- backbone/backbone.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index f23a4995a..6b390e83e 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -170,7 +170,12 @@ declare module Backbone { add(model: TModel, options?: AddOptions): Collection; add(models: TModel[], options?: AddOptions): Collection; at(index: number): TModel; + /** + * Get a model from a collection, specified by an id, a cid, or by passing in a model. + **/ + get(id: number): TModel; get(id: string): TModel; + get(id: Model): TModel; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; From 06392eab9487e17a43bc251e5e2688d76e258a9a Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 16:12:00 -0700 Subject: [PATCH 034/277] How to access attributes in a strongly-typed manner Only added comments and examples --- backbone/backbone.d.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 6b390e83e..d8bdc71c9 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -113,8 +113,23 @@ declare module Backbone { fetch(options?: ModelFetchOptions): JQueryXHR; - get(attributeName: string): any; - set(attributeName: string, value: any, options?: ModelSetOptions): Model; + /** + * For strongly-typed access to attributes, use the `get` method only privately in public getter properties. + * @example + * get name(): string { + * return super.get("name"); + * } + **/ + /*private*/ get(attributeName: string): any; + + /** + * For strongly-typed assignment of attributes, use the `set` method only privately in public setter properties. + * @example + * set name(value: string) { + * super.set("name", value); + * } + **/ + /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; change(): any; From d205eb87269a1266e867b4e95bd85a66524e6cc0 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 18:32:07 -0700 Subject: [PATCH 035/277] Updated collection tests and added comments --- backbone/backbone-tests.ts | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 6b40bb509..e3fbd6ab8 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -113,9 +113,12 @@ class EmployeeCollection extends Backbone.Collection { class Book extends Backbone.Model { title: string; author: string; + published: boolean; } class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. model: typeof Book; } @@ -123,31 +126,26 @@ class Books extends Backbone.Collection { } function test_collection() { - var books = new Library(); + var books = new Books(); - books.each(book => { - book.get("title"); - }); + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); - var titles = books.map(book => { - return book.get("title"); - }); - - var publishedBooks = books.filter(book => { - return book.get("published") === true; - }); - - var alphabetical = books.sortBy((book: Book): number => { - return null; - }); - - var model: Book = new Book({title: "Test", author: "Mike"}); - books.add(model); - var model2: Book = model.collection.first(); - if (model !== model2) { + var model: Book = book1.collection.first(); + if (model !== book1) { throw new Error("Error"); } + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); } ////////// From c18eb2ad641d2bb611416eaa75b4f922f0c13c42 Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Wed, 16 Jul 2014 19:42:09 -0700 Subject: [PATCH 036/277] Added test for adding object literals as models --- backbone/backbone-tests.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index e3fbd6ab8..506fd7bb6 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -131,6 +131,11 @@ function test_collection() { var book1: Book = new Book({ title: "Title 1", author: "Mike" }); books.add(book1); + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); + var model: Book = book1.collection.first(); if (model !== book1) { throw new Error("Error"); From 14fdf0edc6c4ea52d1096b4f508a24a93871c09f Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:12:44 +0100 Subject: [PATCH 037/277] 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 038/277] 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 b09ee215ec421b7ed51ba44b90c8d0f5f25b3cf3 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 17 Jul 2014 21:21:02 +0900 Subject: [PATCH 039/277] Add definitions for ProgressJs --- CONTRIBUTORS.md | 1 + progressjs/progress-tests.ts | 36 ++++++++++++ progressjs/progress.d.ts | 103 +++++++++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 progressjs/progress-tests.ts create mode 100644 progressjs/progress.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c01d01147..456dbc9ce 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -271,6 +271,7 @@ All definitions files include a header with the author and editors, so at some p * [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) * [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)) * [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)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) diff --git a/progressjs/progress-tests.ts b/progressjs/progress-tests.ts new file mode 100644 index 000000000..e2ab62f9a --- /dev/null +++ b/progressjs/progress-tests.ts @@ -0,0 +1,36 @@ +/// + +progressJs(); //without selector, set progress-bar for whole page +progressJs("#targetElement"); //start progress-bar for element id='targetElement' + +progressJs().start(); + +progressJs().set(20); //set progress to 20% + +progressJs().start().autoIncrease(4, 500); //every 500 milliseconds, percentage + 4 + +progressJs().increase(); //increase one percent +progressJs().increase(2); //increase two percent + +progressJs().start().set(20).end(); + +progressJs().setOption("theme", "black"); +progressJs().setOption("overlayMode", true); +progressJs().setOption("considerTransition", false); + +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true, 'considerTransition': false }); +progressJs().setOptions({ 'overlayMode': true }); + +progressJs().onbeforeend(function() { + alert("before end"); +}); + +progressJs().onbeforestart(function() { + alert("before start"); +}); + +progressJs().onprogress(function(targetElm, percent) { + alert("progress changed to:" + percent); +}); diff --git a/progressjs/progress.d.ts b/progressjs/progress.d.ts new file mode 100644 index 000000000..a7f9923c3 --- /dev/null +++ b/progressjs/progress.d.ts @@ -0,0 +1,103 @@ +// Type definitions for ProgressJs v0.1.0 +// Project: http://usablica.github.io/progress.js/ +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface ProgressJsStatic { + + /** + * Creating an ProgressJS object. + * + * @param targetElm String (optional) Should be defined to start progress-bar for specific element. + */ + (targetElm?: string): ProgressJs; +} + +interface ProgressJs { + + /** + * Start the progress-bar for defined element(s). + */ + start(): ProgressJs; + + /** + * Set specific percentage to progress-bar. + * + * @param percent Set to specific percentage. + */ + set(percent: number): ProgressJs; + + /** + * Set an auto-increase timer for the progress-bar. + * + * @param size The size of increment when timer elapsed. + * @param millisecond Timer in milliseconds. + */ + autoIncrease(size: number, millisecond: number): ProgressJs; + + /** + * Increase the progress-bar bar specified size. Default size is 1. + * + * @param size The size of increment. + */ + increase(size?: number): ProgressJs; + + /** + * End the progress-bar and remove the elements from page. + */ + end(): ProgressJs; + + /** + * Set a single option to progressJs object. + * + * @param option Option key name. + * @param value Value of the option. + */ + setOption(option: string, value: string): ProgressJs; + setOption(option: string, value: boolean): ProgressJs; + + /** + * Set a group of options to the progressJs object. + * + * @param options Object that contains option keys with values. + */ + setOptions(options: ProgressJsOptions): ProgressJs; + + /** + * Set a callback function for before end of the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforeend(providedCallback: () => any): ProgressJs; + + /** + * Set a callback function to call before start the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforestart(providedCallback: () => any): ProgressJs; + + /** + * Set callback function to call for each change of progress-bar. + * + * @param providedCallback Callback function. + */ + onprogress(providedCallback: (targetElement: string, percent: number) => any): ProgressJs; +} + +interface ProgressJsOptions { + /** + * progress bar theme + */ + theme?: string; + /** + * overlay mode makes an overlay layer in the target element + */ + overlayMode?: boolean; + /** + * to consider CSS3 transitions in events + */ + considerTransition?: boolean; +} + +declare var progressJs: ProgressJsStatic From 43f1770f23c542e5b07b102f6f2b7fbf58eb82d8 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:22:10 +0100 Subject: [PATCH 040/277] 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 041/277] 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 bc8bc17374d87764fb6338f67ac12940f0ffc0c4 Mon Sep 17 00:00:00 2001 From: Ian Sibner Date: Thu, 17 Jul 2014 11:30:43 -0400 Subject: [PATCH 042/277] Changes based on @BillArmstrong's feedback * Remove optional parameters from Element interface * Remove additional parameters from ElementFinder.isElementPresent * Add "asElementFinders_" and "then" methods to ElementArrayFinder interface --- .../angular-protractor-tests.ts | 5 +- angular-protractor/angular-protractor.d.ts | 71 +++++++++++-------- 2 files changed, 47 insertions(+), 29 deletions(-) diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 62ed46177..5ca9ecde4 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -211,7 +211,6 @@ function TestElementFinder() { promise = elementFinder.getOuterHtml(); promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); @@ -230,6 +229,7 @@ function TestElementArrayFinder() { elementFinder = elementArrayFinder.first(); elementFinder = elementArrayFinder.last(); promise = elementArrayFinder.count(); + promise = elementArrayFinder.asElementFinders_(); elementArrayFinder.each(function(element: protractor.ElementFinder){ // nothing }); @@ -251,6 +251,9 @@ function TestElementArrayFinder() { return accumulator + ',' + text; }); }, ''); + elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ + //nothing + }); } // This function tests the angular specific locator strategies. diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 81eca975e..2de49a0a4 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -225,31 +225,19 @@ declare module protractor { * before the page is available. * * @param {webdriver.Locator} locator An element locator. - * @param {ElementFinder=} opt_parentElementFinder The element finder previous - * to this. (i.e. opt_parentElementFinder.element(locator) => this) - * @param {webdriver.promise.Promise} opt_actionResult The promise which - * will be retrieved with then. Resolves to the latest action result, - * or null if no action has been called. - * @param {number=} opt_index The index of the element to retrieve. null means - * retrieve the only element, while -1 means retrieve the last element * @return {ElementFinder} */ interface Element { - (locator: webdriver.Locator, - opt_parentElementFinder?: protractor.ElementFinder, - opt_actionResult?: webdriver.promise.Promise, - opt_index?: number): ElementFinder; + (locator: webdriver.Locator): ElementFinder; /** * ElementArrayFinder is used for operations on an array of elements (as opposed * to a single element). * * @param {webdriver.Locator} locator An element locator. - * @param {ElementFinder=} opt_parentElementFinder The element finder previous to - * this. (i.e. opt_parentElementFinder.all(locator) => this) * @return {ElementArrayFinder} */ - all(locator: webdriver.Locator, opt_parentElementFinder?: protractor.ElementFinder): ElementArrayFinder; + all(locator: webdriver.Locator): ElementArrayFinder; } interface ElementFinder { @@ -301,21 +289,13 @@ declare module protractor { isPresent(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @see ElementFinder.isPresent + * @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page. */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise; /** * Return this ElementFinder's locator. @@ -552,7 +532,7 @@ declare module protractor { } interface IThenFunction { - (promise: webdriver.promise.Promise): any; + (promiseResult: any): any; } @@ -641,6 +621,37 @@ declare module protractor { * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. */ reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array) + * of ElementFinders specified by the locator. + */ + asElementFinders_(): webdriver.promise.Promise; + + + /** + * Find the elements specified by the locator. The input function is passed + * to the resulting promise, which resolves to an array of ElementFinders. + * + * Use as: element.all(locator).then(thenFunction) + *

    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * element.all(by.css('.items li')).then(function(arr) { + * expect(arr.length).toEqual(3); + * }); + * + * @param {function(Array.)} fn + * + * @type {webdriver.promise.Promise} a promise which will resolve to + * an array of ElementFinders matching the locator. + */ + then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise; } interface IEachFunction { @@ -659,6 +670,10 @@ declare module protractor { (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; } + interface IElementArrayFinderThenFunction { + (promiseResult: ElementFinder[]): any; + } + class LocatorWithColumn extends webdriver.Locator { column(index: number): webdriver.Locator; } From c7cb7f5ceaa6eba0e18f4b4c8d67af833cd34ee5 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:17:47 +0100 Subject: [PATCH 043/277] 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 044/277] 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 045/277] 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 046/277] 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 44ace5c6602c18d5301b23c66d197bb97a086d68 Mon Sep 17 00:00:00 2001 From: Tom Hasner Date: Thu, 17 Jul 2014 18:04:10 -0400 Subject: [PATCH 047/277] added second argument "element" to $.filter --- jquery/jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 59159a188..eb6ec2e56 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -3655,7 +3655,7 @@ interface JQuery { * * @param func A function used as a test for each element in the set. this is the current DOM element. */ - filter(func: (index: number) => any): JQuery; + filter(func: (index: number, element: Element) => any): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. * From c9370c43268664be14a67f139137c8cc7affa71a Mon Sep 17 00:00:00 2001 From: Kensuke Matsuzaki Date: Fri, 18 Jul 2014 14:45:24 +0900 Subject: [PATCH 048/277] Fix jQuery BlockUI Plugin --- jquery.blockUI/jquery.blockUI-tests.ts | 14 ++++++++++++++ jquery.blockUI/jquery.blockUI.d.ts | 10 +++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/jquery.blockUI/jquery.blockUI-tests.ts b/jquery.blockUI/jquery.blockUI-tests.ts index 19372976f..234340b93 100644 --- a/jquery.blockUI/jquery.blockUI-tests.ts +++ b/jquery.blockUI/jquery.blockUI-tests.ts @@ -9,3 +9,17 @@ $.blockUI(opt); $.unblockUI(); $("#test").block().unblock(); $("#test").block(opt); + +$.blockUI.defaults.css.border = '5px solid red'; +$.blockUI.defaults.fadeOut = 200; + +$.blockUI({ message: $('#domMessage') }); +$.unblockUI({ fadeOut: 200 }); + +$.blockUI({ + fadeIn: 1000, + timeout: 2000, + onBlock: function() { + alert('Page is now blocked; fadeIn complete'); + } +}); diff --git a/jquery.blockUI/jquery.blockUI.d.ts b/jquery.blockUI/jquery.blockUI.d.ts index 5b1df3f7b..259044eaf 100644 --- a/jquery.blockUI/jquery.blockUI.d.ts +++ b/jquery.blockUI/jquery.blockUI.d.ts @@ -7,7 +7,7 @@ interface JQBlockUIOptions { /** message displayed when blocking (use null for no message) */ - message?: string; + message?: any; /** title string; only used when theme == true */ title?: string; /** only used when theme == true (requires jquery-ui.js to be loaded) */ @@ -76,7 +76,7 @@ interface JQBlockUIOptions { focusInput?: boolean; /** callback method invoked when fadeIn has completed and blocking message is visible */ - onBlock?: boolean; + onBlock?: () => void; /** * callback method invoked when unblocking has completed; the callback is @@ -99,7 +99,7 @@ interface JQBlockUIOptions { interface JQBlockUIStatic { /** default options */ - default?: JQBlockUIOptions; + defaults?: JQBlockUIOptions; /** block user activity for the page */ (): void; /** @@ -113,7 +113,7 @@ interface JQueryStatic { /** block user activity for the page */ blockUI?: JQBlockUIStatic; /** unblock the page */ - unblockUI?: () => void; + unblockUI?: JQBlockUIStatic; } interface JQuery { @@ -125,5 +125,5 @@ interface JQuery { /** * unblock the element(s) */ - unblock(): JQuery; + unblock(option?: JQBlockUIOptions): JQuery; } \ No newline at end of file From dfab9f569d2233725c375fd17841ff4b649685b0 Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Sat, 19 Jul 2014 05:11:42 +0200 Subject: [PATCH 049/277] moved chai-assert into main chai definition renamed chai-fuzzy-assert to chai-fuzzy --- chai-datetime/chai-datetime-tests.ts | 4 +- ...chai-fuzzy-assert.d.ts => chai-fuzzy.d.ts} | 4 +- ...ts.tscparams => chai-fuzzy.d.ts.tscparams} | 0 chai/chai-assert-tests.ts | 655 ------------------ chai/chai-assert.d.ts | 131 ---- chai/chai-tests.ts | 621 +++++++++++++++++ chai/chai.d.ts | 117 +++- 7 files changed, 741 insertions(+), 791 deletions(-) rename chai-fuzzy/{chai-fuzzy-assert.d.ts => chai-fuzzy.d.ts} (91%) rename chai-fuzzy/{chai-fuzzy-assert.d.ts.tscparams => chai-fuzzy.d.ts.tscparams} (100%) delete mode 100644 chai/chai-assert-tests.ts delete mode 100644 chai/chai-assert.d.ts diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts index 0b7ff729f..8f8238b4e 100644 --- a/chai-datetime/chai-datetime-tests.ts +++ b/chai-datetime/chai-datetime-tests.ts @@ -1,8 +1,8 @@ /// -/// /// var expect = chai.expect; +var assert = chai.assert; function test_equalTime(){ var date: Date = new Date(2014, 1, 1); @@ -44,4 +44,4 @@ function test_afterDate(){ expect(date).to.afterDate(date); date.should.afterDate(date); assert.afterDate(date, date); -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts b/chai-fuzzy/chai-fuzzy.d.ts similarity index 91% rename from chai-fuzzy/chai-fuzzy-assert.d.ts rename to chai-fuzzy/chai-fuzzy.d.ts index f75f99d55..0cbb1741b 100644 --- a/chai-fuzzy/chai-fuzzy-assert.d.ts +++ b/chai-fuzzy/chai-fuzzy.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module chai { interface Assert { @@ -14,4 +14,4 @@ declare module chai { jsonOf(act:any, exp:any, msg?:string); notJsonOf(act:any, exp:any, msg?:string); } -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams b/chai-fuzzy/chai-fuzzy.d.ts.tscparams similarity index 100% rename from chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams rename to chai-fuzzy/chai-fuzzy.d.ts.tscparams diff --git a/chai/chai-assert-tests.ts b/chai/chai-assert-tests.ts deleted file mode 100644 index 4dc430f0c..000000000 --- a/chai/chai-assert-tests.ts +++ /dev/null @@ -1,655 +0,0 @@ -/* - ---------- - test extracted from original test suite - chai original licence follows ---------- - -## License - -(The MIT License) - -Copyright (c) 2011-2013 Jake Luer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -/// - -//stubs - -//tdd -declare function suite(description: string, action: Function):void; -declare function test(description: string, action: Function):void; -declare function err(action: any, msg?: string):void; -interface FieldObj { - field: any; -} -class Foo { - constructor() { - - } -} - -class CrashyObject { - inspect (): void { - throw new Error("Arg's inspect() called even though the test passed"); - } -} - -suite('assert', function () { - - test('assert', function () { - var foo = 'bar'; - assert(foo == 'bar', "expected foo to equal `bar`"); - - err(function () { - assert(foo == 'baz', "expected foo to equal `bar`"); - }, "expected foo to equal `bar`"); - }); - - test('isTrue', function () { - assert.isTrue(true); - - err(function () { - assert.isTrue(false); - }, "expected false to be true"); - - err(function () { - assert.isTrue(1); - }, "expected 1 to be true"); - - err(function () { - assert.isTrue('test'); - }, "expected 'test' to be true"); - }); - - test('ok', function () { - assert.ok(true); - assert.ok(1); - assert.ok('test'); - - err(function () { - assert.ok(false); - }, "expected false to be truthy"); - - err(function () { - assert.ok(0); - }, "expected 0 to be truthy"); - - err(function () { - assert.ok(''); - }, "expected '' to be truthy"); - }); - - test('isFalse', function () { - assert.isFalse(false); - - err(function () { - assert.isFalse(true); - }, "expected true to be false"); - - err(function () { - assert.isFalse(0); - }, "expected 0 to be false"); - }); - - test('equal', function () { - var foo: any; - assert.equal(foo, undefined); - }); - - test('typeof / notTypeOf', function () { - assert.typeOf('test', 'string'); - assert.typeOf(true, 'boolean'); - assert.typeOf(5, 'number'); - - err(function () { - assert.typeOf(5, 'string'); - }, "expected 5 to be a string"); - - }); - - test('notTypeOf', function () { - assert.notTypeOf('test', 'number'); - - err(function () { - assert.notTypeOf(5, 'number'); - }, "expected 5 not to be a number"); - }); - - test('instanceOf', function () { - assert.instanceOf(new Foo(), Foo); - - err(function () { - assert.instanceOf(5, Foo); - }, "expected 5 to be an instance of Foo"); - assert.instanceOf(new CrashyObject(), CrashyObject); - }); - - test('notInstanceOf', function () { - assert.notInstanceOf(new Foo(), String); - - err(function () { - assert.notInstanceOf(new Foo(), Foo); - }, "expected {} to not be an instance of Foo"); - }); - - test('isObject', function () { - assert.isObject({}); - assert.isObject(new Foo()); - - err(function () { - assert.isObject(true); - }, "expected true to be an object"); - - err(function () { - assert.isObject(Foo); - }, "expected [Function: Foo] to be an object"); - - err(function () { - assert.isObject('foo'); - }, "expected 'foo' to be an object"); - }); - - test('isNotObject', function () { - assert.isNotObject(5); - - err(function () { - assert.isNotObject({}); - }, "expected {} not to be an object"); - }); - - test('notEqual', function () { - assert.notEqual(3, 4); - - err(function () { - assert.notEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('strictEqual', function () { - assert.strictEqual('foo', 'foo'); - - err(function () { - assert.strictEqual('5', 5); - }, "expected \'5\' to equal 5"); - }); - - test('notStrictEqual', function () { - assert.notStrictEqual(5, '5'); - - err(function () { - assert.notStrictEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('deepEqual', function () { - assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); - - err(function () { - assert.deepEqual({tea: 'chai'}, {tea: 'black'}); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - - var obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); - - assert.deepEqual(obja, objb); - - var obj1 = Object.create({tea: 'chai'}) - , obj2 = Object.create({tea: 'black'}); - - err(function () { - assert.deepEqual(obj1, obj2); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - }); - - test('deepEqual (ordering)', function () { - var a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; - assert.deepEqual(a, b); - }); - - test('deepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = {}; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.deepEqual(circularObject, secondCircularObject); - - err(function () { - secondCircularObject.field2 = secondCircularObject; - assert.deepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); - }); - - test('notDeepEqual', function () { - assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); - err(function () { - assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); - }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); - }); - - test('notDeepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = { tea: 'jasmine' }; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.notDeepEqual(circularObject, secondCircularObject); - - err(function () { - delete secondCircularObject.tea; - assert.notDeepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); - }); - - test('isNull', function () { - assert.isNull(null); - - err(function () { - assert.isNull(undefined); - }, "expected undefined to equal null"); - }); - - test('isNotNull', function () { - assert.isNotNull(undefined); - - err(function () { - assert.isNotNull(null); - }, "expected null to not equal null"); - }); - - test('isUndefined', function () { - assert.isUndefined(undefined); - - err(function () { - assert.isUndefined(null); - }, "expected null to equal undefined"); - }); - - test('isDefined', function () { - assert.isDefined(null); - - err(function () { - assert.isDefined(undefined); - }, "expected undefined to not equal undefined"); - }); - - test('isFunction', function () { - var func = function () { - }; - assert.isFunction(func); - - err(function () { - assert.isFunction({}); - }, "expected {} to be a function"); - }); - - test('isNotFunction', function () { - assert.isNotFunction(5); - - err(function () { - assert.isNotFunction(function () { - }); - }, "expected [Function] not to be a function"); - }); - - test('isArray', function () { - assert.isArray([]); - assert.isArray(new Array()); - - err(function () { - assert.isArray({}); - }, "expected {} to be an array"); - }); - - test('isNotArray', function () { - assert.isNotArray(3); - - err(function () { - assert.isNotArray([]); - }, "expected [] not to be an array"); - - err(function () { - assert.isNotArray(new Array()); - }, "expected [] not to be an array"); - }); - - test('isString', function () { - assert.isString('Foo'); - assert.isString(new String('foo')); - - err(function () { - assert.isString(1); - }, "expected 1 to be a string"); - }); - - test('isNotString', function () { - assert.isNotString(3); - assert.isNotString([ 'hello' ]); - - err(function () { - assert.isNotString('hello'); - }, "expected 'hello' not to be a string"); - }); - - test('isNumber', function () { - assert.isNumber(1); - assert.isNumber(Number('3')); - - err(function () { - assert.isNumber('1'); - }, "expected \'1\' to be a number"); - }); - - test('isNotNumber', function () { - assert.isNotNumber('hello'); - assert.isNotNumber([ 5 ]); - - err(function () { - assert.isNotNumber(4); - }, "expected 4 not to be a number"); - }); - - test('isBoolean', function () { - assert.isBoolean(true); - assert.isBoolean(false); - - err(function () { - assert.isBoolean('1'); - }, "expected \'1\' to be a boolean"); - }); - - test('isNotBoolean', function () { - assert.isNotBoolean('true'); - - err(function () { - assert.isNotBoolean(true); - }, "expected true not to be a boolean"); - - err(function () { - assert.isNotBoolean(false); - }, "expected false not to be a boolean"); - }); - - test('include', function () { - assert.include('foobar', 'bar'); - assert.include([ 1, 2, 3], 3); - - err(function () { - assert.include('foobar', 'baz'); - }, "expected \'foobar\' to contain \'baz\'"); - - err(function () { - assert.include(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('notInclude', function () { - assert.notInclude('foobar', 'baz'); - assert.notInclude([ 1, 2, 3 ], 4); - - err(function () { - assert.notInclude('foobar', 'bar'); - }, "expected \'foobar\' to not contain \'bar\'"); - - err(function () { - assert.notInclude(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('lengthOf', function () { - assert.lengthOf([1, 2, 3], 3); - assert.lengthOf('foobar', 6); - - err(function () { - assert.lengthOf('foobar', 5); - }, "expected 'foobar' to have a length of 5 but got 6"); - - err(function () { - assert.lengthOf(1, 5); - }, "expected 1 to have a property \'length\'"); - }); - - test('match', function () { - assert.match('foobar', /^foo/); - assert.notMatch('foobar', /^bar/); - - err(function () { - assert.match('foobar', /^bar/i); - }, "expected 'foobar' to match /^bar/i"); - - err(function () { - assert.notMatch('foobar', /^foo/i); - }, "expected 'foobar' not to match /^foo/i"); - }); - - test('property', function () { - var obj = { foo: { bar: 'baz' } }; - var simpleObj = { foo: 'bar' }; - assert.property(obj, 'foo'); - assert.deepProperty(obj, 'foo.bar'); - assert.notProperty(obj, 'baz'); - assert.notProperty(obj, 'foo.bar'); - assert.notDeepProperty(obj, 'foo.baz'); - assert.deepPropertyVal(obj, 'foo.bar', 'baz'); - assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); - - err(function () { - assert.property(obj, 'baz'); - }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); - - err(function () { - assert.deepProperty(obj, 'foo.baz'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); - - err(function () { - assert.notProperty(obj, 'foo'); - }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); - - err(function () { - assert.notDeepProperty(obj, 'foo.bar'); - }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); - - err(function () { - assert.propertyVal(simpleObj, 'foo', 'ball'); - }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); - - err(function () { - assert.deepPropertyVal(obj, 'foo.bar', 'ball'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); - - err(function () { - assert.propertyNotVal(simpleObj, 'foo', 'bar'); - }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); - - err(function () { - assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); - }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); - }); - - test('throws', function () { - assert.throws(function () { - throw new Error('foo'); - }); - assert.throws(function () { - throw new Error('bar'); - }, 'bar'); - assert.throws(function () { - throw new Error('bar'); - }, /bar/); - assert.throws(function () { - throw new Error('bar'); - }, Error); - assert.throws(function () { - throw new Error('bar'); - }, Error, 'bar'); - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, Error, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError, 'bar'); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - }); - }, "expected [Function] to throw an error"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got ''"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, /bar/); - }, "expected [Function] to throw error matching /bar/ but got ''"); - }); - - test('doesNotThrow', function () { - assert.doesNotThrow(function () { - }); - assert.doesNotThrow(function () { - }, 'foo'); - - err(function () { - assert.doesNotThrow(function () { - throw new Error('foo'); - }); - }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); - }); - - test('ifError', function () { - assert.ifError(false); - assert.ifError(null); - assert.ifError(undefined); - - err(function () { - assert.ifError('foo'); - }, "expected \'foo\' to be falsy"); - }); - - test('operator', function () { - assert.operator(1, '<', 2); - assert.operator(2, '>', 1); - assert.operator(1, '==', 1); - assert.operator(1, '<=', 1); - assert.operator(1, '>=', 1); - assert.operator(1, '!=', 2); - assert.operator(1, '!==', 2); - - err(function () { - assert.operator(1, '=', 2); - }, 'Invalid operator "="'); - - err(function () { - assert.operator(2, '<', 1); - }, "expected 2 to be < 1"); - - err(function () { - assert.operator(1, '>', 2); - }, "expected 1 to be > 2"); - - err(function () { - assert.operator(1, '==', 2); - }, "expected 1 to be == 2"); - - err(function () { - assert.operator(2, '<=', 1); - }, "expected 2 to be <= 1"); - - err(function () { - assert.operator(1, '>=', 2); - }, "expected 1 to be >= 2"); - - err(function () { - assert.operator(1, '!=', 1); - }, "expected 1 to be != 1"); - - err(function () { - assert.operator(1, '!==', '1'); - }, "expected 1 to be !== \'1\'"); - }); - - test('closeTo', function () { - assert.closeTo(1.5, 1.0, 0.5); - assert.closeTo(10, 20, 20); - assert.closeTo(-10, 20, 30); - - err(function () { - assert.closeTo(2, 1.0, 0.5); - }, "expected 2 to be close to 1 +/- 0.5"); - - err(function () { - assert.closeTo(-10, 20, 29); - }, "expected -10 to be close to 20 +/- 29"); - }); - - test('members', function () { - assert.includeMembers([1, 2, 3], [2, 3]); - assert.includeMembers([1, 2, 3], []); - assert.includeMembers([1, 2, 3], [3]); - - err(function () { - assert.includeMembers([5, 6], [7, 8]); - }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); - - err(function () { - assert.includeMembers([5, 6], [5, 6, 0]); - }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); - }); - - test('memberEquals', function () { - assert.sameMembers([], []); - assert.sameMembers([1, 2, 3], [3, 2, 1]); - assert.sameMembers([4, 2], [4, 2]); - - err(function () { - assert.sameMembers([], [1, 2]); - }, 'expected [] to have the same members as [ 1, 2 ]'); - - err(function () { - assert.sameMembers([1, 54], [6, 1, 54]); - }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); - }); - -}); diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts deleted file mode 100644 index 30ae2deb7..000000000 --- a/chai/chai-assert.d.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Type definitions for chai v1.9.0 assert style -// Project: http://chaijs.com/ -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module chai { - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } - export function use(plugin: any): void; - - export var Assertion: ChaiAssertion; - export var assert: Assert; - export var config: ChaiConfig; - - export interface ChaiConfig { - includeStack: boolean; - } - - export interface ChaiAssertion { - // what? - } - - export interface Assert { - (express: any, msg?: string):void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string):void; - - ok(val: any, msg?: string):void; - notOk(val: any, msg?: string):void; - - equal(act: any, exp: any, msg?: string):void; - notEqual(act: any, exp: any, msg?: string):void; - - strictEqual(act: any, exp: any, msg?: string):void; - notStrictEqual(act: any, exp: any, msg?: string):void; - - deepEqual(act: any, exp: any, msg?: string):void; - notDeepEqual(act: any, exp: any, msg?: string):void; - - isTrue(val: any, msg?: string):void; - isFalse(val: any, msg?: string):void; - - isNull(val: any, msg?: string):void; - isNotNull(val: any, msg?: string):void; - - isUndefined(val: any, msg?: string):void; - isDefined(val: any, msg?: string):void; - - isFunction(val: any, msg?: string):void; - isNotFunction(val: any, msg?: string):void; - - isObject(val: any, msg?: string):void; - isNotObject(val: any, msg?: string):void; - - isArray(val: any, msg?: string):void; - isNotArray(val: any, msg?: string):void; - - isString(val: any, msg?: string):void; - isNotString(val: any, msg?: string):void; - - isNumber(val: any, msg?: string):void; - isNotNumber(val: any, msg?: string):void; - - isBoolean(val: any, msg?: string):void; - isNotBoolean(val: any, msg?: string):void; - - typeOf(val: any, type: string, msg?: string):void; - notTypeOf(val: any, type: string, msg?: string):void; - - instanceOf(val: any, type: Function, msg?: string):void; - notInstanceOf(val: any, type: Function, msg?: string):void; - - include(exp: string, inc: any, msg?: string):void; - include(exp: any[], inc: any, msg?: string):void; - - notInclude(exp: string, inc: any, msg?: string):void; - notInclude(exp: any[], inc: any, msg?: string):void; - - match(exp: any, re: RegExp, msg?: string):void; - notMatch(exp: any, re: RegExp, msg?: string):void; - - property(obj: Object, prop: string, msg?: string):void; - notProperty(obj: Object, prop: string, msg?: string):void; - deepProperty(obj: Object, prop: string, msg?: string):void; - notDeepProperty(obj: Object, prop: string, msg?: string):void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string):void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - lengthOf(exp: any, len: number, msg?: string):void; - //alias frenzy - throw(fn: Function, msg?: string):void; - throw(fn: Function, regExp: RegExp):void; - throw(fn: Function, errType: Function, msg?: string):void; - throw(fn: Function, errType: Function, regExp: RegExp):void; - - throws(fn: Function, msg?: string):void; - throws(fn: Function, regExp: RegExp):void; - throws(fn: Function, errType: Function, msg?: string):void; - throws(fn: Function, errType: Function, regExp: RegExp):void; - - Throw(fn: Function, msg?: string):void; - Throw(fn: Function, regExp: RegExp):void; - Throw(fn: Function, errType: Function, msg?: string):void; - Throw(fn: Function, errType: Function, regExp: RegExp):void; - - doesNotThrow(fn: Function, msg?: string):void; - doesNotThrow(fn: Function, regExp: RegExp):void; - doesNotThrow(fn: Function, errType: Function, msg?: string):void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; - - operator(val: any, operator: string, val2: any, msg?: string):void; - closeTo(act: number, exp: number, delta: number, msg?: string):void; - - sameMembers(set1: any[], set2: any[], msg?: string):void; - includeMembers(set1: any[], set2: any[], msg?: string):void; - - ifError(val: any, msg?: string):void; - } -} - -//browser global -declare var assert:chai.Assert; diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index b559c515d..398ebd069 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,6 +1,7 @@ /// var expect = chai.expect; +var assert = chai.assert; declare var err: Function; function chaiVersion() { @@ -767,3 +768,623 @@ function members() { expect([5, 4]).not.members([6, 3]); expect([5, 4]).not.members([5, 4, 2]); } + +//tdd +declare function suite(description: string, action: Function):void; +declare function test(description: string, action: Function):void; +declare function err(action: any, msg?: string):void; +interface FieldObj { + field: any; +} +class Foo { + constructor() { + + } +} + +class CrashyObject { + inspect (): void { + throw new Error("Arg's inspect() called even though the test passed"); + } +} + +suite('assert', function () { + + test('assert', function () { + var foo = 'bar'; + assert(foo == 'bar', "expected foo to equal `bar`"); + + err(function () { + assert(foo == 'baz', "expected foo to equal `bar`"); + }, "expected foo to equal `bar`"); + }); + + test('isTrue', function () { + assert.isTrue(true); + + err(function () { + assert.isTrue(false); + }, "expected false to be true"); + + err(function () { + assert.isTrue(1); + }, "expected 1 to be true"); + + err(function () { + assert.isTrue('test'); + }, "expected 'test' to be true"); + }); + + test('ok', function () { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + + err(function () { + assert.ok(false); + }, "expected false to be truthy"); + + err(function () { + assert.ok(0); + }, "expected 0 to be truthy"); + + err(function () { + assert.ok(''); + }, "expected '' to be truthy"); + }); + + test('isFalse', function () { + assert.isFalse(false); + + err(function () { + assert.isFalse(true); + }, "expected true to be false"); + + err(function () { + assert.isFalse(0); + }, "expected 0 to be false"); + }); + + test('equal', function () { + var foo: any; + assert.equal(foo, undefined); + }); + + test('typeof / notTypeOf', function () { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); + + err(function () { + assert.typeOf(5, 'string'); + }, "expected 5 to be a string"); + + }); + + test('notTypeOf', function () { + assert.notTypeOf('test', 'number'); + + err(function () { + assert.notTypeOf(5, 'number'); + }, "expected 5 not to be a number"); + }); + + test('instanceOf', function () { + assert.instanceOf(new Foo(), Foo); + + err(function () { + assert.instanceOf(5, Foo); + }, "expected 5 to be an instance of Foo"); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', function () { + assert.notInstanceOf(new Foo(), String); + + err(function () { + assert.notInstanceOf(new Foo(), Foo); + }, "expected {} to not be an instance of Foo"); + }); + + test('isObject', function () { + assert.isObject({}); + assert.isObject(new Foo()); + + err(function () { + assert.isObject(true); + }, "expected true to be an object"); + + err(function () { + assert.isObject(Foo); + }, "expected [Function: Foo] to be an object"); + + err(function () { + assert.isObject('foo'); + }, "expected 'foo' to be an object"); + }); + + test('isNotObject', function () { + assert.isNotObject(5); + + err(function () { + assert.isNotObject({}); + }, "expected {} not to be an object"); + }); + + test('notEqual', function () { + assert.notEqual(3, 4); + + err(function () { + assert.notEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('strictEqual', function () { + assert.strictEqual('foo', 'foo'); + + err(function () { + assert.strictEqual('5', 5); + }, "expected \'5\' to equal 5"); + }); + + test('notStrictEqual', function () { + assert.notStrictEqual(5, '5'); + + err(function () { + assert.notStrictEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('deepEqual', function () { + assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); + + err(function () { + assert.deepEqual({tea: 'chai'}, {tea: 'black'}); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({tea: 'chai'}) + , obj2 = Object.create({tea: 'black'}); + + err(function () { + assert.deepEqual(obj1, obj2); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + }); + + test('deepEqual (ordering)', function () { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(function () { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); + }); + + test('notDeepEqual', function () { + assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); + err(function () { + assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); + }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); + }); + + test('notDeepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(function () { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); + }); + + test('isNull', function () { + assert.isNull(null); + + err(function () { + assert.isNull(undefined); + }, "expected undefined to equal null"); + }); + + test('isNotNull', function () { + assert.isNotNull(undefined); + + err(function () { + assert.isNotNull(null); + }, "expected null to not equal null"); + }); + + test('isUndefined', function () { + assert.isUndefined(undefined); + + err(function () { + assert.isUndefined(null); + }, "expected null to equal undefined"); + }); + + test('isDefined', function () { + assert.isDefined(null); + + err(function () { + assert.isDefined(undefined); + }, "expected undefined to not equal undefined"); + }); + + test('isFunction', function () { + var func = function () { + }; + assert.isFunction(func); + + err(function () { + assert.isFunction({}); + }, "expected {} to be a function"); + }); + + test('isNotFunction', function () { + assert.isNotFunction(5); + + err(function () { + assert.isNotFunction(function () { + }); + }, "expected [Function] not to be a function"); + }); + + test('isArray', function () { + assert.isArray([]); + assert.isArray(new Array()); + + err(function () { + assert.isArray({}); + }, "expected {} to be an array"); + }); + + test('isNotArray', function () { + assert.isNotArray(3); + + err(function () { + assert.isNotArray([]); + }, "expected [] not to be an array"); + + err(function () { + assert.isNotArray(new Array()); + }, "expected [] not to be an array"); + }); + + test('isString', function () { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(function () { + assert.isString(1); + }, "expected 1 to be a string"); + }); + + test('isNotString', function () { + assert.isNotString(3); + assert.isNotString([ 'hello' ]); + + err(function () { + assert.isNotString('hello'); + }, "expected 'hello' not to be a string"); + }); + + test('isNumber', function () { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(function () { + assert.isNumber('1'); + }, "expected \'1\' to be a number"); + }); + + test('isNotNumber', function () { + assert.isNotNumber('hello'); + assert.isNotNumber([ 5 ]); + + err(function () { + assert.isNotNumber(4); + }, "expected 4 not to be a number"); + }); + + test('isBoolean', function () { + assert.isBoolean(true); + assert.isBoolean(false); + + err(function () { + assert.isBoolean('1'); + }, "expected \'1\' to be a boolean"); + }); + + test('isNotBoolean', function () { + assert.isNotBoolean('true'); + + err(function () { + assert.isNotBoolean(true); + }, "expected true not to be a boolean"); + + err(function () { + assert.isNotBoolean(false); + }, "expected false not to be a boolean"); + }); + + test('include', function () { + assert.include('foobar', 'bar'); + assert.include([ 1, 2, 3], 3); + + err(function () { + assert.include('foobar', 'baz'); + }, "expected \'foobar\' to contain \'baz\'"); + + err(function () { + assert.include(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('notInclude', function () { + assert.notInclude('foobar', 'baz'); + assert.notInclude([ 1, 2, 3 ], 4); + + err(function () { + assert.notInclude('foobar', 'bar'); + }, "expected \'foobar\' to not contain \'bar\'"); + + err(function () { + assert.notInclude(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('lengthOf', function () { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(function () { + assert.lengthOf('foobar', 5); + }, "expected 'foobar' to have a length of 5 but got 6"); + + err(function () { + assert.lengthOf(1, 5); + }, "expected 1 to have a property \'length\'"); + }); + + test('match', function () { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(function () { + assert.match('foobar', /^bar/i); + }, "expected 'foobar' to match /^bar/i"); + + err(function () { + assert.notMatch('foobar', /^foo/i); + }, "expected 'foobar' not to match /^foo/i"); + }); + + test('property', function () { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(function () { + assert.property(obj, 'baz'); + }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); + + err(function () { + assert.deepProperty(obj, 'foo.baz'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); + + err(function () { + assert.notProperty(obj, 'foo'); + }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); + + err(function () { + assert.notDeepProperty(obj, 'foo.bar'); + }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); + + err(function () { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); + + err(function () { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); + + err(function () { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); + + err(function () { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); + }); + + test('throws', function () { + assert.throws(function () { + throw new Error('foo'); + }); + assert.throws(function () { + throw new Error('bar'); + }, 'bar'); + assert.throws(function () { + throw new Error('bar'); + }, /bar/); + assert.throws(function () { + throw new Error('bar'); + }, Error); + assert.throws(function () { + throw new Error('bar'); + }, Error, 'bar'); + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, Error, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError, 'bar'); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + }); + }, "expected [Function] to throw an error"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got ''"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, /bar/); + }, "expected [Function] to throw error matching /bar/ but got ''"); + }); + + test('doesNotThrow', function () { + assert.doesNotThrow(function () { + }); + assert.doesNotThrow(function () { + }, 'foo'); + + err(function () { + assert.doesNotThrow(function () { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', function () { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(function () { + assert.ifError('foo'); + }, "expected \'foo\' to be falsy"); + }); + + test('operator', function () { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(function () { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(function () { + assert.operator(2, '<', 1); + }, "expected 2 to be < 1"); + + err(function () { + assert.operator(1, '>', 2); + }, "expected 1 to be > 2"); + + err(function () { + assert.operator(1, '==', 2); + }, "expected 1 to be == 2"); + + err(function () { + assert.operator(2, '<=', 1); + }, "expected 2 to be <= 1"); + + err(function () { + assert.operator(1, '>=', 2); + }, "expected 1 to be >= 2"); + + err(function () { + assert.operator(1, '!=', 1); + }, "expected 1 to be != 1"); + + err(function () { + assert.operator(1, '!==', '1'); + }, "expected 1 to be !== \'1\'"); + }); + + test('closeTo', function () { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(function () { + assert.closeTo(2, 1.0, 0.5); + }, "expected 2 to be close to 1 +/- 0.5"); + + err(function () { + assert.closeTo(-10, 20, 29); + }, "expected -10 to be close to 20 +/- 29"); + }); + + test('members', function () { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(function () { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(function () { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', function () { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(function () { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(function () { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); + +}); diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 058d55196..fc767c639 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,11 +1,25 @@ // Type definitions for chai 1.7.2 // Project: http://chaijs.com/ -// Definitions by: Jed Hunsaker +// Definitions by: Jed Hunsaker , Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chai { + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } function expect(target: any, message?: string): Expect; + + export var assert: Assert; + export var config: Config; + + export interface Config { + includeStack: boolean; + } // Provides a way to extend the internals of Chai function use(fn: (chai: any, utils: any) => void): any; @@ -161,6 +175,107 @@ declare module chai { (constructor: Function, expected?: string, message?: string): Expect; (constructor: Function, expected?: RegExp, message?: string): Expect; } + + export interface Assert { + (express: any, msg?: string):void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string):void; + + ok(val: any, msg?: string):void; + notOk(val: any, msg?: string):void; + + equal(act: any, exp: any, msg?: string):void; + notEqual(act: any, exp: any, msg?: string):void; + + strictEqual(act: any, exp: any, msg?: string):void; + notStrictEqual(act: any, exp: any, msg?: string):void; + + deepEqual(act: any, exp: any, msg?: string):void; + notDeepEqual(act: any, exp: any, msg?: string):void; + + isTrue(val: any, msg?: string):void; + isFalse(val: any, msg?: string):void; + + isNull(val: any, msg?: string):void; + isNotNull(val: any, msg?: string):void; + + isUndefined(val: any, msg?: string):void; + isDefined(val: any, msg?: string):void; + + isFunction(val: any, msg?: string):void; + isNotFunction(val: any, msg?: string):void; + + isObject(val: any, msg?: string):void; + isNotObject(val: any, msg?: string):void; + + isArray(val: any, msg?: string):void; + isNotArray(val: any, msg?: string):void; + + isString(val: any, msg?: string):void; + isNotString(val: any, msg?: string):void; + + isNumber(val: any, msg?: string):void; + isNotNumber(val: any, msg?: string):void; + + isBoolean(val: any, msg?: string):void; + isNotBoolean(val: any, msg?: string):void; + + typeOf(val: any, type: string, msg?: string):void; + notTypeOf(val: any, type: string, msg?: string):void; + + instanceOf(val: any, type: Function, msg?: string):void; + notInstanceOf(val: any, type: Function, msg?: string):void; + + include(exp: string, inc: any, msg?: string):void; + include(exp: any[], inc: any, msg?: string):void; + + notInclude(exp: string, inc: any, msg?: string):void; + notInclude(exp: any[], inc: any, msg?: string):void; + + match(exp: any, re: RegExp, msg?: string):void; + notMatch(exp: any, re: RegExp, msg?: string):void; + + property(obj: Object, prop: string, msg?: string):void; + notProperty(obj: Object, prop: string, msg?: string):void; + deepProperty(obj: Object, prop: string, msg?: string):void; + notDeepProperty(obj: Object, prop: string, msg?: string):void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string):void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + lengthOf(exp: any, len: number, msg?: string):void; + //alias frenzy + throw(fn: Function, msg?: string):void; + throw(fn: Function, regExp: RegExp):void; + throw(fn: Function, errType: Function, msg?: string):void; + throw(fn: Function, errType: Function, regExp: RegExp):void; + + throws(fn: Function, msg?: string):void; + throws(fn: Function, regExp: RegExp):void; + throws(fn: Function, errType: Function, msg?: string):void; + throws(fn: Function, errType: Function, regExp: RegExp):void; + + Throw(fn: Function, msg?: string):void; + Throw(fn: Function, regExp: RegExp):void; + Throw(fn: Function, errType: Function, msg?: string):void; + Throw(fn: Function, errType: Function, regExp: RegExp):void; + + doesNotThrow(fn: Function, msg?: string):void; + doesNotThrow(fn: Function, regExp: RegExp):void; + doesNotThrow(fn: Function, errType: Function, msg?: string):void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; + + operator(val: any, operator: string, val2: any, msg?: string):void; + closeTo(act: number, exp: number, delta: number, msg?: string):void; + + sameMembers(set1: any[], set2: any[], msg?: string):void; + includeMembers(set1: any[], set2: any[], msg?: string):void; + + ifError(val: any, msg?: string):void; + } } declare module "chai" { From d1f9d3fef52d491cbdfd0ab11a564672a5dff4a3 Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Sat, 19 Jul 2014 05:35:05 +0200 Subject: [PATCH 050/277] fixed chai test --- chai/chai-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index 398ebd069..98d75e8ae 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -772,7 +772,7 @@ function members() { //tdd declare function suite(description: string, action: Function):void; declare function test(description: string, action: Function):void; -declare function err(action: any, msg?: string):void; + interface FieldObj { field: any; } From e827d60b1a4f0278d5bb0022e7e5d416c642a8ae Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Sat, 19 Jul 2014 11:44:50 +0200 Subject: [PATCH 051/277] jasmine: add missing variable DEFAULT_TIMEOUT_INTERVAL --- jasmine/jasmine.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index f64a59d39..34e30cdd1 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -429,4 +429,5 @@ declare module jasmine { export var HtmlReporter: HtmlReporter; export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; } From 3c4d380a0fb61defc9f11ac57eb44881f5fba58a Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Sat, 19 Jul 2014 11:48:42 +0200 Subject: [PATCH 052/277] add example to jasmine-tests.ts --- jasmine/jasmine-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 3ce5dbc5f..8a4a00e22 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -698,3 +698,5 @@ describe("Asynchronous specs", function () { }; })(); + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; From 730cb88fb0ac988945ff4376506678eb7c0d2fb9 Mon Sep 17 00:00:00 2001 From: Sebastian Lenz Date: Sun, 20 Jul 2014 12:13:28 +0200 Subject: [PATCH 053/277] Added lunr.js definitions --- lunr/lunr-tests.ts | 44 +++ lunr/lunr.d.ts | 839 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 883 insertions(+) create mode 100644 lunr/lunr-tests.ts create mode 100644 lunr/lunr.d.ts diff --git a/lunr/lunr-tests.ts b/lunr/lunr-tests.ts new file mode 100644 index 000000000..949a53e87 --- /dev/null +++ b/lunr/lunr-tests.ts @@ -0,0 +1,44 @@ +/// + +/** + * Basic test, from http://lunrjs.com/ + */ +function basic_test() { + var index = lunr(function () { + this.field('title', {boost: 10}); + this.field('body'); + this.ref('id'); + }); + + index.add({ + id: 1, + title: 'Foo', + body: 'Foo foo foo!' + }); + + index.add({ + id: 2, + title: 'Bar', + body: 'Bar bar bar!' + }); + + index.search('foo'); +} + + +/** + * Pipeline test, from http://lunrjs.com/ + */ +function pipeline_test() { + var index = lunr(function () { + this.pipeline.add(function (token:string, tokenIndex:number, tokens:string[]):string { + // text processing in here + return token; + }); + + this.pipeline.after(lunr.stopWordFilter, function (token:string, tokenIndex:number, tokens:string[]):string { + // text processing in here + return token; + }); + }) +} \ No newline at end of file diff --git a/lunr/lunr.d.ts b/lunr/lunr.d.ts new file mode 100644 index 000000000..709e5864d --- /dev/null +++ b/lunr/lunr.d.ts @@ -0,0 +1,839 @@ +// Type definitions for lunr.js 0.5.4 +// Project: https://github.com/olivernn/lunr.js +// Definitions by: Sebastian Lenz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 0.5.4 + * Copyright (C) 2014 Oliver Nightingale + * MIT Licensed + * @license + */ +declare module lunr +{ + var version:string; + + + /** + * A function for splitting a string into tokens ready to be inserted into the search index. + * + * @param token The token to pass through the filter + */ + function tokenizer(token:string):string; + + + /** + * lunr.stemmer is an english language stemmer, this is a JavaScript implementation of + * the PorterStemmer taken from http://tartaurs.org/~martin + * + * @param token The string to stem + */ + function stemmer(token:string):string; + + + /** + * lunr.stopWordFilter is an English language stop word list filter, any words contained + * in the list will not be passed through the filter. + * + * This is intended to be used in the Pipeline. If the token does not pass the filter then + * undefined will be returned. + * + * @param token The token to pass through the filter + */ + function stopWordFilter(token:string):string; + + module stopWordFilter { + var stopWords:SortedSet; + } + + + /** + * lunr.trimmer is a pipeline function for trimming non word characters from the beginning + * and end of tokens before they enter the index. + * + * This implementation may not work correctly for non latin characters and should either + * be removed or adapted for use with languages with non-latin characters. + * @param token The token to pass through the filter + */ + function trimmer(token:string):string; + + + /** + * lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers + * and triggering events and their handlers. + */ + class EventEmitter + { + /** + * Can bind a single function to many different events in one call. + * + * @param eventName The name(s) of events to bind this function to. + * @param handler The function to call when an event is fired. Binds a handler + * function to a specific event(s). + */ + addListener(eventName:string, handler:Function):void; + addListener(eventName:string, eventName2:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, eventName4:string, handler:Function):void; + addListener(eventName:string, eventName2:string, eventName3:string, eventName4:string, eventName5:string, handler:Function):void; + + + /** + * Removes a handler function from a specific event. + * + * @param eventName The name of the event to remove this function from. + * @param handler The function to remove from an event. + */ + removeListener(eventName:string, handler:Function):void; + + + /** + * Calls all functions bound to the given event. + * + * Additional data can be passed to the event handler as arguments to emit after the event name. + * + * @param eventName The name of the event to emit. + * @param args + */ + emit(eventName:string, ...args:any[]):void; + + + /** + * Checks whether a handler has ever been stored against an event. + * + * @param eventName The name of the event to check. + */ + hasHandler(eventName:string):boolean; + } + + + interface IPipelineFunction { + (token:string):string; + (token:string, tokenIndex:number):string; + (token:string, tokenIndex:number, tokens:string[]):string; + } + + + /** + * lunr.Pipelines maintain an ordered list of functions to be applied to all tokens in documents + * entering the search index and queries being ran against the index. + * + * An instance of lunr.Index created with the lunr shortcut will contain a pipeline with a stop + * word filter and an English language stemmer. Extra functions can be added before or after either + * of these functions or these default functions can be removed. + * + * When run the pipeline will call each function in turn, passing a token, the index of that token + * in the original list of all tokens and finally a list of all the original tokens. + * + * The output of functions in the pipeline will be passed to the next function in the pipeline. + * To exclude a token from entering the index the function should return undefined, the rest of + * the pipeline will not be called with this token. + * + * For serialisation of pipelines to work, all functions used in an instance of a pipeline should + * be registered with lunr.Pipeline. Registered functions can then be loaded. If trying to load a + * serialised pipeline that uses functions that are not registered an error will be thrown. + * + * If not planning on serialising the pipeline then registering pipeline functions is not necessary. + */ + class Pipeline + { + registeredFunctions:{[label:string]:Function}; + + + /** + * Register a function with the pipeline. + * + * Functions that are used in the pipeline should be registered if the pipeline needs to be + * serialised, or a serialised pipeline needs to be loaded. + * + * Registering a function does not add it to a pipeline, functions must still be added to instances + * of the pipeline for them to be used when running a pipeline. + * + * @param fn The function to check for. + * @param label The label to register this function with + */ + registerFunction(fn:IPipelineFunction, label:string):void; + + + /** + * Warns if the function is not registered as a Pipeline function. + * + * @param fn The function to check for. + */ + warnIfFunctionNotRegistered(fn:IPipelineFunction):void; + + + /** + * Adds new functions to the end of the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param functions Any number of functions to add to the pipeline. + */ + add(...functions:IPipelineFunction[]):void; + + + /** + * Adds a single function after a function that already exists in the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param existingFn A function that already exists in the pipeline. + * @param newFn The new function to add to the pipeline. + */ + after(existingFn:IPipelineFunction, newFn:IPipelineFunction):void; + + + /** + * Adds a single function before a function that already exists in the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param existingFn A function that already exists in the pipeline. + * @param newFn The new function to add to the pipeline. + */ + before(existingFn:IPipelineFunction, newFn:IPipelineFunction):void; + + + /** + * Removes a function from the pipeline. + * + * @param fn The function to remove from the pipeline. + */ + remove(fn:IPipelineFunction):void; + + + /** + * Runs the current list of functions that make up the pipeline against + * the passed tokens. + * + * @param tokens The tokens to run through the pipeline. + */ + run(tokens:string[]):string[]; + + + /** + * Resets the pipeline by removing any existing processors. + */ + reset():void; + + + /** + * Returns a representation of the pipeline ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised pipeline. + * + * All functions to be loaded must already be registered with lunr.Pipeline. If any function from + * the serialised data has not been registered then an error will be thrown. + * + * @param serialised The serialised pipeline to load. + */ + static load(serialised:any):Pipeline; + } + + + /** + * lunr.Vectors implement vector related operations for a series of elements. + */ + class Vector + { + list:Node; + + + /** + * Calculates the magnitude of this vector. + */ + magnitude():number; + + + /** + * Calculates the dot product of this vector and another vector. + * @param otherVector The vector to compute the dot product with. + */ + dot(otherVector:Vector):number; + + + /** + * Calculates the cosine similarity between this vector and another vector. + * + * @param otherVector The other vector to calculate the + */ + similarity(otherVector:Vector):number; + } + + + /** + * lunr.Vector.Node is a simple struct for each node in a lunr.Vector. + */ + class Node + { + /** + * The index of the node in the vector. + */ + idx:number; + + /** + * The data at this node in the vector. + */ + val:number; + + /** + * The node directly after this node in the vector. + */ + next:Node; + + + /** + * @param idx The index of the node in the vector. + * @param val The data at this node in the vector. + * @param next The node directly after this node in the vector. + */ + constructor(idx:number, val:number, next:Node); + } + + + /** + * lunr.SortedSets are used to maintain an array of unique values in a sorted order. + */ + class SortedSet + { + elements:T[]; + + length:number; + + + /** + * Inserts new items into the set in the correct position to maintain the order. + * + * @param values The objects to add to this set. + */ + add(...values:T[]):void; + + + /** + * Converts this sorted set into an array. + */ + toArray():T[]; + + + /** + * Creates a new array with the results of calling a provided function on + * every element in this sorted set. + * + * Delegates to Array.prototype.map and has the same signature. + * + * @param fn The function that is called on each element of the + * @param ctx An optional object that can be used as the context + */ + map(fn:Function, ctx:any):T[]; + + + /** + * Executes a provided function once per sorted set element. + * + * Delegates to Array.prototype.forEach and has the same signature. + * + * @param fn The function that is called on each element of the + * @param ctx An optional object that can be used as the context + */ + forEach(fn:Function, ctx:any):any; + + + /** + * Returns the index at which a given element can be found in the sorted + * set, or -1 if it is not present. + * + * @param elem The object to locate in the sorted set. + * @param start An optional index at which to start searching from + * @param end An optional index at which to stop search from within + */ + indexOf(elem:T, start?:number, end?:number):number; + + + /** + * Returns the position within the sorted set that an element should be + * inserted at to maintain the current order of the set. + * + * This function assumes that the element to search for does not already exist + * in the sorted set. + * + * @param elem - The elem to find the position for in the set + * @param start - An optional index at which to start searching from + * @param end - An optional index at which to stop search from within + */ + locationFor(elem:T, start?:number, end?:number):number; + + + /** + * Creates a new lunr.SortedSet that contains the elements in the + * intersection of this set and the passed set. + * + * @param otherSet The set to intersect with this set. + */ + intersect(otherSet:SortedSet):SortedSet; + + + /** + * Creates a new lunr.SortedSet that contains the elements in the union of this + * set and the passed set. + * + * @param otherSet The set to union with this set. + */ + union(otherSet:SortedSet):SortedSet; + + + /** + * Makes a copy of this set + */ + clone():SortedSet; + + + /** + * Returns a representation of the sorted set ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised sorted set. + * + * @param serialisedData The serialised set to load. + */ + static load(serialisedData:T[]):SortedSet; + } + + + interface IIndexField + { + /** + * The name of the field within the document that + */ + name:string; + + /** + * An optional boost that can be applied to terms in this field. + */ + boost:number; + } + + + interface IIndexSearchResult + { + ref:any; + + score:number; + } + + + /** + * lunr.Index is object that manages a search index. It contains the indexes and stores + * all the tokens and document lookups. It also provides the main user facing API for + * the library. + */ + class Index + { + eventEmitter:EventEmitter; + + documentStore:Store; + + tokenStore:TokenStore; + + corpusTokens:SortedSet; + + pipeline:Pipeline; + + _fields:IIndexField[]; + + _ref:string; + + _idfCache:{[key:string]:string}; + + + /** + * Bind a handler to events being emitted by the index. + * + * The handler can be bound to many events at the same time. + * + * @param eventName The name(s) of events to bind the function to. + * @param handler The function to call when an event is fired. Binds a handler + * function to a specific event(s). + */ + on(eventName:string, handler:Function):void; + on(eventName:string, eventName2:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, eventName4:string, handler:Function):void; + on(eventName:string, eventName2:string, eventName3:string, eventName4:string, eventName5:string, handler:Function):void; + + + /** + * Removes a handler from an event being emitted by the index. + * + * @param eventName The name of events to remove the function from. + * @param handler The serialised set to load. + */ + off(eventName:string, handler:Function):void; + + + /** + * Adds a field to the list of fields that will be searchable within documents in the index. + * + * An optional boost param can be passed to affect how much tokens in this field rank in + * search results, by default the boost value is 1. + * + * Fields should be added before any documents are added to the index, fields that are added + * after documents are added to the index will only apply to new documents added to the index. + * + * @param fieldName The name of the field within the document that + * @param options An optional boost that can be applied to terms in this field. + */ + field(fieldName:string, options?:{boost?:number}):Index; + + + /** + * Sets the property used to uniquely identify documents added to the index, by default this + * property is 'id'. + * + * This should only be changed before adding documents to the index, changing the ref property + * without resetting the index can lead to unexpected results. + * + * @refName The property to use to uniquely identify the + */ + ref(refName:string):Index; + + + /** + * Add a document to the index. + * + * This is the way new documents enter the index, this function will run the fields from the + * document through the index's pipeline and then add it to the index, it will then show up + * in search results. + * + * An 'add' event is emitted with the document that has been added and the index the document + * has been added to. This event can be silenced by passing false as the second argument to add. + * + * @param doc The document to add to the index. + * @param emitEvent Whether or not to emit events, default true. + */ + add(doc:any, emitEvent?:boolean):void; + + + /** + * Removes a document from the index. + * + * To make sure documents no longer show up in search results they can be removed from the + * index using this method. + * + * The document passed only needs to have the same ref property value as the document that was + * added to the index, they could be completely different objects. + * + * A 'remove' event is emitted with the document that has been removed and the index the + * document has been removed from. This event can be silenced by passing false as the second + * argument to remove. + * + * @param doc The document to remove from the index. + * @param emitEvent Whether to emit remove events, defaults to true + */ + remove(doc:any, emitEvent?:boolean):void; + + + /** + * Updates a document in the index. + * + * When a document contained within the index gets updated, fields changed, added or removed, + * to make sure it correctly matched against search queries, it should be updated in the index. + * + * This method is just a wrapper around [[remove]] and [[add]]. + * + * An 'update' event is emitted with the document that has been updated and the index. + * This event can be silenced by passing false as the second argument to update. Only an + * update event will be fired, the 'add' and 'remove' events of the underlying calls are + * silenced. + * + * @param doc The document to update in the index. + * @param emitEvent Whether to emit update events, defaults to true + */ + update(doc:any, emitEvent?:boolean):void; + + + /** + * Calculates the inverse document frequency for a token within the index. + * + * @param token The token to calculate the idf of. + */ + idf(token:string):string; + + + /** + * Searches the index using the passed query. + * + * Queries should be a string, multiple words are allowed and will lead to an AND based + * query, e.g. idx.search('foo bar') will run a search for documents containing both + * 'foo' and 'bar'. + * + * All query tokens are passed through the same pipeline that document tokens are passed + * through, so any language processing involved will be run on every query term. + * + * Each query term is expanded, so that the term 'he' might be expanded to 'hello' + * and 'help' if those terms were already included in the index. + * + * Matching documents are returned as an array of objects, each object contains the + * matching document ref, as set for this index, and the similarity score for this + * document against the query. + * + * @param query The query to search the index with. + */ + search(query:string):IIndexSearchResult[]; + + + /** + * Generates a vector containing all the tokens in the document matching the + * passed documentRef. + * + * The vector contains the tf-idf score for each token contained in the document with + * the passed documentRef. The vector will contain an element for every token in the + * indexes corpus, if the document does not contain that token the element will be 0. + * + * @param documentRef The ref to find the document with. + */ + documentVector(documentRef:string):Vector; + + + /** + * Returns a representation of the index ready for serialisation. + */ + toJSON():any; + + + /** + * Applies a plugin to the current index. + * + * A plugin is a function that is called with the index as its context. Plugins can be + * used to customise or extend the behaviour the index in some way. A plugin is just a + * function, that encapsulated the custom behaviour that should be applied to the index. + * + * The plugin function will be called with the index as its argument, additional arguments + * can also be passed when calling use. The function will be called with the index as + * its context. + * + * Example: + * + * ```javascript + * var myPlugin = function(idx, arg1, arg2) { + * // `this` is the index to be extended + * // apply any extensions etc here. + * }; + * + * var idx = lunr(function() { + * this.use(myPlugin, 'arg1', 'arg2'); + * }); + * ``` + * + * @param plugin The plugin to apply. + * @param args + */ + use(plugin:Function, ...args:any[]):void; + + + /** + * Loads a previously serialised index. + * + * Issues a warning if the index being imported was serialised by a different version + * of lunr. + * + * @param serialisedData The serialised set to load. + */ + static load(serialisedData:any):Index; + } + + + /** + * lunr.Store is a simple key-value store used for storing sets of tokens for documents + * stored in index. + */ + class Store + { + store:{[id:string]:SortedSet}; + + length:number; + + + /** + * Stores the given tokens in the store against the given id. + * + * @param id The key used to store the tokens against. + * @param tokens The tokens to store against the key. + */ + set(id:string, tokens:SortedSet):void; + + + /** + * Retrieves the tokens from the store for a given key. + * + * @param id The key to lookup and retrieve from the store. + */ + get(id:string):SortedSet; + + + /** + * Checks whether the store contains a key. + * + * @param id The id to look up in the store. + */ + has(id:string):boolean; + + + /** + * Removes the value for a key in the store. + * + * @param id The id to remove from the store. + */ + remove(id:string):void; + + + /** + * Returns a representation of the store ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised store. + * + * @param serialisedData The serialised store to load. + */ + static load(serialisedData:any):Store; + } + + + interface ITokenDocument + { + ref:number; + + tf:number; + } + + + /** + * lunr.TokenStore is used for efficient storing and lookup of the reverse index of token + * to document ref. + */ + class TokenStore + { + root:{[token:string]:TokenStore}; + + docs:{[ref:string]:ITokenDocument}; + + length:number; + + + /** + * Adds a new token doc pair to the store. + * + * By default this function starts at the root of the current store, however it can + * start at any node of any token store if required. + * + * @param token The token to store the doc under + * @param doc The doc to store against the token + * @param root An optional node at which to start looking for the + */ + add(token:string, doc:ITokenDocument, root?:TokenStore):void; + + + /** + * Checks whether this key is contained within this lunr.TokenStore. + * + * @param token The token to check for + */ + has(token:string):boolean; + + + /** + * Retrieve a node from the token store for a given token. + * + * @param token The token to get the node for. + */ + getNode(token:string):TokenStore; + + + /** + * Retrieve the documents for a node for the given token. + * + * By default this function starts at the root of the current store, however it can + * start at any node of any token store if required. + * + * @param token The token to get the documents for. + * @param root An optional node at which to start. + */ + get(token:string, root:TokenStore):{[ref:string]:ITokenDocument}; + + + count(token:string, root:TokenStore):number; + + + /** + * Remove the document identified by ref from the token in the store. + * + * @param token The token to get the documents for. + * @param ref The ref of the document to remove from this token. + */ + remove(token:string, ref:string):void; + + + /** + * Find all the possible suffixes of the passed token using tokens currently in + * the store. + * + * @param token The token to expand. + * @param memo + */ + expand(token:string, memo?:string[]):string[]; + + + /** + * Returns a representation of the token store ready for serialisation. + */ + toJSON():any; + + + /** + * Loads a previously serialised token store. + * + * @param serialisedData The serialised token store to load. + */ + static load(serialisedData:any):TokenStore; + } +} + + +/** + * Convenience function for instantiating a new lunr index and configuring it with the default + * pipeline functions and the passed config function. + * + * When using this convenience function a new index will be created with the following functions + * already in the pipeline: + * + * * lunr.StopWordFilter - filters out any stop words before they enter the index + * + * * lunr.stemmer - stems the tokens before entering the index. + * + * Example: + * + * ```javascript + * var idx = lunr(function () { + * this.field('title', 10); + * this.field('tags', 100); + * this.field('body'); + * + * this.ref('cid'); + * + * this.pipeline.add(function () { + * // some custom pipeline function + * }); + * }); + * ``` + */ +declare function lunr(config:Function):lunr.Index; \ No newline at end of file From 4227be18c1bf006da4af4f435fcdab2349f125db Mon Sep 17 00:00:00 2001 From: Steve Ognibene Date: Sun, 20 Jul 2014 09:10:21 -0400 Subject: [PATCH 054/277] Added typing for big.js library --- big.js/big.js-tests.ts | 233 +++++++++++++++++++++++++++++++++++++++++ big.js/big.js.d.ts | 200 +++++++++++++++++++++++++++++++++++ 2 files changed, 433 insertions(+) create mode 100644 big.js/big.js-tests.ts create mode 100644 big.js/big.js.d.ts diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts new file mode 100644 index 000000000..6de9ee7cc --- /dev/null +++ b/big.js/big.js-tests.ts @@ -0,0 +1,233 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +/* + + Tests include code from http://mikemcl.github.io/big.js/ + + Minor changes have been made such as adding variable definitions where required. + +*/ + +function constructorTests() { + var x = new Big(9) // '9' + var y = new Big(x) // '9' + var d = Big(435.345) // 'new' is optional + var e = Big('435.345') // 'new' is optional + var a = new Big('5032485723458348569331745.33434346346912144534543') + var b = new Big('4.321e+4') // '43210' + var c = new Big('-735.0918e-430') // '-7.350918e-428' +} + +function staticPropertiesTests() { + Big.DP = 40; + Big.RM = 3; + Big.RM = BigJsLibrary.RoundingMode.RoundAwayFromZero; +} + +function absTests() { + var x = new Big(-0.8); + x.abs(); // '0.8' +} + +function cmpTests() { + var x = new Big(6); + var y = new Big(5); + x.cmp(y); // 1 + y.cmp(x.minus(1)); // 0 +} + +function divTests() { + var x = new Big(355); + var y = new Big(113); + x.div(y); // '3.14159292035398230088' + Big.DP = 2; + x.div(y); // '3.14' + x.div(5); // '71' +} + +function eqTests() { + 0 === 1e-324; // true + var x = new Big(0); + x.eq('1e-324'); // false + Big(-0).eq(x); // true ( -0 === 0 ) +} + +function gtTests() { + 0.1 > 0.3 - 0.2; // true + var x = new Big(0.1); + x.gt(Big(0.3).minus(0.2)); // false + Big(0).gt(x); // false +} + +function gteTests() { + 0.3 - 0.2 >= 0.1; // false + var x = new Big(0.3).minus(0.2); + x.gte(0.1); // true + Big(1).gte(x); // true +} + +function ltTests() { + 0.3 - 0.2 < 0.1; // true + var x = new Big(0.3).minus(0.2); + x.lt(0.1); // false + Big(0).lt(x); // true +} + +function lteTests() { + 0.1 <= 0.3 - 0.2; // false + var x = new Big(0.1); + x.lte(Big(0.3).minus(0.2)); // true + Big(-1).lte(x); // true +} + +function minusTests() { + 0.3 - 0.1; // 0.19999999999999998 + var x = new Big(0.3); + x.minus(0.1); // '0.2' +} + +function modTests() { + 1 % 0.9 // 0.09999999999999998 + var x = Big(1); + x.mod(0.9) // '0.1' +} + +function plusTests() { + 0.1 + 0.2 // 0.30000000000000004 + var x = new Big(0.1) + var y = x.plus(0.2) // '0.3' + Big(0.7).plus(x).plus(y) // '1' +} + +function powTests() { + Math.pow(0.7, 2) // 0.48999999999999994 + var x = new Big(0.7) + x.pow(2) // '0.49' + Big.DP = 20 + Big(3).pow(-2) // '0.11111111111111111111' + + new Big(123.456).pow(1000).toString().length // 5099 + new Big(2).pow(1e+6) // Time taken (Node.js): 9 minutes 34 secs. +} + +function roundTests() { + var x = 123.45 + Math.round(x) // 123 + var y = new Big(x) + y.round() // '123' + y.round(2) // '123.45' + y.round(10) // '123.45' + y.round(1, 0) // '123.4' + y.round(1, 1) // '123.5' + y.round(1, 2) // '123.4' + y.round(1, 3) // '123.5' + y // '123.45' +} + +function sqrtTests() { + var x = new Big(16) + x.sqrt() // '4' + var y = new Big(3) + y.sqrt() // '1.73205080756887729353' +} + +function timesTests() { + 0.6 * 3 // 1.7999999999999998 + var x = new Big(0.6) + var y = x.times(3) // '1.8' + Big('7e+500').times(y) // '1.26e+501' +} + +function toExponentialTests() { + var x = 45.6 + var y = new Big(x) + x.toExponential() // '4.56e+1' + y.toExponential() // '4.56e+1' + x.toExponential(0) // '5e+1' + y.toExponential(0) // '5e+1' + x.toExponential(1) // '4.6e+1' + y.toExponential(1) // '4.6e+1' + x.toExponential(3) // '4.560e+1' + y.toExponential(3) // '4.560e+1' +} + +function toFixedTests() { + var x = 45.6 + var y = new Big(x) + x.toFixed() // '46' + y.toFixed() // '45.6' + y.toFixed(0) // '46' + x.toFixed(3) // '45.600' + y.toFixed(3) // '45.600' +} + +function toPrecisionTests() { + var x = 45.6 + var y = new Big(x) + x.toPrecision() // '45.6' + y.toPrecision() // '45.6' + x.toPrecision(1) // '5e+1' + y.toPrecision(1) // '5e+1' + x.toPrecision(5) // '45.600' + y.toPrecision(5) // '45.600' +} + +function toStringTests() { + var x = new Big('9.99e+20') + x.toString() // '999000000000000000000' + var y = new Big('1E21') + x.toString() // '1e+21' +} + +function valueOfTests() { + var x = new Big('177.7e+457') + x.valueOf() // '1.777e+459' +} + +function toJSONTests() { + var x = new Big('177.7e+457') + var y = new Big(235.4325) + var z = new Big('0.0098074') + var str = JSON.stringify([x, y, z]) + + var a = new Big('123').toJSON(); + + JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) }) // Returns an array of three Big numbers. +} + +function propertiesTest1() { + var x = new Big(0.123) // '0.123' + x.toExponential() // '1.23e-1' + x.c // '1,2,3' + x.e // -1 + x.s // 1 + + var y = new Number(-123.4567000e+2) // '-12345.67' + y.toExponential() // '-1.234567e+4' + var z = new Big('-123.4567000e+2') // '-12345.67' + z.toExponential() // '-1.234567e+4' + z.c // '1,2,3,4,5,6,7' + z.e // 4 + z.s // -1 +} + +function propertiesTest2() { + var x = new Big('1234.000') // '1234' + x.toExponential() // '1.234e+3' + x.c // '1,2,3,4' + x.e // 3 + + x.e = -5 + x // '0.00001234' +} + +function propertiesTest3() { + var y = new Big(-0) // '0' + y.c // '0' [0].toString() + y.e // 0 + y.s // -1 +} \ No newline at end of file diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts new file mode 100644 index 000000000..4f6278a80 --- /dev/null +++ b/big.js/big.js.d.ts @@ -0,0 +1,200 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module BigJsLibrary { + + export enum RoundingMode { + RoundTowardsZero = 0, + RoundTowardsNearestAwayFromZero = 1, + RoundTowardsNearestTowardsEven = 2, + RoundAwayFromZero = 3 + } + + interface BigJS extends BigJS_Constructors { + /** The maximum number of decimal places of the results of operations involving division. + It is relevant only to the div and sqrt methods, and the pow method when the exponent is negative. + @default 40 */ + DP: number; + + /** The rounding mode used in the above operations and by round, toExponential, toFixed and toPrecision. + Default is RoundTowardsNearestAwayFromZero + @default 1 */ + RM: RoundingMode; + } + + interface BigJS_Constructors { + /** A decimal value. */ + new (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + new (value: string): BigJS; + /** A decimal value. */ + new (value: BigJS): BigJS; + /** A decimal value. */ + (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + (value: string): BigJS; + /** A decimal value. */ + (value: BigJS): BigJS; + } + + /** BigJS instance methods */ + interface BigJS extends BigJS_Constructors { + /** Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number. */ + abs(): BigJS; + + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: number): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: string): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: BigJS): number; + + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: BigJS): BigJS; + + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: number): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: string): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: number): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: string): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: number): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: string): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: number): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: string): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: number): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: string): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: BigJS): boolean; + + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number raised to the power exp. + If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. + @param exp integer, -1e+6 to 1e+6 inclusive */ + pow(exp: number): BigJS; + + /** Returns a Big number whose value is the value of this Big number rounded to a whole number. */ + round(): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. */ + round(dp: number): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. + @param rm Rounding mode. If rm is omitted or is null or undefined, the current Big.RM setting is used. */ + round(dp: number, rm: RoundingMode): BigJS; + + /** Returns a Big number whose value is the square root of this Big number. */ + sqrt(): BigJS; + + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: BigJS): BigJS; + + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ + toExponential(): string; + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly. */ + toExponential(dp: number): string; + + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. */ + toFixed(): string; + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, then the return value is simply the value in normal notation. This is also unlike Number.prototype.toFixed, which returns the value to zero decimal places. */ + toFixed(dp: number): string; + + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. */ + toPrecision(): string; + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. + @param sd significant digits. If sd is omitted, or is null or undefined, then the return value is the same as .toString(). */ + toPrecision(sd: number /** number of significant digits (0 to 1e+6 inclusive) */): string; + + /** Returns a string representing the value of this Big number. */ + toString(): string; + + /** As toString. */ + valueOf(): string; + + /** As toString. */ + toJSON(): string; + + /** coefficient (significand) */ + c: number[]; + + /** exponent (Integer, -1e+6 to 1e+6 inclusive) */ + e: number; + + /** sign (-1 or 1) */ + s: number; + } +} + +declare var Big: BigJsLibrary.BigJS; \ No newline at end of file From 433b0cf2df9a92cc00ab22901da4f13a74a1c9dc Mon Sep 17 00:00:00 2001 From: Steve Ognibene Date: Sun, 20 Jul 2014 09:14:58 -0400 Subject: [PATCH 055/277] Added line to contributors file. --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c01d01147..4955fcbdb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -28,6 +28,7 @@ All definitions files include a header with the author and editors, so at some p * [aws-sdk-js](https://github.com/aws/aws-sdk-js) (by [midknight41](https://github.com/midknight41)) * [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)) * [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)) From dc4d81a6bda11013ce1e1752a53a8cf00606adfd Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 12:59:27 -0400 Subject: [PATCH 056/277] Remove useless reference to RxJS This reference is not needed and is now causing problem because the definitelyTyped for RxJS is now part of the RxJS package directly. The Nuget package will needed to be changed also. --- knockout.rx/knockout.rx.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..601ef5af4 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From 0692edd2381159aa004995cfd973f4d6995170f8 Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 16:25:49 -0400 Subject: [PATCH 057/277] Revert "Remove useless reference to RxJS" This reverts commit dc4d81a6bda11013ce1e1752a53a8cf00606adfd. --- knockout.rx/knockout.rx.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 601ef5af4..71d95d758 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From a2cb953ad174cbd4431b9dc78c97251413bbe76f Mon Sep 17 00:00:00 2001 From: Carl de Billy Date: Sun, 20 Jul 2014 16:30:34 -0400 Subject: [PATCH 058/277] Removed useless reference to RxJS typing Since the typing is now part of RxJS, referencing it (which is causing a nuget package dependency) will cause a problem by having twice the save references in the samme app. --- knockout.rx/knockout.rx.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..4a27f3fed 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; @@ -21,6 +20,8 @@ interface KnockoutComputedFunctions { } declare module Rx { + interface ISubject { } + interface Observable { toKoSubscribable(): KnockoutSubscribable; toKoObservable(initialValue?: T): KnockoutObservable; From 735c0f1d5d58cff9399035d4f70d6d30a12256c7 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Mon, 21 Jul 2014 11:48:03 +1000 Subject: [PATCH 059/277] Added val methods - ref https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#api --- typeahead/typeahead-tests.ts | 5 +++++ typeahead/typeahead.d.ts | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 67fc8d31a..1044fe3bf 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -85,3 +85,8 @@ $('.example-countries .typeahead').typeahead({ prefetch: '../data/countries.json', limit: 10 }); + +module valueTest { + var value: string = $('foo').typeahead('val'); + $('foo').typeahead('val', value); +} \ No newline at end of file diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index f6f387986..bb8aaf31d 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -60,6 +60,17 @@ interface JQuery { * @param dataset Array of datasets */ typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset): JQuery; + + /** + * Returns the current value of the typeahead. The value is the text the user has entered into the input element. + */ + typeahead(methodName: 'val'): string; + typeahead(methodName: string): string; + + /** + * Sets the value of the typeahead. This should be used in place of jQuery#val. + */ + typeahead(methodName: 'val', value: string): JQuery; } declare module Twitter.Typeahead { From fe47b495c8aa7ee551fb3239fb08c93f15a05f92 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 11:09:13 +0200 Subject: [PATCH 060/277] 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 93116a95bb19d90999519cf863170d905c91ebfd Mon Sep 17 00:00:00 2001 From: Taylan Date: Mon, 21 Jul 2014 10:24:55 +0100 Subject: [PATCH 061/277] Update kineticjs.d.ts Updated arguments for Node.move() to match library: http://kineticjs.com/docs/Kinetic.Node.html --- kineticjs/kineticjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index dc9219fe2..b5d56e846 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -45,7 +45,7 @@ declare module Kinetic { isDraggable(): boolean; isDragging(): boolean; isListening(): boolean; - move(x: number, y: number): void; + move(change:{x: number; y: number}): void; moveDown(): void; moveTo(newContainer: IContainer): void; moveToBottom(): void; From 625b9f2523e465181c9b3793269a2755e4fddca7 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 15:33:31 +0200 Subject: [PATCH 062/277] 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 063/277] 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 48a3150ca5fa6b7a4a48b8d79709ae1e03961b8c Mon Sep 17 00:00:00 2001 From: "Omid K. Rad" Date: Mon, 21 Jul 2014 16:04:35 -0700 Subject: [PATCH 064/277] Backbone.emulateJSON http://backbonejs.org/#Sync-emulateJSON --- backbone/backbone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index d8bdc71c9..3aeeb7d90 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -375,7 +375,7 @@ declare module Backbone { function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; - var emulateJSONBackbone: boolean; + var emulateJSON: boolean; // Utility function noConflict(): typeof Backbone; From c0df8aa594852cec97d841e28488d9b39b1c62ee Mon Sep 17 00:00:00 2001 From: Brian Malehorn Date: Mon, 21 Jul 2014 17:56:42 -0700 Subject: [PATCH 065/277] 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 70b0bfebde611eeb97ddc8286fa9ae1f8d19d226 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:10:22 -0700 Subject: [PATCH 066/277] rx.jquery.d.ts moved to separated folder 'rx-jquery'. --- {rx.js => rx-jquery}/rx.jquery.d.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {rx.js => rx-jquery}/rx.jquery.d.ts (100%) diff --git a/rx.js/rx.jquery.d.ts b/rx-jquery/rx.jquery.d.ts similarity index 100% rename from rx.js/rx.jquery.d.ts rename to rx-jquery/rx.jquery.d.ts From 3a92e771933d2dd8fc184294d4077b0ef86f47a5 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:11:26 -0700 Subject: [PATCH 067/277] rx.js renamed to rx. --- {rx.js => rx}/rx-lite.d.ts | 0 {rx.js => rx}/rx.aggregates.d.ts | 0 {rx.js => rx}/rx.all.ts | 0 {rx.js => rx}/rx.async-lite.d.ts | 0 {rx.js => rx}/rx.async-tests.ts | 0 {rx.js => rx}/rx.async.d.ts | 0 {rx.js => rx}/rx.backpressure-lite.d.ts | 0 {rx.js => rx}/rx.backpressure-tests.ts | 0 {rx.js => rx}/rx.backpressure.d.ts | 0 {rx.js => rx}/rx.binding-lite.d.ts | 0 {rx.js => rx}/rx.binding.d.ts | 0 {rx.js => rx}/rx.coincidence-lite.d.ts | 0 {rx.js => rx}/rx.coincidence.d.ts | 0 {rx.js => rx}/rx.d.ts | 0 {rx.js => rx}/rx.experimental.d.ts | 0 {rx.js => rx}/rx.joinpatterns.d.ts | 0 {rx.js => rx}/rx.lite.d.ts | 0 {rx.js => rx}/rx.testing.d.ts | 0 {rx.js => rx}/rx.time-lite.d.ts | 0 {rx.js => rx}/rx.time.d.ts | 0 {rx.js => rx}/rx.virtualtime.d.ts | 0 21 files changed, 0 insertions(+), 0 deletions(-) rename {rx.js => rx}/rx-lite.d.ts (100%) rename {rx.js => rx}/rx.aggregates.d.ts (100%) rename {rx.js => rx}/rx.all.ts (100%) rename {rx.js => rx}/rx.async-lite.d.ts (100%) rename {rx.js => rx}/rx.async-tests.ts (100%) rename {rx.js => rx}/rx.async.d.ts (100%) rename {rx.js => rx}/rx.backpressure-lite.d.ts (100%) rename {rx.js => rx}/rx.backpressure-tests.ts (100%) rename {rx.js => rx}/rx.backpressure.d.ts (100%) rename {rx.js => rx}/rx.binding-lite.d.ts (100%) rename {rx.js => rx}/rx.binding.d.ts (100%) rename {rx.js => rx}/rx.coincidence-lite.d.ts (100%) rename {rx.js => rx}/rx.coincidence.d.ts (100%) rename {rx.js => rx}/rx.d.ts (100%) rename {rx.js => rx}/rx.experimental.d.ts (100%) rename {rx.js => rx}/rx.joinpatterns.d.ts (100%) rename {rx.js => rx}/rx.lite.d.ts (100%) rename {rx.js => rx}/rx.testing.d.ts (100%) rename {rx.js => rx}/rx.time-lite.d.ts (100%) rename {rx.js => rx}/rx.time.d.ts (100%) rename {rx.js => rx}/rx.virtualtime.d.ts (100%) diff --git a/rx.js/rx-lite.d.ts b/rx/rx-lite.d.ts similarity index 100% rename from rx.js/rx-lite.d.ts rename to rx/rx-lite.d.ts diff --git a/rx.js/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts similarity index 100% rename from rx.js/rx.aggregates.d.ts rename to rx/rx.aggregates.d.ts diff --git a/rx.js/rx.all.ts b/rx/rx.all.ts similarity index 100% rename from rx.js/rx.all.ts rename to rx/rx.all.ts diff --git a/rx.js/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts similarity index 100% rename from rx.js/rx.async-lite.d.ts rename to rx/rx.async-lite.d.ts diff --git a/rx.js/rx.async-tests.ts b/rx/rx.async-tests.ts similarity index 100% rename from rx.js/rx.async-tests.ts rename to rx/rx.async-tests.ts diff --git a/rx.js/rx.async.d.ts b/rx/rx.async.d.ts similarity index 100% rename from rx.js/rx.async.d.ts rename to rx/rx.async.d.ts diff --git a/rx.js/rx.backpressure-lite.d.ts b/rx/rx.backpressure-lite.d.ts similarity index 100% rename from rx.js/rx.backpressure-lite.d.ts rename to rx/rx.backpressure-lite.d.ts diff --git a/rx.js/rx.backpressure-tests.ts b/rx/rx.backpressure-tests.ts similarity index 100% rename from rx.js/rx.backpressure-tests.ts rename to rx/rx.backpressure-tests.ts diff --git a/rx.js/rx.backpressure.d.ts b/rx/rx.backpressure.d.ts similarity index 100% rename from rx.js/rx.backpressure.d.ts rename to rx/rx.backpressure.d.ts diff --git a/rx.js/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts similarity index 100% rename from rx.js/rx.binding-lite.d.ts rename to rx/rx.binding-lite.d.ts diff --git a/rx.js/rx.binding.d.ts b/rx/rx.binding.d.ts similarity index 100% rename from rx.js/rx.binding.d.ts rename to rx/rx.binding.d.ts diff --git a/rx.js/rx.coincidence-lite.d.ts b/rx/rx.coincidence-lite.d.ts similarity index 100% rename from rx.js/rx.coincidence-lite.d.ts rename to rx/rx.coincidence-lite.d.ts diff --git a/rx.js/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts similarity index 100% rename from rx.js/rx.coincidence.d.ts rename to rx/rx.coincidence.d.ts diff --git a/rx.js/rx.d.ts b/rx/rx.d.ts similarity index 100% rename from rx.js/rx.d.ts rename to rx/rx.d.ts diff --git a/rx.js/rx.experimental.d.ts b/rx/rx.experimental.d.ts similarity index 100% rename from rx.js/rx.experimental.d.ts rename to rx/rx.experimental.d.ts diff --git a/rx.js/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts similarity index 100% rename from rx.js/rx.joinpatterns.d.ts rename to rx/rx.joinpatterns.d.ts diff --git a/rx.js/rx.lite.d.ts b/rx/rx.lite.d.ts similarity index 100% rename from rx.js/rx.lite.d.ts rename to rx/rx.lite.d.ts diff --git a/rx.js/rx.testing.d.ts b/rx/rx.testing.d.ts similarity index 100% rename from rx.js/rx.testing.d.ts rename to rx/rx.testing.d.ts diff --git a/rx.js/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts similarity index 100% rename from rx.js/rx.time-lite.d.ts rename to rx/rx.time-lite.d.ts diff --git a/rx.js/rx.time.d.ts b/rx/rx.time.d.ts similarity index 100% rename from rx.js/rx.time.d.ts rename to rx/rx.time.d.ts diff --git a/rx.js/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts similarity index 100% rename from rx.js/rx.virtualtime.d.ts rename to rx/rx.virtualtime.d.ts From aef69df8b45cae140cf3696a84f4ecc98c05eda1 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:13:36 -0700 Subject: [PATCH 068/277] Fixed reference path in rx.jquery.d.ts --- rx-jquery/rx.jquery.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rx-jquery/rx.jquery.d.ts b/rx-jquery/rx.jquery.d.ts index ace0c5071..d3d405451 100644 --- a/rx-jquery/rx.jquery.d.ts +++ b/rx-jquery/rx.jquery.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface RxJQueryAjaxResult { data: T; From 3394ad045ed7febf7b6d05bccbc590c0e0a028e3 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:15:18 -0700 Subject: [PATCH 069/277] Fixed reference path to RxJS in knockout.rx.d.ts --- knockout.rx/knockout.rx.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index 71d95d758..7b98e25c2 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; From fb839ffeb94cc8b94a5f93825fd7bce209a40b1a Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Mon, 21 Jul 2014 18:36:03 -0700 Subject: [PATCH 070/277] Fixed reference of rx in promises-a-plus-tests.ts --- promises-a-plus/promises-a-plus-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/promises-a-plus/promises-a-plus-tests.ts b/promises-a-plus/promises-a-plus-tests.ts index 042c4f066..bba258649 100644 --- a/promises-a-plus/promises-a-plus-tests.ts +++ b/promises-a-plus/promises-a-plus-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// /// /// import When = require("../when/when"); From e917a9c81ea00b39281e75c69dd827ed3c0153c6 Mon Sep 17 00:00:00 2001 From: basarat Date: Tue, 22 Jul 2014 21:00:50 +1000 Subject: [PATCH 071/277] JQuery `originalEvent` should be of type `Event` closes #2545 --- jquery/jquery-tests.ts | 3 +++ jquery/jquery.d.ts | 7 ++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 920b95846..2f647c4d1 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -1494,6 +1494,9 @@ function test_eventParams() { $('#whichkey').bind('mousedown', function (e) { $('#log').html(e.type + ': ' + e.which); }); + $(window).on('mousewheel', (e) => { + var delta = (e.originalEvent).deltaY; + }); } function test_extend() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index eb6ec2e56..e40110c16 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -548,6 +548,7 @@ interface BaseJQueryEventObject extends Event { isImmediatePropagationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; + originalEvent: Event; preventDefault(): any; relatedTarget: Element; result: any; @@ -585,11 +586,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } -interface JQueryPopStateEventObject extends BaseJQueryEventObject { - originalEvent: PopStateEvent; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ } /* From fde9a8e787f472f252b163ba83ed4e86867e1834 Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Tue, 22 Jul 2014 20:58:26 +0200 Subject: [PATCH 072/277] 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 073/277] 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 074/277] 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 075/277] 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 076/277] 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 1a61ce3145b040904fc9eeaf4889cde480b57b1b Mon Sep 17 00:00:00 2001 From: Gil Amran Date: Wed, 23 Jul 2014 17:26:15 +0300 Subject: [PATCH 077/277] Removed webgl.d.ts (Included in lib.d.ts) Added missing x and y properties Added missing semicolon --- pixi/pixi.d.ts | 735 ++++++++++++++++++++++++------------------------ pixi/webgl.d.ts | 227 --------------- 2 files changed, 368 insertions(+), 594 deletions(-) delete mode 100644 pixi/webgl.d.ts diff --git a/pixi/pixi.d.ts b/pixi/pixi.d.ts index d5daba948..c86c1bd47 100644 --- a/pixi/pixi.d.ts +++ b/pixi/pixi.d.ts @@ -3,435 +3,436 @@ // Definitions by: xperiments // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// declare module PIXI { - /* STATICS */ - export var gl:WebGLRenderingContext; - export var BaseTextureCache: {}; - export var texturesToUpdate: BaseTexture[]; - export var texturesToDestroy: BaseTexture[]; - export var TextureCache: {}; - export var FrameCache: {}; - export var blendModes:{ NORMAL:number; SCREEN:number; }; + /* STATICS */ + export var gl:WebGLRenderingContext; + export var BaseTextureCache: {}; + export var texturesToUpdate: BaseTexture[]; + export var texturesToDestroy: BaseTexture[]; + export var TextureCache: {}; + export var FrameCache: {}; + export var blendModes:{ NORMAL:number; SCREEN:number; }; - /* MODULE FUNCTIONS */ - export function autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?: boolean): IPixiRenderer; - export function FilterBlock( mask:Graphics ):void; - export function MaskFilter( graphics:Graphics ):void; + /* MODULE FUNCTIONS */ + export function autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?: boolean): IPixiRenderer; + export function FilterBlock( mask:Graphics ):void; + export function MaskFilter( graphics:Graphics ):void; - /* DEBUG METHODS */ + /* DEBUG METHODS */ - export function runList( x ):void; + export function runList( x ):void; - /*INTERFACES*/ + /*INTERFACES*/ - export interface IBasicCallback - { - ():void - } + export interface IBasicCallback + { + ():void + } - export interface IEvent - { - type: string; - content: any; - } + export interface IEvent + { + type: string; + content: any; + } - export interface IHitArea - { - contains(x: number, y: number):boolean; - } + export interface IHitArea + { + contains(x: number, y: number):boolean; + } - export interface IInteractionDataCallback - { - (interactionData: InteractionData):void - } + export interface IInteractionDataCallback + { + (interactionData: InteractionData):void + } - export interface IPixiRenderer - { - view: HTMLCanvasElement; - render(stage: Stage): void; - } + export interface IPixiRenderer + { + view: HTMLCanvasElement; + render(stage: Stage): void; + } - export interface IBitmapTextStyle - { - font?: string; - align?: string; - } + export interface IBitmapTextStyle + { + font?: string; + align?: string; + } - export interface ITextStyle - { - font?: string; - stroke?: string; - fill?: string; - align?: string; - strokeThickness?: number; - wordWrap?: boolean; - wordWrapWidth?:number; - } + export interface ITextStyle + { + font?: string; + stroke?: string; + fill?: string; + align?: string; + strokeThickness?: number; + wordWrap?: boolean; + wordWrapWidth?:number; + } - /* CLASES */ + /* CLASES */ - export class AssetLoader extends EventTarget - { - assetURLs: string[]; - onComplete: IBasicCallback; - onProgress: IBasicCallback; - constructor(assetURLs: string[], crossorigin?:boolean ); - load(): void; - } + export class AssetLoader extends EventTarget + { + assetURLs: string[]; + onComplete: IBasicCallback; + onProgress: IBasicCallback; + constructor(assetURLs: string[], crossorigin?:boolean ); + load(): void; + } - export class BaseTexture extends EventTarget - { - height: number; - width: number; - source: string; + export class BaseTexture extends EventTarget + { + height: number; + width: number; + source: string; - constructor(source: HTMLImageElement); - constructor(source: HTMLCanvasElement); - destroy():void; + constructor(source: HTMLImageElement); + constructor(source: HTMLCanvasElement); + destroy():void; - static fromImage(imageUrl: string, crossorigin?:boolean ): BaseTexture; - } + static fromImage(imageUrl: string, crossorigin?:boolean ): BaseTexture; + } - export class BitmapFontLoader extends EventTarget - { - baseUrl:string; - crossorigin:boolean; - texture:Texture; - url:string; - constructor(url: string, crossorigin?: boolean); - load():void; - } + export class BitmapFontLoader extends EventTarget + { + baseUrl:string; + crossorigin:boolean; + texture:Texture; + url:string; + constructor(url: string, crossorigin?: boolean); + load():void; + } - export class BitmapText extends DisplayObjectContainer - { - width:number; - height:number; - constructor(text: string, style: IBitmapTextStyle); - setStyle(style: IBitmapTextStyle): void; - setText(text: string): void; - } + export class BitmapText extends DisplayObjectContainer + { + width:number; + height:number; + constructor(text: string, style: IBitmapTextStyle); + setStyle(style: IBitmapTextStyle): void; + setText(text: string): void; + } - export class CanvasRenderer implements IPixiRenderer - { - context: CanvasRenderingContext2D; - height: number; - view: HTMLCanvasElement; - width: number; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean); - render(stage: Stage): void; - resize(width: number, height: number):void; - } + export class CanvasRenderer implements IPixiRenderer + { + context: CanvasRenderingContext2D; + height: number; + view: HTMLCanvasElement; + width: number; + constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean); + render(stage: Stage): void; + resize(width: number, height: number):void; + } - export class Circle implements IHitArea - { - x: number; - y: number; - radius: number; - constructor(x: number, y: number, radius: number); - clone(): Circle; - contains(x: number, y: number):boolean; - } + export class Circle implements IHitArea + { + x: number; + y: number; + radius: number; + constructor(x: number, y: number, radius: number); + clone(): Circle; + contains(x: number, y: number):boolean; + } - // TODO what is renderGroup - export class CustomRenderable extends DisplayObject - { - constructor(); - renderCanvas(renderer: CanvasRenderer): void; - initWebGL(renderer: WebGLRenderer): void; - renderWebGL(renderGroup: any, projectionMatrix: any): void; - } + // TODO what is renderGroup + export class CustomRenderable extends DisplayObject + { + constructor(); + renderCanvas(renderer: CanvasRenderer): void; + initWebGL(renderer: WebGLRenderer): void; + renderWebGL(renderGroup: any, projectionMatrix: any): void; + } - export class DisplayObject - { - alpha: number; - buttonMode: boolean; - filter:boolean; - hitArea: IHitArea; - parent: DisplayObjectContainer; - pivot: Point; - position: Point; - rotation: number; - renderable: boolean; - scale: Point; - stage: Stage; - visible: boolean; - worldAlpha: number; - constructor(); - static autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean): IPixiRenderer; - click: IInteractionDataCallback; - mousedown: IInteractionDataCallback; - mouseout: IInteractionDataCallback; - mouseover: IInteractionDataCallback; - mouseup: IInteractionDataCallback; - mouseupoutside: IInteractionDataCallback; - mousemove: IInteractionDataCallback; - tap: IInteractionDataCallback; - touchend: IInteractionDataCallback; - touchendoutside: IInteractionDataCallback; - touchstart: IInteractionDataCallback; - touchmove: IInteractionDataCallback; + export class DisplayObject + { + x: number; + y: number; + alpha: number; + buttonMode: boolean; + filter:boolean; + hitArea: IHitArea; + parent: DisplayObjectContainer; + pivot: Point; + position: Point; + rotation: number; + renderable: boolean; + scale: Point; + stage: Stage; + visible: boolean; + worldAlpha: number; + constructor(); + static autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean): IPixiRenderer; + click: IInteractionDataCallback; + mousedown: IInteractionDataCallback; + mouseout: IInteractionDataCallback; + mouseover: IInteractionDataCallback; + mouseup: IInteractionDataCallback; + mouseupoutside: IInteractionDataCallback; + mousemove: IInteractionDataCallback; + tap: IInteractionDataCallback; + touchend: IInteractionDataCallback; + touchendoutside: IInteractionDataCallback; + touchstart: IInteractionDataCallback; + touchmove: IInteractionDataCallback; - //deprecated - setInteractive(interactive: boolean): void; + //deprecated + setInteractive(interactive: boolean): void; - // getters setters - interactive:boolean; - mask:Graphics; - } + // getters setters + interactive:boolean; + mask:Graphics; + } - export class DisplayObjectContainer extends DisplayObject - { - children: DisplayObject[]; - constructor(); + export class DisplayObjectContainer extends DisplayObject + { + children: DisplayObject[]; + constructor(); - addChild(child: DisplayObject): void; - addChildAt(child: DisplayObject, index: number): void; - getChildAt(index:number):DisplayObject; - removeChild(child: DisplayObject): void; - swapChildren(child: DisplayObject, child2: DisplayObject): void; - } + addChild(child: DisplayObject): void; + addChildAt(child: DisplayObject, index: number): void; + getChildAt(index:number):DisplayObject; + removeChild(child: DisplayObject): void; + swapChildren(child: DisplayObject, child2: DisplayObject): void; + } - export class Ellipse implements IHitArea - { - x: number; - y: number; - width: number; - height: number; + export class Ellipse implements IHitArea + { + x: number; + y: number; + width: number; + height: number; - constructor(x: number, y: number, width: number, height: number); - clone(): Ellipse; - contains(x: number, y: number):boolean; - getBounds():Rectangle; - } + constructor(x: number, y: number, width: number, height: number); + clone(): Ellipse; + contains(x: number, y: number):boolean; + getBounds():Rectangle; + } - export class EventTarget - { - addEventListener(type: string, listener: (event: IEvent) => void ); - removeEventListener(type: string, listener: (event: IEvent) => void ); - dispatchEvent(event: IEvent); - } + export class EventTarget + { + addEventListener(type: string, listener: (event: IEvent) => void ); + removeEventListener(type: string, listener: (event: IEvent) => void ); + dispatchEvent(event: IEvent); + } - export class Graphics extends DisplayObjectContainer - { - lineWidth:number; - lineColor:string; - constructor(); + export class Graphics extends DisplayObjectContainer + { + lineWidth:number; + lineColor:string; + constructor(); - beginFill(color?: number, alpha?: number): void; - clear(): void; - drawCircle(x: number, y: number, radius: number): void; - drawElipse(x: number, y: number, width: number, height: number): void; - drawRect(x: number, y: number, width: number, height: number): void; - endFill(): void; - lineStyle(lineWidth?: number, color?: number, alpha?: number ): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; + beginFill(color?: number, alpha?: number): void; + clear(): void; + drawCircle(x: number, y: number, radius: number): void; + drawElipse(x: number, y: number, width: number, height: number): void; + drawRect(x: number, y: number, width: number, height: number): void; + endFill(): void; + lineStyle(lineWidth?: number, color?: number, alpha?: number ): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; - static POLY:number; - static RECT:number; - static CIRC:number; - static ELIP:number; - } + static POLY:number; + static RECT:number; + static CIRC:number; + static ELIP:number; + } - export class ImageLoader extends EventTarget - { - texture:Texture; - constructor(url: string, crossorigin?: boolean); - load(): void; - } + export class ImageLoader extends EventTarget + { + texture:Texture; + constructor(url: string, crossorigin?: boolean); + load(): void; + } - /* TODO determine type of originalEvent*/ - export class InteractionData - { - global: Point; - target: Sprite; - constructor(); - originalEvent:any; - getLocalPosition(displayObject: DisplayObject): Point; - } + /* TODO determine type of originalEvent*/ + export class InteractionData + { + global: Point; + target: Sprite; + constructor(); + originalEvent:any; + getLocalPosition(displayObject: DisplayObject): Point; + } - export class InteractionManager - { - mouse: InteractionData; - stage: Stage; - touchs:{ [id:string]:InteractionData }; - constructor(stage: Stage); - } + export class InteractionManager + { + mouse: InteractionData; + stage: Stage; + touchs:{ [id:string]:InteractionData }; + constructor(stage: Stage); + } - export class JsonLoader extends EventTarget - { - url:string; - crossorigin: boolean; - baseUrl:string; - loaded:boolean; - constructor(url: string, crossorigin?: boolean); - load(): void; - } + export class JsonLoader extends EventTarget + { + url:string; + crossorigin: boolean; + baseUrl:string; + loaded:boolean; + constructor(url: string, crossorigin?: boolean); + load(): void; + } - export class MovieClip extends Sprite - { - animationSpeed: number; - currentFrame:number; - loop: boolean; - playing: boolean; - textures: Texture[]; - constructor(textures: Texture[]); - onComplete:IBasicCallback; - gotoAndPlay(frameNumber: number): void; - gotoAndStop(frameNumber: number): void; - play(): void; - stop(): void; - } + export class MovieClip extends Sprite + { + animationSpeed: number; + currentFrame:number; + loop: boolean; + playing: boolean; + textures: Texture[]; + constructor(textures: Texture[]); + onComplete:IBasicCallback; + gotoAndPlay(frameNumber: number): void; + gotoAndStop(frameNumber: number): void; + play(): void; + stop(): void; + } - export class Point - { - x: number; - y: number; - constructor(x: number, y: number); - clone(): Point; - } + export class Point + { + x: number; + y: number; + constructor(x: number, y: number); + clone(): Point; + } - export class Polygon implements IHitArea - { - points: Point[]; + export class Polygon implements IHitArea + { + points: Point[]; - constructor(points: Point[]); - constructor(points: number[]); - constructor(...points: Point[]); - constructor(...points: number[]); + constructor(points: Point[]); + constructor(points: number[]); + constructor(...points: Point[]); + constructor(...points: number[]); - clone(): Polygon; - contains( x:number, y:number ):boolean; - } + clone(): Polygon; + contains( x:number, y:number ):boolean; + } - export class Rectangle implements IHitArea - { - x: number; - y: number; - width: number; - height: number; - constructor(x: number, y: number, width: number, height: number); - clone(): Rectangle; - contains(x: number, y: number):boolean - } + export class Rectangle implements IHitArea + { + x: number; + y: number; + width: number; + height: number; + constructor(x: number, y: number, width: number, height: number); + clone(): Rectangle; + contains(x: number, y: number):boolean; + } - export class RenderTexture extends Texture - { - constructor(width: number, height: number); - resize(width: number, height: number): void; - } + export class RenderTexture extends Texture + { + constructor(width: number, height: number); + resize(width: number, height: number): void; + } - export class Sprite extends DisplayObjectContainer - { - anchor: Point; - blendMode: number; - texture: Texture; + export class Sprite extends DisplayObjectContainer + { + anchor: Point; + blendMode: number; + texture: Texture; - //getters setters - height: number; - width: number; + //getters setters + height: number; + width: number; - constructor(texture: Texture); + constructor(texture: Texture); - static fromFrame(frameId: string): Sprite; - static fromImage(url: string): Sprite; - setTexture(texture: Texture): void; - } + static fromFrame(frameId: string): Sprite; + static fromImage(url: string): Sprite; + setTexture(texture: Texture): void; + } - /* TODO determine type of frames */ - export class SpriteSheetLoader extends EventTarget - { - url:string; - crossorigin:boolean; - baseUrl:string; - texture:Texture; - frames:Object; - constructor(url: string, crossorigin?: boolean); - load(); - } + /* TODO determine type of frames */ + export class SpriteSheetLoader extends EventTarget + { + url:string; + crossorigin:boolean; + baseUrl:string; + texture:Texture; + frames:Object; + constructor(url: string, crossorigin?: boolean); + load(); + } - export class Stage extends DisplayObjectContainer - { - interactive:boolean; - interactionManager:InteractionManager; - constructor(backgroundColor: number, interactive?: boolean); - getMousePosition(): Point; - setBackgroundColor(backgroundColor: number): void; - } + export class Stage extends DisplayObjectContainer + { + interactive:boolean; + interactionManager:InteractionManager; + constructor(backgroundColor: number, interactive?: boolean); + getMousePosition(): Point; + setBackgroundColor(backgroundColor: number): void; + } - export class Text extends Sprite - { - constructor(text: string, style: ITextStyle); - destroy(destroyTexture:boolean):void; - setText(text: string): void; - setStyle(style: ITextStyle): void; - } + export class Text extends Sprite + { + constructor(text: string, style: ITextStyle); + destroy(destroyTexture:boolean):void; + setText(text: string): void; + setStyle(style: ITextStyle): void; + } - export class Texture extends EventTarget - { - baseTexture: BaseTexture; - frame: Rectangle; - trim:Point; - render( displayObject:DisplayObject, position:Point, clear:boolean ):void; - constructor(baseTexture: BaseTexture, frame?: Rectangle); - destroy(destroyBase:boolean):void; - setFrame(frame: Rectangle): void; + export class Texture extends EventTarget + { + baseTexture: BaseTexture; + frame: Rectangle; + trim:Point; + render( displayObject:DisplayObject, position:Point, clear:boolean ):void; + constructor(baseTexture: BaseTexture, frame?: Rectangle); + destroy(destroyBase:boolean):void; + setFrame(frame: Rectangle): void; - static addTextureToCache(texture: Texture, id: string): void; - static fromCanvas(canvas: HTMLCanvasElement): Texture; - static fromFrame(frameId: string): Texture; - static fromImage(imageUrl: string, crossorigin?: boolean): Texture; - static removeTextureFromCache(id: any): Texture; - } + static addTextureToCache(texture: Texture, id: string): void; + static fromCanvas(canvas: HTMLCanvasElement): Texture; + static fromFrame(frameId: string): Texture; + static fromImage(imageUrl: string, crossorigin?: boolean): Texture; + static removeTextureFromCache(id: any): Texture; + } - export class TilingSprite extends DisplayObjectContainer - { - width:number; - height:number; - texture:Texture; - tilePosition: Point; - tileScale: Point; - constructor(texture: Texture, width: number, height: number); - setTexture( texture: Texture ):void; - } + export class TilingSprite extends DisplayObjectContainer + { + width:number; + height:number; + texture:Texture; + tilePosition: Point; + tileScale: Point; + constructor(texture: Texture, width: number, height: number); + setTexture( texture: Texture ):void; + } - export class WebGLBatch - { - constructor(webGLContext: WebGLRenderingContext); - clean():void; - restoreLostContext(gl:WebGLRenderingContext) - init(sprite: Sprite): void; - insertAfter(sprite: Sprite, previousSprite: Sprite): void; - insertBefore(sprite: Sprite, nextSprite: Sprite): void; - growBatch(): void; - merge(batch: WebGLBatch): void; - refresh(): void; - remove(sprite: Sprite): void; - render(): void; - split(sprite: Sprite): WebGLBatch; - update(): void; - } + export class WebGLBatch + { + constructor(webGLContext: WebGLRenderingContext); + clean():void; + restoreLostContext(gl:WebGLRenderingContext); + init(sprite: Sprite): void; + insertAfter(sprite: Sprite, previousSprite: Sprite): void; + insertBefore(sprite: Sprite, nextSprite: Sprite): void; + growBatch(): void; + merge(batch: WebGLBatch): void; + refresh(): void; + remove(sprite: Sprite): void; + render(): void; + split(sprite: Sprite): WebGLBatch; + update(): void; + } - /* Determine type of Object */ - export class WebGLRenderGroup - { - render(projection:Object):void; - } + /* Determine type of Object */ + export class WebGLRenderGroup + { + render(projection:Object):void; + } - export class WebGLRenderer implements IPixiRenderer - { - view: HTMLCanvasElement; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?:boolean ); - render(stage: Stage): void; - resize(width: number, height: number): void; - } + export class WebGLRenderer implements IPixiRenderer + { + view: HTMLCanvasElement; + constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?:boolean ); + render(stage: Stage): void; + resize(width: number, height: number): void; + } } @@ -440,7 +441,7 @@ declare function requestAnimFrame( animate: PIXI.IBasicCallback ); declare module PIXI.PolyK { - export function Triangulate( p:number[]):number[]; + export function Triangulate( p:number[]):number[]; } diff --git a/pixi/webgl.d.ts b/pixi/webgl.d.ts deleted file mode 100644 index ebf1204dc..000000000 --- a/pixi/webgl.d.ts +++ /dev/null @@ -1,227 +0,0 @@ -// Type definitions for WebGL -// Project: https://www.khronos.org/webgl/ -// Definitions by: xperiments -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface WebGLObject { - $__dummyprop__WebGLObject : any; -} - -interface WebGLBuffer extends WebGLObject { - $__dummyprop__WebGLBuffer : any; -} - -interface WebGLFramebuffer extends WebGLObject { - $__dummyprop__WebGLFramebuffer : any; -} - -interface WebGLProgram extends WebGLObject { - $__dummyprop__WebGLProgram : any; -} - -interface WebGLRenderbuffer extends WebGLObject { - $__dummyprop__WebGLRenderbuffer : any; -} - -interface WebGLShader extends WebGLObject { - $__dummyprop__WebGLShader : any; -} - -interface WebGLTexture extends WebGLObject { - $__dummyprop__WebGLTexture : any; -} - -interface WebGLUniformLocation { - $__dummyprop__WebGLUniformLocation : any; -} - -interface WebGLRenderingContext { - NUM_COMPRESSED_TEXTURE_FORMATS : number; - ACTIVE_UNIFORM_MAX_LENGTH : number; - INFO_LOG_LENGTH : number; - SHADER_SOURCE_LENGTH : number; - getContextAttributes() : WebGLContextAttributes; - isContextLost() : boolean; - getSupportedExtensions() : string[]; - getExtension(name : string) : any; - activeTexture(texture : number) : void; - attachShader(program : WebGLProgram, shader : WebGLShader) : void; - bindAttribLocation(program : WebGLProgram, index : number, name : string) : void; - bindBuffer(target : number, buffer : WebGLBuffer) : void; - bindFramebuffer(target : number, framebuffer : WebGLFramebuffer) : void; - bindRenderbuffer(target : number, renderbuffer : WebGLRenderbuffer) : void; - bindTexture(target : number, texture : WebGLTexture) : void; - blendColor(red : number, green : number, blue : number, alpha : number) : void; - blendEquation(mode : number) : void; - blendEquationSeparate(modeRGB : number, modeAlpha : number) : void; - blendFunc(sfactor : number, dfactor : number) : void; - blendFuncSeparate(srcRGB : number, dstRGB : number, srcAlpha : number, dstAlpha : number) : void; - bufferData(target : number, size : number, usage : number) : void; - bufferData(target : number, data : ArrayBufferView, usage : number) : void; - bufferData(target : number, data : ArrayBuffer, usage : number) : void; - bufferSubData(target : number, offset : number, data : ArrayBufferView) : void; - bufferSubData(target : number, offset : number, data : ArrayBuffer) : void; - checkFramebufferStatus(target : number) : number; - clear(mask : number) : void; - clearColor(red : number, green : number, blue : number, alpha : number) : void; - clearDepth(depth : number) : void; - clearStencil(s : number) : void; - colorMask(red : boolean, green : boolean, blue : boolean, alpha : boolean) : void; - compileShader(shader : WebGLShader) : void; - copyTexImage2D(target : number, level : number, internalformat : number, x : number, y : number, width : number, height : number, border : number) : void; - copyTexSubImage2D(target : number, level : number, xoffset : number, yoffset : number, x : number, y : number, width : number, height : number) : void; - createBuffer() : WebGLBuffer; - createFramebuffer() : WebGLFramebuffer; - createProgram() : WebGLProgram; - createRenderbuffer() : WebGLRenderbuffer; - createShader(type : number) : WebGLShader; - createTexture() : WebGLTexture; - cullFace(mode : number) : void; - deleteBuffer(buffer : WebGLBuffer) : void; - deleteFramebuffer(framebuffer : WebGLFramebuffer) : void; - deleteProgram(program : WebGLProgram) : void; - deleteRenderbuffer(renderbuffer : WebGLRenderbuffer) : void; - deleteShader(shader : WebGLShader) : void; - deleteTexture(texture : WebGLTexture) : void; - depthFunc(func : number) : void; - depthMask(flag : boolean) : void; - depthRange(zNear : number, zFar : number) : void; - detachShader(program : WebGLProgram, shader : WebGLShader) : void; - disable(cap : number) : void; - disableVertexAttribArray(index : number) : void; - drawArrays(mode : number, first : number, count : number) : void; - drawElements(mode : number, count : number, type : number, offset : number) : void; - enable(cap : number) : void; - enableVertexAttribArray(index : number) : void; - finish() : void; - flush() : void; - framebufferRenderbuffer(target : number, attachment : number, renderbuffertarget : number, renderbuffer : WebGLRenderbuffer) : void; - framebufferTexture2D(target : number, attachment : number, textarget : number, texture : WebGLTexture, level : number) : void; - frontFace(mode : number) : void; - generateMipmap(target : number) : void; - getActiveAttrib(program : WebGLProgram, index : number) : WebGLActiveInfo; - getActiveUniform(program : WebGLProgram, index : number) : WebGLActiveInfo; - getAttachedShaders(program : WebGLProgram) : WebGLShader[]; - getAttribLocation(program : WebGLProgram, name : string) : number; - getParameter(pname : number) : any; - getBufferParameter(target : number, pname : number) : any; - getError() : number; - getFramebufferAttachmentParameter(target : number, attachment : number, pname : number) : any; - getProgramParameter(program : WebGLProgram, pname : number) : any; - getProgramInfoLog(program : WebGLProgram) : string; - getRenderbufferParameter(target : number, pname : number) : any; - getShaderParameter(shader : WebGLShader, pname : number) : any; - getShaderInfoLog(shader : WebGLShader) : string; - getShaderSource(shader : WebGLShader) : string; - getTexParameter(target : number, pname : number) : any; - getUniform(program : WebGLProgram, location : WebGLUniformLocation) : any; - getUniformLocation(program : WebGLProgram, name : string) : WebGLUniformLocation; - getVertexAttrib(index : number, pname : number) : any; - getVertexAttribOffset(index : number, pname : number) : number; - hint(target : number, mode : number) : void; - isBuffer(buffer : WebGLBuffer) : boolean; - isEnabled(cap : number) : boolean; - isFramebuffer(framebuffer : WebGLFramebuffer) : boolean; - isProgram(program : WebGLProgram) : boolean; - isRenderbuffer(renderbuffer : WebGLRenderbuffer) : boolean; - isShader(shader : WebGLShader) : boolean; - isTexture(texture : WebGLTexture) : boolean; - lineWidth(width : number) : void; - linkProgram(program : WebGLProgram) : void; - pixelStorei(pname : number, param : number) : void; - polygonOffset(factor : number, units : number) : void; - readPixels(x : number, y : number, width : number, height : number, format : number, type : number, pixels : ArrayBufferView) : void; - renderbufferStorage(target : number, internalformat : number, width : number, height : number) : void; - sampleCoverage(value : number, invert : boolean) : void; - scissor(x : number, y : number, width : number, height : number) : void; - shaderSource(shader : WebGLShader, source : string) : void; - stencilFunc(func : number, ref : number, mask : number) : void; - stencilFuncSeparate(face : number, func : number, ref : number, mask : number) : void; - stencilMask(mask : number) : void; - stencilMaskSeparate(face : number, mask : number) : void; - stencilOp(fail : number, zfail : number, zpass : number) : void; - stencilOpSeparate(face : number, fail : number, zfail : number, zpass : number) : void; - texImage2D(target : number, level : number, internalformat : number, width : number, height : number, border : number, format : number, type : number, pixels : ArrayBufferView) : void; - texImage2D(target : number, level : number, internalformat : number, format : number, type : number, pixels : ImageData) : void; - texImage2D(target : number, level : number, internalformat : number, format : number, type : number, image : HTMLImageElement) : void; - texImage2D(target : number, level : number, internalformat : number, format : number, type : number, canvas : HTMLCanvasElement) : void; - texImage2D(target : number, level : number, internalformat : number, format : number, type : number, video : HTMLVideoElement) : void; - texParameterf(target : number, pname : number, param : number) : void; - texParameteri(target : number, pname : number, param : number) : void; - texSubImage2D(target : number, level : number, xoffset : number, yoffset : number, width : number, height : number, format : number, type : number, pixels : ArrayBufferView) : void; - texSubImage2D(target : number, level : number, xoffset : number, yoffset : number, format : number, type : number, pixels : ImageData) : void; - texSubImage2D(target : number, level : number, xoffset : number, yoffset : number, format : number, type : number, image : HTMLImageElement) : void; - texSubImage2D(target : number, level : number, xoffset : number, yoffset : number, format : number, type : number, canvas : HTMLCanvasElement) : void; - texSubImage2D(target : number, level : number, xoffset : number, yoffset : number, format : number, type : number, video : HTMLVideoElement) : void; - uniform1f(location : WebGLUniformLocation, x : number) : void; - uniform1fv(location : WebGLUniformLocation, v : Float32Array) : void; - uniform1fv(location : WebGLUniformLocation, v : number[]) : void; - uniform1i(location : WebGLUniformLocation, x : number) : void; - uniform1iv(location : WebGLUniformLocation, v : Int32Array) : void; - uniform1iv(location : WebGLUniformLocation, v : number[]) : void; - uniform2f(location : WebGLUniformLocation, x : number, y : number) : void; - uniform2fv(location : WebGLUniformLocation, v : Float32Array) : void; - uniform2fv(location : WebGLUniformLocation, v : number[]) : void; - uniform2i(location : WebGLUniformLocation, x : number, y : number) : void; - uniform2iv(location : WebGLUniformLocation, v : Int32Array) : void; - uniform2iv(location : WebGLUniformLocation, v : number[]) : void; - uniform3f(location : WebGLUniformLocation, x : number, y : number, z : number) : void; - uniform3fv(location : WebGLUniformLocation, v : Float32Array) : void; - uniform3fv(location : WebGLUniformLocation, v : number[]) : void; - uniform3i(location : WebGLUniformLocation, x : number, y : number, z : number) : void; - uniform3iv(location : WebGLUniformLocation, v : Int32Array) : void; - uniform3iv(location : WebGLUniformLocation, v : number[]) : void; - uniform4f(location : WebGLUniformLocation, x : number, y : number, z : number, w : number) : void; - uniform4fv(location : WebGLUniformLocation, v : Float32Array) : void; - uniform4fv(location : WebGLUniformLocation, v : number[]) : void; - uniform4i(location : WebGLUniformLocation, x : number, y : number, z : number, w : number) : void; - uniform4iv(location : WebGLUniformLocation, v : Int32Array) : void; - uniform4iv(location : WebGLUniformLocation, v : number[]) : void; - uniformMatrix2fv(location : WebGLUniformLocation, transpose : boolean, value : Float32Array) : void; - uniformMatrix2fv(location : WebGLUniformLocation, transpose : boolean, value : number[]) : void; - uniformMatrix3fv(location : WebGLUniformLocation, transpose : boolean, value : Float32Array) : void; - uniformMatrix3fv(location : WebGLUniformLocation, transpose : boolean, value : number[]) : void; - uniformMatrix4fv(location : WebGLUniformLocation, transpose : boolean, value : Float32Array) : void; - uniformMatrix4fv(location : WebGLUniformLocation, transpose : boolean, value : number[]) : void; - useProgram(program : WebGLProgram) : void; - validateProgram(program : WebGLProgram) : void; - vertexAttrib1f(indx : number, x : number) : void; - vertexAttrib1fv(indx : number, values : Float32Array) : void; - vertexAttrib1fv(indx : number, values : number[]) : void; - vertexAttrib2f(indx : number, x : number, y : number) : void; - vertexAttrib2fv(indx : number, values : Float32Array) : void; - vertexAttrib2fv(indx : number, values : number[]) : void; - vertexAttrib3f(indx : number, x : number, y : number, z : number) : void; - vertexAttrib3fv(indx : number, values : Float32Array) : void; - vertexAttrib3fv(indx : number, values : number[]) : void; - vertexAttrib4f(indx : number, x : number, y : number, z : number, w : number) : void; - vertexAttrib4fv(indx : number, values : Float32Array) : void; - vertexAttrib4fv(indx : number, values : number[]) : void; - vertexAttribPointer(indx : number, size : number, type : number, normalized : boolean, stride : number, offset : number) : void; - viewport(x : number, y : number, width : number, height : number) : void; -} - -interface WebGLContextEvent extends Event { - initWebGLContextEvent(typeArg : string, canBubbleArg : boolean, cancelableArg : boolean, statusMessageArg : string) : void; -} - -//Extend the window object with cross Browser callbacks so TS will not complain -//Also add the (non-standard) Canvas Element parameter for performance improvement -interface WindowAnimationTiming { - requestAnimationFrame(callback: FrameRequestCallback, canvas ?: HTMLCanvasElement): number; - //msRequestAnimationFrame(callback: FrameRequestCallback, canvas ?: HTMLCanvasElement): number; - mozRequestAnimationFrame(callback: FrameRequestCallback, canvas ?: HTMLCanvasElement): number; - webkitRequestAnimationFrame(callback: FrameRequestCallback, canvas ?: HTMLCanvasElement): number; - oRequestAnimationFrame(callback: FrameRequestCallback, canvas ?: HTMLCanvasElement): number; - - cancelRequestAnimationFrame(handle: number): void; - //msCancelRequestAnimationFrame(handle: number): void; - mozCancelRequestAnimationFrame(handle: number): void; - webkitCancelRequestAnimationFrame(handle: number): void; - oCancelRequestAnimationFrame(handle: number): void; -} - -//To make WebGL work -interface HTMLCanvasElement { - getContext(contextId: string, params : {}): WebGLRenderingContext; -} From 1e9a25470164976c069ecc4c7dce1941f60e85d8 Mon Sep 17 00:00:00 2001 From: Nickolas Westman Date: Wed, 23 Jul 2014 11:24:32 -0700 Subject: [PATCH 078/277] 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 079/277] 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 080/277] 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 081/277] 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 082/277] 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 083/277] 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 084/277] 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 085/277] 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 086/277] 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 087/277] 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 088/277] 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 089/277] 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 090/277] 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 091/277] 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 f60c44af614ced02ab504f5e58f76ae703faa3ed Mon Sep 17 00:00:00 2001 From: Gil Amran Date: Sat, 26 Jul 2014 13:31:35 +0300 Subject: [PATCH 092/277] webgl removed also from tests --- pixi/pixi-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/pixi/pixi-tests.ts b/pixi/pixi-tests.ts index de452f72e..6600bb121 100644 --- a/pixi/pixi-tests.ts +++ b/pixi/pixi-tests.ts @@ -1,5 +1,4 @@ /// -/// function PixiTests() { From f8cfab178847551b2a023f133ad10f2b9fca8c71 Mon Sep 17 00:00:00 2001 From: damianog Date: Sat, 26 Jul 2014 14:33:29 +0200 Subject: [PATCH 093/277] 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 094/277] 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 095/277] 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 096/277] 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 097/277] 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 098/277] 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 099/277] 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 100/277] 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 101/277] 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 102/277] 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 103/277] 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 104/277] 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 105/277] 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 106/277] 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 d0d8d7887c4edcd4da73b55ecfffe2651360cddd Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Tue, 29 Jul 2014 11:35:42 +0200 Subject: [PATCH 107/277] Fixed: D3.Layout.TreeLayout.nodes() returns Array instead of TreeLayout --- 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 598cd9f34..80de53804 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1128,7 +1128,7 @@ declare module D3 { /** * Runs the tree layout */ - nodes(root: GraphNode): TreeLayout; + nodes(root: GraphNode): Array; /** * Given the specified array of nodes, such as those returned by nodes, returns an array of objects representing the links from parent to child for each node */ From 22894235a23f59f738278398144d9fc57c002cd9 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:08:28 +0100 Subject: [PATCH 108/277] 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 109/277] 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 110/277] 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 111/277] 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 112/277] 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 113/277] 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 114/277] 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 115/277] 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 116/277] 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 117/277] 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 118/277] 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 119/277] 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 120/277] 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 121/277] 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 122/277] 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 123/277] 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 124/277] 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 125/277] 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 126/277] 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 127/277] 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 128/277] 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 129/277] 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 b71fbf13305f974da5bcedaacd81262405876d1c Mon Sep 17 00:00:00 2001 From: Georgie Date: Thu, 31 Jul 2014 10:50:27 -0700 Subject: [PATCH 130/277] Complete DataTable, DataView --- .../google.visualization.d.ts | 103 +++++++++++++++++- 1 file changed, 97 insertions(+), 6 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index f45f3f6a3..fb538d329 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -58,7 +58,7 @@ declare module google { setRefreshInterval(interval: number): void; setOption(key: string, value: any): void; setOptions(options: Object): void; - setView(view_spec: DataView): void; + setView(view_spec: string): void; } //#endregion @@ -71,17 +71,68 @@ declare module google { addColumn(descriptionObject: DataTableColumnDescription): number; addRow(cellObject: DataObjectCell): number; addRow(cellArray?: any[]): number; - addRows(count: number): number; - addRows(array: DataObjectCell[][]): number; - addRows(array: any[]): number; + addRows(numberOfEmptyRows: number): number; + addRows(rows: DataObjectCell[][]): number; + addRows(rows: any[][]): number; + clone(): DataTable; + getColumnId(columnIndex: number): String; + getColumnLabel(columnIndex: number): string; + getColumnPattern(columnIndex: number): string; + getColumnProperties(columnIndex: number): Properties; + getColumnProperty(columnIndex: number, name: string): any; + getColumnRange(columnIndex: number): { min: any; max: any }; + getColumnRole(columnIndex: string): string; + getColumnType(columnIndex: number): string; + getDistinctValues(columnIndex: number): any[]; getFilteredRows(filters: DataTableCellFilter[]): number[]; getFormattedValue(rowIndex: number, columnIndex: number): string; - getValue(rowIndex: number, columnIndex: number): any; getNumberOfColumns(): number; getNumberOfRows(): number; + getProperty(rowIndex: number, columnIndex: number, name: string): any; + getProperties(rowIndex: number, columnIndex: number): Properties; + getRowProperties(rowIndex: number): Properties; + getRowProperty(rowIndex: number, name: string): Properties; + getSortedRows(sortColumn: number): number[]; + getSortedRows(sortColumn: SortByColumn): number[]; + getSortedRows(sortColumns: number[]): number[]; + getSortedRows(sortColumns: SortByColumn[]): number[]; + getTableProperties(): Properties; + getTableProperty(name: string): any; + getValue(rowIndex: number, columnIndex: number): any; + insertColumn(columnIndex: number, type: string, label?: string, id?: string); + insertRows(rowIndex: number, numberOfEmptyRows: number); + insertRows(rowIndex: number, rows: DataObjectCell[][]); + insertRows(rowIndex: number, rows: any[][]); + removeColumn(columnIndex: number): void; + removeColumns(columnIndex: number, numberOfColumns: number): void; removeRow(rowIndex: number): void; removeRows(rowIndex: number, numberOfRows: number): void; + setCell(rowIndex: number, columnIndex: number, value?: any, formattedValue?: string, properties?: Properties): void; setColumnLabel(columnIndex: number, label: string): void; + setColumnProperty(columnIndex: number, name: string, value: any): void; + setColumnProperties(columnIndex: number, properties: Properties): void; + setFormattedValue(rowIndex: number, columnIndex: number, formattedValue: string): void; + setProperty(rowIndex: number, columnIndex: number, name: string, value: any): void; + setProperties(rowIndex: number, columnIndex: number, properties: Properties): void; + setRowProperty(rowIndex: number, name: string, value: any): void; + setRowProperties(rowIndex: number, properties: Properties): void; + setTableProperty(name: string, value: any): void; + setTableProperties(properties: Properties): void; + setValue(rowIndex: number, columnIndex: number, value: any); + sort(sortColumn: number): number[]; + sort(sortColumn: SortByColumn): number[]; + sort(sortColumns: number[]): number[]; + sort(sortColumns: SortByColumn[]): number[]; + toJSON(): string; + } + + export interface Properties { + [property: string]: any + } + + export interface SortByColumn { + column: number; + desc: boolean; } export interface DataTableColumnDescription { @@ -113,6 +164,9 @@ declare module google { export interface DataTableCellFilter { column: number; + value?: any; + minValue?: any; + maxValue?: any; } export interface DataObjectCell { @@ -139,7 +193,44 @@ declare module google { export class DataView { constructor(data: DataTable); constructor(data: DataView); - setColumns(columnIndexes: any[]): void; + + getColumnId(columnIndex: number): String; + getColumnLabel(columnIndex: number): string; + getColumnPattern(columnIndex: number): string; + getColumnProperty(columnIndex: number, name: string): any; + getColumnRange(columnIndex: number): { min: any; max: any }; + getColumnType(columnIndex: number): string; + getDistinctValues(columnIndex: number): any[]; + getFilteredRows(filters: DataTableCellFilter[]): number[]; + getFormattedValue(rowIndex: number, columnIndex: number): string; + getNumberOfColumns(): number; + getNumberOfRows(): number; + getProperty(rowIndex: number, columnIndex: number, name: string): any; + getProperties(rowIndex: number, columnIndex: number): Properties; + getRowProperty(rowIndex: number, name: string): Properties; + getSortedRows(sortColumn: number): number[]; + getSortedRows(sortColumn: SortByColumn): number[]; + getSortedRows(sortColumns: number[]): number[]; + getSortedRows(sortColumns: SortByColumn[]): number[]; + getTableProperty(name: string): any; + getValue(rowIndex: number, columnIndex: number): any; + getTableColumnIndex(viewColumnIndex: number): number; + getTableRowIndex(viewRowIndex: number): number; + getViewColumnIndex(tableColumnIndex: number): number; + getViewColumns(): number[]; + getViewRowIndex(tableRowIndex: number): number; + getViewRows(): number[]; + + hideColumns(columnIndexes: number[]): void; + hideRows(min: number, max: number): void; + hideRows(rowIndexes: number[]): void; + + setColumns(columnIndexes: number[]): void; + setRows(min: number, max: number): void; + setRows(rowIndexes: number[]); + + toDataTable(): DataTable; + toJSON(): string; } //#endregion From 9900804542bee0f8eb0ee99871dbaa7b860fd85f Mon Sep 17 00:00:00 2001 From: Georgie Date: Thu, 31 Jul 2014 11:04:51 -0700 Subject: [PATCH 131/277] Fixed setColumns, added void returns --- .../google.visualization.d.ts | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index fb538d329..2657d8274 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -99,10 +99,10 @@ declare module google { getTableProperties(): Properties; getTableProperty(name: string): any; getValue(rowIndex: number, columnIndex: number): any; - insertColumn(columnIndex: number, type: string, label?: string, id?: string); - insertRows(rowIndex: number, numberOfEmptyRows: number); - insertRows(rowIndex: number, rows: DataObjectCell[][]); - insertRows(rowIndex: number, rows: any[][]); + insertColumn(columnIndex: number, type: string, label?: string, id?: string): void; + insertRows(rowIndex: number, numberOfEmptyRows: number): void; + insertRows(rowIndex: number, rows: DataObjectCell[][]): void; + insertRows(rowIndex: number, rows: any[][]): void; removeColumn(columnIndex: number): void; removeColumns(columnIndex: number, numberOfColumns: number): void; removeRow(rowIndex: number): void; @@ -118,7 +118,7 @@ declare module google { setRowProperties(rowIndex: number, properties: Properties): void; setTableProperty(name: string, value: any): void; setTableProperties(properties: Properties): void; - setValue(rowIndex: number, columnIndex: number, value: any); + setValue(rowIndex: number, columnIndex: number, value: any): void; sort(sortColumn: number): number[]; sort(sortColumn: SortByColumn): number[]; sort(sortColumns: number[]): number[]; @@ -226,13 +226,25 @@ declare module google { hideRows(rowIndexes: number[]): void; setColumns(columnIndexes: number[]): void; + setColumns(columnIndexes: ColumnSpec[]): void; + setColumns(columnIndexes: any[]): void; setRows(min: number, max: number): void; - setRows(rowIndexes: number[]); + setRows(rowIndexes: number[]): void; toDataTable(): DataTable; toJSON(): string; } + export interface ColumnSpec { + calc: (dataTable: DataTable, row: number) => any; + type: string; + label?: string; + id?: string; + sourceColumn?: number; + properties?: Properties; + role?: string; + } + //#endregion //#region GeoChart From d564ddbb2c4f6642331f615eaa41d0ef46e14d5d Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Fri, 1 Aug 2014 11:29:04 +0900 Subject: [PATCH 132/277] 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 133/277] 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 134/277] 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 135/277] 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 136/277] 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 137/277] 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 138/277] 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 139/277] 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 140/277] 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 141/277] 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 142/277] 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 143/277] 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 144/277] 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 145/277] 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 146/277] 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 147/277] 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 148/277] 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 149/277] 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 150/277] 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 151/277] 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 152/277] 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 153/277] 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 154/277] 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 155/277] 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 156/277] 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 157/277] 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 158/277] 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 159/277] 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 160/277] 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 161/277] 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 162/277] 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 163/277] 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 164/277] 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 165/277] 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 166/277] 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 167/277] 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 168/277] 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 169/277] 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 170/277] [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 171/277] [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 172/277] 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 173/277] 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 174/277] 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 175/277] 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 176/277] 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 177/277] 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 178/277] 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 179/277] 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 180/277] 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 181/277] 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 182/277] 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 183/277] 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 184/277] 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 185/277] 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 186/277] 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 187/277] 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 188/277] 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 189/277] 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 190/277] 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 191/277] 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 192/277] 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 193/277] 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 194/277] 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 195/277] 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 196/277] 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 197/277] [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 198/277] [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 199/277] 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 200/277] 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 201/277] 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 202/277] 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 203/277] 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 204/277] 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 205/277] 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 206/277] 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 2736551e5a150dd42818ad5c5c755778802657f1 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Fri, 8 Aug 2014 17:42:16 +0200 Subject: [PATCH 207/277] Various fixes in three.d.ts --- threejs/three.d.ts | 421 ++++++++++++++++++++------------------------- 1 file changed, 190 insertions(+), 231 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 41a07f32b..55ecde323 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -413,7 +413,7 @@ declare module THREE { */ id: number; - uuid: number; + uuid: string; name: string; attributes: BufferAttribute[]; drawcalls: { start: number; count: number; index: number; }[]; @@ -944,7 +944,7 @@ declare module THREE { /** * */ - uuid: number; + uuid: string; /** * Optional name of the object (doesn't need to be unique). @@ -1053,11 +1053,6 @@ declare module THREE { 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. */ @@ -1743,15 +1738,6 @@ declare module THREE { } - 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(); @@ -1797,7 +1783,7 @@ declare module THREE { } - export class JSonLoaderResultGeometry extends Geometry { + export interface JSonLoaderResultGeometry extends Geometry { animation: AnimationData; } @@ -1830,7 +1816,7 @@ declare module THREE { } - export class MaterialLoader extends EventDispatcher { + export class MaterialLoader { constructor(manager?: LoadingManager); load(url: string, onLoad: (material: Material) => void): void; @@ -1838,7 +1824,7 @@ declare module THREE { parse(json: any): Material; } - export class ObjectLoader extends EventDispatcher { + export class ObjectLoader { constructor(manager?: LoadingManager); load(url: string, onLoad: (object: Object3D) => void): void; @@ -1853,7 +1839,7 @@ declare module THREE { * 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. */ - export class TextureLoader extends EventDispatcher { + export class TextureLoader { constructor(manager?: LoadingManager); crossOrigin: string; /** @@ -1865,7 +1851,7 @@ declare module THREE { setCrossOrigin(crossOrigin: string): void; } - export class XHRLoader extends EventDispatcher { + export class XHRLoader { constructor(manager?: LoadingManager); cache: Cache; @@ -1958,9 +1944,9 @@ declare module THREE { alphaTest: number; /** - * Enables/disables overdraw. If enabled, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is false. + * Enables/disables overdraw. If greater than zero, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is 0. */ - overdraw: boolean; + overdraw: number; /** * Defines whether this material is visible. Default is true. @@ -2093,7 +2079,7 @@ declare module THREE { clone(): MeshDepthMaterial; } - export class MeshFaceMaterial extends Material { + export class MeshFaceMaterial { constructor(materials?: Material[]); materials: Material[]; @@ -2552,154 +2538,153 @@ declare module THREE { } 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; + static aliceblue: number; + static antiquewhite: number; + static aqua: number; + static aquamarine: number; + static azure: number; + static beige: number; + static bisque: number; + static black: number; + static blanchedalmond: number; + static blue: number; + static blueviolet: number; + static brown: number; + static burlywood: number; + static cadetblue: number; + static chartreuse: number; + static chocolate: number; + static coral: number; + static cornflowerblue: number; + static cornsilk: number; + static crimson: number; + static cyan: number; + static darkblue: number; + static darkcyan: number; + static darkgoldenrod: number; + static darkgray: number; + static darkgreen: number; + static darkgrey: number; + static darkkhaki: number; + static darkmagenta: number; + static darkolivegreen: number; + static darkorange: number; + static darkorchid: number; + static darkred: number; + static darksalmon: number; + static darkseagreen: number; + static darkslateblue: number; + static darkslategray: number; + static darkslategrey: number; + static darkturquoise: number; + static darkviolet: number; + static deeppink: number; + static deepskyblue: number; + static dimgray: number; + static dimgrey: number; + static dodgerblue: number; + static firebrick: number; + static floralwhite: number; + static forestgreen: number; + static fuchsia: number; + static gainsboro: number; + static ghostwhite: number; + static gold: number; + static goldenrod: number; + static gray: number; + static green: number; + static greenyellow: number; + static grey: number; + static honeydew: number; + static hotpink: number; + static indianred: number; + static indigo: number; + static ivory: number; + static khaki: number; + static lavender: number; + static lavenderblush: number; + static lawngreen: number; + static lemonchiffon: number; + static lightblue: number; + static lightcoral: number; + static lightcyan: number; + static lightgoldenrodyellow: number; + static lightgray: number; + static lightgreen: number; + static lightgrey: number; + static lightpink: number; + static lightsalmon: number; + static lightseagreen: number; + static lightskyblue: number; + static lightslategray: number; + static lightslategrey: number; + static lightsteelblue: number; + static lightyellow: number; + static lime: number; + static limegreen: number; + static linen: number; + static magenta: number; + static maroon: number; + static mediumaquamarine: number; + static mediumblue: number; + static mediumorchid: number; + static mediumpurple: number; + static mediumseagreen: number; + static mediumslateblue: number; + static mediumspringgreen: number; + static mediumturquoise: number; + static mediumvioletred: number; + static midnightblue: number; + static mintcream: number; + static mistyrose: number; + static moccasin: number; + static navajowhite: number; + static navy: number; + static oldlace: number; + static olive: number; + static olivedrab: number; + static orange: number; + static orangered: number; + static orchid: number; + static palegoldenrod: number; + static palegreen: number; + static paleturquoise: number; + static palevioletred: number; + static papayawhip: number; + static peachpuff: number; + static peru: number; + static pink: number; + static plum: number; + static powderblue: number; + static purple: number; + static red: number; + static rosybrown: number; + static royalblue: number; + static saddlebrown: number; + static salmon: number; + static sandybrown: number; + static seagreen: number; + static seashell: number; + static sienna: number; + static silver: number; + static skyblue: number; + static slateblue: number; + static slategray: number; + static slategrey: number; + static snow: number; + static springgreen: number; + static steelblue: number; + static tan: number; + static teal: number; + static thistle: number; + static tomato: number; + static turquoise: number; + static violet: number; + static wheat: number; + static white: number; + static whitesmoke: number; + static yellow: number; + static yellowgreen: number; } export class Euler { @@ -3442,14 +3427,14 @@ declare module THREE { * * distanceTo(v:T):number; */ - distanceTo(v: Vector): number; + distanceTo?(v: Vector): number; /** * NOTE: Vector4 doesn't have the property. * * distanceToSquared(v:T):number; */ - distanceToSquared(v: Vector): number; + distanceToSquared?(v: Vector): number; /** * setLength(l:number):T; @@ -3913,36 +3898,22 @@ declare module THREE { /** * Sets X component of this vector. */ - setX(x: number): Vector2; + setX(x: number): Vector4; /** * Sets Y component of this vector. */ - setY(y: number): Vector2; + setY(y: number): Vector4; /** * Sets Z component of this vector. */ - setZ(z: number): Vector2; + setZ(z: number): Vector4; /** * Sets w component of this vector. */ - setW(w: number): Vector2; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceTo(v: Vector): number; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceToSquared(v: Vector): number; + setW(w: number): Vector4; } // Objects ////////////////////////////////////////////////////////////////////////////////// @@ -4065,7 +4036,7 @@ declare module THREE { clone(object?: PointCloud): PointCloud; } - export class Skeleton extends Mesh { + export class Skeleton { constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); bones: Bone[]; useVertexTexture: boolean; @@ -4249,11 +4220,6 @@ declare module THREE { */ sortObjects: boolean; - /** - * Defines whether the renderer should auto update objects. Default is true. - */ - autoUpdateObjects: boolean; - /** * Default is false. */ @@ -4433,7 +4399,6 @@ declare module THREE { */ render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; - initWebGLObjects(scene: Scene): void; initMaterial(material: Material, lights: Light[], fog: Fog, object: Object3D): void; /** @@ -4510,7 +4475,7 @@ declare module THREE { export class RenderableFace { constructor(); - color: number; + color: Color; material: Material; uvs: Vector2[][]; v1: RenderableVertex; @@ -4863,8 +4828,8 @@ declare module THREE { clone(): Texture; dispose(): void; - DEFAULT_IMAGE: any; - DEFAULT_MAPPING: any; + static DEFAULT_IMAGE: any; + static DEFAULT_MAPPING: any; } // Extras ///////////////////////////////////////////////////////////////////// @@ -4976,13 +4941,6 @@ declare module THREE { play(animation: Animation): void; stop(animation: Animation): void; update(deltaTimeMS: number): void; - - // deprecated - add(data: AnimationData): void; - // deprecated - get(name: string): AnimationData; - // deprecated - remove(name: string): void; }; export class MorphAnimation { @@ -5008,10 +4966,9 @@ declare module THREE { hierarchy: KeyFrames[]; currentTime: number; timeScale: number; - isPlaying: number; - isPaused: number; - loop: number; - JITCompile: boolean; + isPlaying: boolean; + isPaused: boolean; + loop: boolean; play(startTime?: number): void; stop(): void; @@ -5022,7 +4979,7 @@ declare module THREE { // Extras / Curves ///////////////////////////////////////////////////////////////////// export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); } export class ClosedSplineCurve3 extends Curve { constructor( points:Vector3[] ); @@ -5044,18 +5001,18 @@ declare module THREE { export class CubicBezierCurve3 extends Curve { constructor( v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3 ); - v0: Vector2; - v1: Vector2; - v2: Vector2; - v3: Vector2; + v0: Vector3; + v1: Vector3; + v2: Vector3; + v3: Vector3; getPoint(t: number): Vector3; } export class EllipseCurve extends Curve { constructor( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); - ax: number; - ay: number; + aX: number; + aY: number; xRadius: number; yRadius: number; aStartAngle: number; @@ -5077,8 +5034,8 @@ declare module THREE { export class LineCurve3 extends Curve { constructor( v1: Vector3, v2: Vector3 ); - v1: Vector2; - v2: Vector2; + v1: Vector3; + v2: Vector3; getPoint(t: number): Vector3; } @@ -5095,9 +5052,9 @@ declare module THREE { export class QuadraticBezierCurve3 extends Curve { constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); - v0: Vector2; - v1: Vector2; - v2: Vector2; + v0: Vector3; + v1: Vector3; + v2: Vector3; getPoint(t: number): Vector3; } @@ -5124,8 +5081,6 @@ declare module THREE { * class Curve<T extends Vector> */ export class Curve { - constructor(); - needsUpdate: boolean; /** @@ -5228,10 +5183,10 @@ declare module THREE { scaleWorld: Vector3; translationWorld: Vector3; - rotationWorld: Quaternion; + quaternionWorld: Quaternion; translationObject: Vector3; scaleObject: Vector3; - rotationObject: Quaternion; + quaternionObject: Quaternion; updateMatrixWorld(force?: boolean): void; } @@ -5246,13 +5201,18 @@ declare module THREE { ELLIPSE, } + export interface PathAction { + action: PathActions; + args: any; + } + /** * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. */ export class Path extends CurvePath { constructor(points?: Vector2); - actions: PathActions[]; + actions: PathAction[]; fromPoints(vectors: Vector2[]): void; moveTo(x: number, y: number): void; @@ -5366,7 +5326,6 @@ declare module THREE { constructor(shape: Shape, options?: any); constructor(shapes: Shape[], options?: any); - shapebb: BoundingBox; addShapeList(shapes: Shape[], options: any): ShapeGeometry; addShape(shape: Shape, options?: any): void; } From 8a1c9ebad9d96bc26856bbd41f337db3347af5c4 Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 8 Aug 2014 19:09:46 +0200 Subject: [PATCH 208/277] Updated DropboxJS Definitions --- dropboxjs/dropboxjs-tests.ts | 20 +- dropboxjs/dropboxjs.d.ts | 548 ++++++++++++++++++++++++++++++----- 2 files changed, 487 insertions(+), 81 deletions(-) diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts index cf5fd3827..efc6a3693 100644 --- a/dropboxjs/dropboxjs-tests.ts +++ b/dropboxjs/dropboxjs-tests.ts @@ -2,18 +2,18 @@ var browserClient = new Dropbox.Client({ key: "your-key-here" }); -browserClient.authenticate(function (error, client) { +browserClient.authenticate((error:any, client:Dropbox.Client) => { if (error) { alert(error); } - client.onError.addListener(function (error) { - if (window.console) { // Skip the "if" in node.js code. + client.onError.addListener((error:any) =>{ + if (window['console']) { // Skip the "if" in node.js code. console.error(error); } }); - client.getAccountInfo(function (error, accountInfo) { + client.getAccountInfo( (error:Dropbox.ApiError, accountInfo:Dropbox.AccountInfo) => { if (error) { alert(error); // Something went wrong. } @@ -21,7 +21,7 @@ browserClient.authenticate(function (error, client) { alert("Hello, " + accountInfo.name + "!"); }); - client.writeFile("hello_world.txt", "Hello, world!\n", function (error, stat) { + client.writeFile("hello_world.txt", "Hello, world!\n", (error:Dropbox.ApiError, stat:Dropbox.File.Stat ) => { if (error) { alert(error); // Something went wrong. } @@ -29,7 +29,7 @@ browserClient.authenticate(function (error, client) { alert("File saved as revision " + stat.versionTag); }); - client.readFile("hello_world.txt", function (error, data) { + client.readFile("hello_world.txt", (error:Dropbox.ApiError, data:string) => { if (error) { alert(error); // Something went wrong. } @@ -37,18 +37,18 @@ browserClient.authenticate(function (error, client) { alert(data); // data has the file's contents }); - client.readdir("/", function (error, entries) { + client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries?: Dropbox.File.Stat[]) => { if (error) { alert(error); // Something went wrong. } - alert("Your Dropbox contains " + entries.join(", ")); + alert("Your Dropbox contains " + filenames.join(", ")); }); }); -var serverClient = new Dropbox.Client({ +var serverClient:Dropbox.Client = new Dropbox.Client({ key: "your-key-here", secret: "your-secret-here" }); -serverClient.authDriver(new Dropbox.AuthDriver.NodeServer(8191)); \ No newline at end of file +serverClient.authDriver(new Dropbox.AuthDriver.NodeServer({port:8191})); \ No newline at end of file diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index a718fabaf..c40a69f4b 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -1,15 +1,367 @@ // Type definitions for dropbox-js // Project: https://github.com/dropbox/dropbox-js -// Definitions by: Steve Fenton +// Definitions by: Steve Fenton , Pedro Casaubon // Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module Dropbox { - export interface DropboxConfig { + + + interface QueryParams { + [key: string]: any; + } + interface Credentials { key: string; secret?: string; + token?: string; + uid?: string; } - export interface AccountInfoData { + + /* Callbacks */ + + interface AuthenticateCallback { + (err: ApiError, client: Client): void; + (err: AuthError, client: Client): void; + } + + interface QueryParamsCallback { + (queryParams: QueryParams): void; + } + + interface ClientFileReadCallback { + + (err: ApiError, fileContents: string, stat: File.Stat, rangeInfo: Http.RangeInfo): void; + } + + interface ClientFileWriteCallback { + + (err: ApiError, stat: File.Stat): void; + } + + interface ResumableUploadStepCallback { + (err: ApiError, uploadCursor: Http.UploadCursor): void; + } + + interface ReadThumbnailCallback { + (err: ApiError, imageData: string, stat: File.Stat): void; + (err: ApiError, imageData: Blob, stat: File.Stat): void; + } + + interface FileStatCallback { + (err: ApiError, stat: File.Stat): void; + } + + /* Options */ + + interface AuthenticateOptions { + interactive: boolean; + } + + interface SingOutOptions { + mustInvalidate: boolean; + } + + interface AccountInfoOptions { + httpCache: boolean; + } + + interface ClientFileReadOptions { + + versionTag?: string; + rev?: string; + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + binary?: boolean; + length?: number; + start?: number; + httpCache?: boolean; + } + + interface ClientFileWriteOptions { + lastVersionTag?: string; + parentRev?: string; + noOverwrite?: boolean; + } + + interface ReadDirOptions { + removed?: boolean; + deleted?: boolean; + limit?: any; + versionTag?: string; + contentHash?: string; + httpCache?: boolean; + } + + interface MakeURLOptions { + download?: boolean; + downloadHack?: boolean; + long?: boolean; + longUrl?: boolean; + } + + interface HistoryOptions { + limit?: number; + httpCache?: boolean; + + } + + interface ThumbnailUrlOptions { + png?: boolean; + format?: string; + size?: string; + } + + interface ReadThumbnailOptions extends ThumbnailUrlOptions { + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + } + + interface FindByNameOptions { + limit?: number; + removed?: boolean; + deleted?: boolean; + httpCache?: boolean; + + } + + interface RedirectOptions { + redirectUrl?: string; + redirectFile?: string; + scope?: string; + rememberUser?: boolean; + } + + module Util { + + class EventSource { + constructor(options: { cancelable: boolean }); + addListener(listener: (event: any) => void): EventSource; + removeListener(listener: (event: any) => void): EventSource; + dispatch(event: {}): boolean; + } + + class Oauth { + static queryParamsFromUrl(url: string): QueryParams; + static randomAuthStateParam(): string; + checkAuthStateParam(stateParam: string): boolean; + } + + class Xhr { + xhr: XMLHttpRequest; + onError: (error: ApiError, callBack: (error: ApiError) => void) => void; + + constructor(method: string, baseUrl: string); + static urlEncode(obj: {}): string; + static urlEncodeValue(obj: {}): string; + static urlDecode(string: {}): QueryParams; + + + setParams(params: QueryParams): Xhr; + setCallback(callback: (err: ApiError, responseType: string, metadataHeader: {}, headers: {}) => void): Xhr; + signWithOauth(oauth: Oauth, cacheFriendly: boolean): Xhr; + addOauthParams(oauth: Oauth): Xhr; + addOauthHeader(oauth: Oauth): Xhr; + + setBody(body: string): Xhr; + setBody(body: Blob): Xhr; + setBody(body: ArrayBuffer): Xhr; + + setResponseType(responseType: string): Xhr; + setHeader(headerName: string, value: string): Xhr; + reportResponseHeaders(): Xhr; + setFileField(fieldName: string, fileName: string, fileData: string, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: Blob, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: File, contentType?: string): void; + prepare(): Xhr; + send(callback: (err: ApiError, responseType: string, metadataHeader: {}) => void): Xhr; + onReadyStateChange(): void; + onXdrLoad(): void; + onXdrError(): void; + } + } + module Http { + class AppInfo { + static ICON_SMALL: number; + static ICON_LARGE: number; + static parse(appInfo: {}, appKey?: string): AppInfo; + name: string; + key: string; + canUseDatastores: boolean; + canUseFiles: boolean; + hasAppFolder: boolean; + canUseFullDropbox: boolean; + icon(width: number, height?: number): void; + } + + class PollResult { + static parse(response: {}): PollResult; + hasChanges: boolean; + retryAfter: number; + } + + class PulledChanges { + static parse(deltaInfo: {}): PulledChanges; + blankSlate: boolean; + cursorTag: string; + shouldPullAgain: boolean; + shouldBackOff: boolean; + cursor(): string; + } + + class PulledChange { + static parse(entry: {}): PulledChange; + path: string; + wasRemoved: boolean; + stat: File.Stat; + } + + class RangeInfo { + static parse(headerValue: string): RangeInfo; + start: number; + size: number; + end: number; + } + + class UploadCursor { + static parse(cursorData: string): UploadCursor; + static parse(cursorData: {}): UploadCursor; + constructor(cursorData: string); + constructor(cursorData: {}); + tag: string; + offset: number; + expiresAt: Date; + toJSON(): {}; + } + } + module File { + + interface StatOptions { + version: number; + removed: boolean; + deleted: boolean; + readDir: boolean; + versionTag: string; + rev: string; + contentHash: string; + hash: string; + httpCache: boolean; + } + + class ShareUrl { + static parse(urlData: string, isDirect: boolean): ShareUrl; + static parse(urlData: {}, isDirect: boolean): ShareUrl; + url: string; + expiresAt: Date; + isDirect: boolean; + isPreview: boolean; + toJSON(): {}; + } + + class CopyReference { + static parse(refData: string): CopyReference; + static parse(refData: {}): CopyReference; + tag: string; + expiresAt: Date; + toJSON(): {}; + } + + class Stat { + static parse(metadata: {}): Stat; + 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; + toJSON(): {}; + } + } + module AuthDriver { + + class IAuthDriver { + doAuthorize(authUrl: string, stateParam: string, client: Client, callback?: QueryParamsCallback): void; + } + + class BrowserBase { + static localStorage(): Storage; + static currentLocation(): string; + static cleanupLocation(): void; + + constructor(options: { scope: string; rememberUser: boolean }); + authType(): string; + onAuthStepChange(client: Client, callback: () => void): void; + locationStateParam(url: string): string; + } + + class Redirect { + constructor(options?: { redirectUrl: string; redirectFile: string; scope: string; rememberUser: boolean }); + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + + } + + class Popup extends IAuthDriver { + static locationOrigin(location: string): string; + static oauthReceiver(): void; + constructor(options?: RedirectOptions); + url(): string; + + } + + class ChromeApp extends IAuthDriver { + constructor(options?: { scope: string }); + } + + class ChromeExtension extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + } + + class Cordova extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + url(): string; + } + + class NodeServer extends IAuthDriver { + constructor(options?: { port: number; tls?: {} }); + authType(): string; + url(): string; + openBrowser(url: string): void; + createApp(): void; + closeServer(): void; + + // TODO check request response types + doRequest(request:any, response:any): void; + closeBrowser(response:any): void; + } + } + + + class AuthDriver { + authType(): string; + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client, callback: QueryParamsCallback): void; + getStateParam(client: Client, callback: (state: string) => void): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + onAuthStepChange(client: Client, callback: () => void): void; + } + + class AccountInfo { + static parse(acountInfo: {}): AccountInfo; name: string; email: string; countryCode: string; @@ -20,82 +372,136 @@ declare module Dropbox { usedQuota: number; privateBytes: number; sharedBytes: number; + json(): {}; } - export interface AccountInfo extends AccountInfoData { - parse(accountInfo: string): AccountInfo; - json(): AccountInfoData; + class ApiError { + status: number; + method: string; + url: string; + responseText: string; + response: {}; + + constructor(xhr: XMLHttpRequest, method: string, url: string); + + static NETWORK_ERROR: number; + static NO_CONTENT: number; + static INVALID_PARAM: number; + static INVALID_TOKEN: number; + static OAUTH_ERROR: number; + static NOT_FOUND: number; + static INVALID_METHOD: number; + static NOT_ACCEPTABLE: number; + static CONFLICT: number; + static RATE_LIMITED: number; + static SERVER_ERROR: number; + static OVER_QUOTA: number; } - 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; + class AuthError { + + code: string; + description: string; + uri: string; + constructor(queryString: QueryParams); + + static ACCESS_DENIED: string; + static INVALID_REQUEST: string; + static UNAUTHORIZED_CLIENT: string; + static INVALID_GRANT: string; + static INVALID_SCOPE: string; + static UNSUPPORTED_GRANT_TYPE: string; + static UNSUPPORTED_RESPONSE_TYPE: string; + static SERVER_ERROR: string; + static TEMPORARILY_UNAVAILABLE: string; } - 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; - } + class Client { + static ERROR: number; + static RESET: number; + static PARAM_SET: number; + static PARAM_LOADED: number; + static AUTHORIZED: number; + static DONE: number; + static SIGNED_OUT: number; - export interface FileStatistics extends FileStatisticsData { - parse(stats: string): FileStatistics; - json(): FileStatisticsData; - } + onXhr: Util.EventSource; + onError: Util.EventSource; + onAuthStepChange: Util.EventSource; + authStep: number; - 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; + constructor(options: Credentials); + authDriver(driver: AuthDriver.IAuthDriver): Client; dropboxUid(): string; + credentials(): Credentials; + + // TODO check the error interface + authenticate(): Client; + authenticate(callback: AuthenticateCallback): Client; + authenticate(options: AuthenticateOptions): Client; + authenticate(options: AuthenticateOptions, callback: AuthenticateCallback): Client; 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; + signOut(callback: (err: ApiError) => void): XMLHttpRequest; + signOut(options: SingOutOptions, callback: (err: ApiError) => void): XMLHttpRequest; + signOff(callback: (err: ApiError) => void): void; + signOff(options: SingOutOptions, callback: (err: ApiError) => void): void; + getAccountInfo(callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + getAccountInfo(options: AccountInfoOptions, callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + readFile(path: string, callback: ClientFileReadCallback): XMLHttpRequest; + readFile(path: string, options: ClientFileReadOptions, callback: ClientFileReadCallback): XMLHttpRequest; + writeFile(path: string, data: any, callback: ClientFileWriteCallback): XMLHttpRequest; + writeFile(path: string, data: any, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadStep(data: any, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadStep(data: any, cursor: Http.UploadCursor, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; + metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + makeUrl(path: string, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + makeUrl(path: string, options: MakeURLOptions, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + history(path: string, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + history(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + revisions(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): void; + thumbnailUrl(path: string, options?: ThumbnailUrlOptions): string; + readThumbnail(path: string, callback: ReadThumbnailCallback): XMLHttpRequest; + readThumbnail(path: string, options: ReadThumbnailOptions, callback: ReadThumbnailCallback): XMLHttpRequest; + revertFile(path: string, versionTag: string, callback: FileStatCallback): XMLHttpRequest; + restore(path: string, versionTag: string, callback: FileStatCallback): void; + findByName(path: string, namePattern: string, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + findByName(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + search(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): void; + makeCopyReference(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + copyRef(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + pullChanges(callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + delta(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + delta(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + pollForChanges(cursor: string, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + pollForChanges(cursor: Http.PulledChanges, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + mkdir(path: string, callback: FileStatCallback): XMLHttpRequest; + remove(path: string, callback: FileStatCallback): XMLHttpRequest; + unlink(path: string, callback: FileStatCallback): void; + delete(path: string, callback: FileStatCallback): void; + copy(from: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + copy(from: File.CopyReference, toPath: string, callback: FileStatCallback): XMLHttpRequest; + move(fromPath: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + appInfo(callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + appInfo(appKey: string, callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + + // TODO check if this can better be described + isAppDeveloper(userId:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + isAppDeveloper(userId:any, appKey:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: Http.AppInfo, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + reset(): Client; + setCredentials(credentials: Credentials): Client; + appHash(): string; + } - - export module AuthDriver { - export interface NodeServer { - new (port: number): any; - } - - export var NodeServer: NodeServer; - } - - export var Client: Client; -} +} \ No newline at end of file From 3878a37dfad2c3ad01d6be3988aa7d5460519b58 Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 8 Aug 2014 19:10:43 +0200 Subject: [PATCH 209/277] 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 210/277] 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 211/277] 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 212/277] 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 213/277] 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 214/277] 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 215/277] 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 216/277] 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 217/277] 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 218/277] 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 219/277] 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 220/277] 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 From 5e202a9846bae747fe94bb945efefe137821320f Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 10 Aug 2014 21:34:48 +0800 Subject: [PATCH 221/277] add res.sendFile and mark res.sendfile as deprecated --- express/express.d.ts | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index d9551e22b..439adc141 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -485,14 +485,18 @@ declare module "express" { * * Options: * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. * * Examples: * - * The following example illustrates how `res.sendfile()` may + * 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 + * 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){ @@ -501,16 +505,35 @@ declare module "express" { * * req.user.mayViewFilesFrom(uid, function(yes){ * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); + * res.sendFile('/uploads/' + uid + '/' + file); * } else { * res.send(403, 'Sorry! you cant see that.'); * } * }); * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * deprecated, use sendFile instead. */ sendfile(path: string): void; + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, options: any): void; + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, fn: Errback): void; + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, options: any, fn: Errback): void; /** From e74fdd30bed040fa7eb63348de2b82ca6965a5c5 Mon Sep 17 00:00:00 2001 From: "Jason R. McNeil" Date: Wed, 6 Aug 2014 12:07:37 -0700 Subject: [PATCH 222/277] Add Builder support/options to xml2js --- xml2js/xml2js-tests.ts | 10 ++++++ xml2js/xml2js.d.ts | 77 +++++++++++++++++++++++++++++------------- 2 files changed, 63 insertions(+), 24 deletions(-) diff --git a/xml2js/xml2js-tests.ts b/xml2js/xml2js-tests.ts index 3e3fbb661..f2d9dc41e 100644 --- a/xml2js/xml2js-tests.ts +++ b/xml2js/xml2js-tests.ts @@ -5,3 +5,13 @@ import xml2js = require('xml2js'); xml2js.parseString("Hello xml2js!", (err: any, result: any) => { }); xml2js.parseString("Hello xml2js!", {trim: true}, (err: any, result: any) => { }); + +var builder = new xml2js.Builder({ + renderOpts: { + pretty: false + } +}); + +var outString = builder.buildObject({ + 'hello': 'xml2js!' +}); diff --git a/xml2js/xml2js.d.ts b/xml2js/xml2js.d.ts index 30aa64a87..f734e4ba0 100644 --- a/xml2js/xml2js.d.ts +++ b/xml2js/xml2js.d.ts @@ -1,6 +1,6 @@ // Type definitions for node-xml2js // Project: https://github.com/Leonidas-from-XIV/node-xml2js -// Definitions by: Michel Salib +// Definitions by: Michel Salib , Jason McNeil // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'xml2js' { @@ -8,29 +8,58 @@ declare module 'xml2js' { export = xml2js; module xml2js { - function parseString(xml:string, callback: (err: any, result:any) => void): void; - function parseString(xml:string, options: Options, callback: (err: any, result:any) => void): void; + function parseString(xml: string, callback: (err: any, result: any) => void): void; + function parseString(xml: string, options: Options, callback: (err: any, result: any) => void): void; - interface Options { - attrkey?: string; - charkey?: string; - explicitCharkey?: boolean; - trim?: boolean; - normalizeTags?: boolean; - normalize?: boolean; - explicitRoot?: boolean; - emptyTag?: any; - explicitArray?: boolean; - ignoreAttrs?: boolean; - mergeAttrs?: boolean; - validator?: Function; - xmlns?: boolean; - explicitChildren?: boolean; - charsAsChildren?: boolean; - async?: boolean; - strict?: boolean; - attrNameProcessors?: (name: string) => string; - tagNameProcessors?: (name: string) => string; - } + class Builder { + constructor(options?: BuilderOptions); + buildObject(rootObj: any): string; + } + + interface RenderOptions { + indent?: string; + newline?: string; + pretty?: boolean; + } + + interface XMLDeclarationOptions { + encoding?: string; + standalone?: boolean; + version?: string; + } + + interface BuilderOptions { + doctype?: any; + headless?: boolean; + indent?: string; + newline?: string; + pretty?: boolean; + renderOpts?: RenderOptions; + rootName?: string; + xmldec?: XMLDeclarationOptions; + } + + interface Options { + async?: boolean; + attrkey?: string; + attrNameProcessors?: (name: string) => string; + charkey?: string; + charsAsChildren?: boolean; + childkey?: string; + emptyTag?: any; + explicitArray?: boolean; + explicitCharkey?: boolean; + explicitChildren?: boolean; + explicitRoot?: boolean; + ignoreAttrs?: boolean; + mergeAttrs?: boolean; + normalize?: boolean; + normalizeTags?: boolean; + strict?: boolean; + tagNameProcessors?: (name: string) => string; + trim?: boolean; + validator?: Function; + xmlns?: boolean; + } } } From 3a8aadde8fbceaf599bde9be121a09508edc8760 Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:44:18 -0700 Subject: [PATCH 223/277] Updates for current compatibility... 1) Make Object3D inherit from EventDispatcher because it does... 2) Add setSize and domElement to Renderer interface because they are commonly used in boilerplate and it's better to return a "Renderer" depending on what is available. 3) Update ParticleSystemMaterial to PointCloudMaterial since ParticleSystemMaterial is deprecated. --- threejs/three.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 748900166..371e37da0 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -891,7 +891,7 @@ declare module THREE { /** * Base class for scene graph objects */ - export class Object3D { + export class Object3D extends EventDispatcher { constructor(); /** @@ -2169,7 +2169,7 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface ParticleSystemMaterialParameters { + export interface PointCloutMaterialParameters { color?: number; map?: Texture; size?: number; @@ -2178,7 +2178,7 @@ declare module THREE { fog?: boolean; } - export class ParticleSystemMaterial extends Material { + export class PointCloudMaterial extends Material { constructor(parameters?: ParticleSystemMaterialParameters); color: Color; map: Texture; @@ -3806,9 +3806,9 @@ declare module THREE { * @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); /** @@ -3872,6 +3872,8 @@ declare module THREE { export interface Renderer { render(scene: Scene, camera: Camera): void; + setSize(width:number, height:number, updateStyle?:boolean): void; + domElement: HTMLCanvasElement; } export interface CanvasRendererParameters { From 39a3186f8d15cbda489a53cba9c4416e424fdeea Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:47:40 -0700 Subject: [PATCH 224/277] Fixed typo PointClout to PointCloud --- threejs/three.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 371e37da0..584ad7df9 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2169,7 +2169,7 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface PointCloutMaterialParameters { + export interface PointCloudMaterialParameters { color?: number; map?: Texture; size?: number; From 6861331875bc5a6b6e410d5c3e4f00d84b7d56bd Mon Sep 17 00:00:00 2001 From: electricessence Date: Mon, 11 Aug 2014 11:49:19 -0700 Subject: [PATCH 225/277] Fixed tabbing --- threejs/three.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 584ad7df9..7cf3a0d78 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3872,8 +3872,8 @@ declare module THREE { export interface Renderer { render(scene: Scene, camera: Camera): void; - setSize(width:number, height:number, updateStyle?:boolean): void; - domElement: HTMLCanvasElement; + setSize(width:number, height:number, updateStyle?:boolean): void; + domElement: HTMLCanvasElement; } export interface CanvasRendererParameters { From dbd1973487d4f10fe371e8c19d8fe82f89549dd0 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 11 Aug 2014 13:44:29 -0700 Subject: [PATCH 226/277] Updated Force Layout nodes and links Different layouts have different definitions for node objects and link objects. I created a new `GraphNodeForce` and `GraphLinkForce` interface for the Force Layout. See the [docs](https://github.com/mbostock/d3/wiki/Force-Layout#nodes) for more info. --- d3/d3.d.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 2229fa8a4..026b6c405 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1237,6 +1237,21 @@ declare module D3 { source: GraphNode; target: GraphNode; } + + export interface GraphNodeForce { + index?: number; + x?: number; + y?: number; + px?: number; + py?: number; + fixed?: boolean; + weight?: number; + } + + export interface GraphLinkForce { + source: GraphNodeForce; + target: GraphNodeForce; + } export interface ForceLayout { (): ForceLayout; @@ -1287,14 +1302,14 @@ declare module D3 { }; links: { - (): GraphLink[]; - (arLinks: GraphLink[]): ForceLayout; + (): GraphLinkForce[]; + (arLinks: GraphLinkForce[]): ForceLayout; }; nodes: { - (): GraphNode[]; - (arNodes: GraphNode[]): ForceLayout; + (): GraphNodeForce[]; + (arNodes: GraphNodeForce[]): ForceLayout; }; start(): ForceLayout; From 1ad980949158f2a3d040f51edfdee1cfc7f7fb12 Mon Sep 17 00:00:00 2001 From: nitram509 Date: Mon, 11 Aug 2014 22:52:44 +0200 Subject: [PATCH 227/277] added missing optional method parameter 'intersecting' see http://fabricjs.com/docs/fabric.Object.html#sendBackwards http://fabricjs.com/docs/fabric.Object.html#bringForward --- fabricjs/fabricjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index cfca6c481..d532b1c56 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -324,7 +324,7 @@ declare module fabric { setWidth(value: number): IObject; // methods - bringForward(): IObject; + bringForward(intersecting?: boolean): IObject; bringToFront(): IObject; center(): IObject; centerH(): IObject; @@ -355,7 +355,7 @@ declare module fabric { scale(value: number): IObject; scaleToHeight(value: number): IObject; scaleToWidth(value: number): IObject; - sendBackwards(): IObject; + sendBackwards(intersecting?: boolean): IObject; sendToBack(): IObject; set (properties: IObjectOptions): IObject; From 455f9dce68a893a55d8ba17ce748b4b2932966be Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 12 Aug 2014 17:15:17 +0900 Subject: [PATCH 228/277] 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..0f8eb5c57 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -13,6 +13,7 @@ declare module ng.ui { templateUrl?: any; templateProvider?: () => string; controller?: any; + controllerAs?: string; controllerProvider?: any; resolve?: {}; url?: string; From 98118d8d39d79e538e2acf01fab37a5de8921e74 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Tue, 12 Aug 2014 16:38:53 +0200 Subject: [PATCH 229/277] three.js: Fix Quaternion.multiplyVector3 --- threejs/three.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 55ecde323..b9442abe3 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3193,7 +3193,10 @@ declare module THREE { */ multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - multiplyVector3(vector: Vector3, dest: Vector3): Quaternion; + /** + * Deprecated. Use Vector3.applyQuaternion instead + */ + multiplyVector3(vector: Vector3): Vector3; /** * Clones this quaternion. From decf4875a67c28d909ac46c9700e5a71c2d74c82 Mon Sep 17 00:00:00 2001 From: froginvasion Date: Wed, 13 Aug 2014 14:28:33 +0200 Subject: [PATCH 230/277] removed methods in collection that were mixed in that are no longer there. Removed from View, it isnt there anymore since 0.9.0 --- backbone/backbone.d.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 3aeeb7d90..270b949aa 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -215,12 +215,10 @@ declare module Backbone { any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; chain(): any; - compact(): TModel[]; contains(value: any): boolean; countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; countBy(attribute: string): _.Dictionary; detect(iterator: (item: any) => boolean, context?: any): any; // ??? - difference(...model: TModel[]): TModel[]; drop(): TModel; drop(n: number): TModel[]; each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; @@ -229,7 +227,6 @@ declare module Backbone { find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; first(): TModel; first(n: number): TModel[]; - flatten(shallow?: boolean): TModel[]; foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; @@ -239,7 +236,6 @@ declare module Backbone { initial(): TModel; initial(n: number): TModel[]; inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - intersection(...model: TModel[]): TModel[]; isEmpty(object: any): boolean; invoke(methodName: string, arguments?: any[]): any; last(): TModel; @@ -248,7 +244,6 @@ declare module Backbone { map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - object(...values: any[]): any[]; reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; select(iterator: any, context?: any): any[]; size(): number; @@ -257,8 +252,6 @@ declare module Backbone { sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; sortBy(attribute: string, context?: any): TModel[]; sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; - range(stop: number, step?: number): any; - range(start: number, stop: number, step?: number): any; reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; rest(): TModel; @@ -266,10 +259,7 @@ declare module Backbone { tail(): TModel; tail(n: number): TModel[]; toArray(): any[]; - union(...model: TModel[]): TModel[]; - uniq(isSorted?: boolean, iterator?: (element: TModel, index: number) => boolean): TModel[]; without(...values: any[]): TModel[]; - zip(...model: TModel[]): TModel[]; } class Router extends Events { @@ -349,7 +339,6 @@ declare module Backbone { model: TModel; collection: Collection; //template: (json, options?) => string; - make(tagName: string, attrs?: any, opts?: any): View; setElement(element: HTMLElement, delegate?: boolean): View; setElement(element: JQuery, delegate?: boolean): View; id: string; From e7e263cae12fa2e8479139eed898ff75bd406085 Mon Sep 17 00:00:00 2001 From: jandersonBB Date: Wed, 13 Aug 2014 14:16:13 -0700 Subject: [PATCH 231/277] Update jasmine.d.ts https://groups.google.com/forum/#!topic/jasmine-js/LwlC-yCksY4 --- jasmine/jasmine.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 34e30cdd1..e3f46ca17 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -45,6 +45,7 @@ declare module jasmine { function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; function getEnv(): Env; + function addMatchers(matchers: any): Any; interface Any { From 728ef7843f4d09d4514241d1684ad3c7be5400e8 Mon Sep 17 00:00:00 2001 From: Asger Feldthaus Date: Thu, 14 Aug 2014 11:07:02 +0200 Subject: [PATCH 232/277] three.js: Reverted change to MeshFaceMaterial --- threejs/three.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index b9442abe3..e86db17c4 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2079,7 +2079,7 @@ declare module THREE { clone(): MeshDepthMaterial; } - export class MeshFaceMaterial { + export class MeshFaceMaterial extends Material { constructor(materials?: Material[]); materials: Material[]; From a002a64b22572584599231ab1d19b029eb0e7317 Mon Sep 17 00:00:00 2001 From: yuuki Date: Fri, 15 Aug 2014 13:30:33 +0900 Subject: [PATCH 233/277] Fixed return type --- raphael/raphael.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index e57aa3954..82dba5d4c 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -215,7 +215,7 @@ interface RaphaelPaper { renderfix(): void; safari(): void; set(elements?: RaphaelElement[]): RaphaelSet; - setFinish(): void; + setFinish(): RaphaelSet; setSize(width: number, height: number): void; setStart(): void; setViewBox(x: number, y: number, w: number, h: number, fit: boolean): void; From 317fb99d45adda1a5e38e8096e859bba1a211b8b Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 14:11:21 +0200 Subject: [PATCH 234/277] Created typings file for timezonecomplete version 1.4.6 --- .../timezonecomplete-1.3.0-tests.ts | 174 +++ timezonecomplete/timezonecomplete-1.3.0.d.ts | 702 ++++++++++ timezonecomplete/timezonecomplete.d.ts | 1170 +++++++++++------ 3 files changed, 1612 insertions(+), 434 deletions(-) create mode 100644 timezonecomplete/timezonecomplete-1.3.0-tests.ts create mode 100644 timezonecomplete/timezonecomplete-1.3.0.d.ts diff --git a/timezonecomplete/timezonecomplete-1.3.0-tests.ts b/timezonecomplete/timezonecomplete-1.3.0-tests.ts new file mode 100644 index 000000000..142b3f25a --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.3.0-tests.ts @@ -0,0 +1,174 @@ +/// + +import tc = require("timezonecomplete"); + +var b: boolean = tc.isLeapYear(2014); +var n: number = tc.daysInMonth(2014, 10); +var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-1.3.0.d.ts b/timezonecomplete/timezonecomplete-1.3.0.d.ts new file mode 100644 index 000000000..6fbea6f6f --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.3.0.d.ts @@ -0,0 +1,702 @@ +// Type definitions for timezonecomplete 1.3.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle v0.2.0 + +declare module 'timezonecomplete' { + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns an ISO time string. Note that months are 1-12. + */ + export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + } + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ + toDate(): Date; + /** + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ + toString(): string; + } +} + diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 6fbea6f6f..46b202e8f 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,24 +1,54 @@ -// Type definitions for timezonecomplete 1.3.0 +// Type definitions for timezonecomplete 1.4.6 // Project: https://github.com/SpiritIT/timezonecomplete // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle v0.2.0 declare module 'timezonecomplete' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import dayOfYear = basics.dayOfYear; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + export import DateFunctions = javascript.DateFunctions; + import period = require("__timezonecomplete/period"); + export import Period = period.Period; + export import PeriodDst = period.PeriodDst; + export import periodDstToString = period.periodDstToString; + import timesource = require("__timezonecomplete/timesource"); + export import TimeSource = timesource.TimeSource; + export import RealTimeSource = timesource.RealTimeSource; + import timezone = require("__timezonecomplete/timezone"); + export import NormalizeOption = timezone.NormalizeOption; + export import TimeZoneKind = timezone.TimeZoneKind; + export import TimeZone = timezone.TimeZone; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); /** - * @return True iff the given year is a leap year. + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc */ - export function isLeapYear(year: number): boolean; - /** - * @param year The full year - * @param month The month 1-12 - * @return The number of days in the given month - */ - export function daysInMonth(year: number, month: number): number; - /** - * Returns an ISO time string. Note that months are 1-12. - */ - export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } /** * Time units */ @@ -31,6 +61,476 @@ declare module 'timezonecomplete' { Month = 5, Year = 6, } + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * The days in a given year + */ + export function daysInYear(year: number): number; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns the day of the year of the given date [0..365]. January first is 0. + * + * @param year The year e.g. 1986 + * @param month Month 1-12 + * @param day Day of month 1-31 + */ + export function dayOfYear(year: number, month: number, day: number): number; + /** + * Returns the last instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the last occurrence of the week day in the month + */ + export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is >= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is <= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Convert a unix milli timestamp into a TimeT structure. + * This does NOT take leap seconds into account. + */ + export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; + /** + * Convert a year, month, day etc into a unix milli timestamp. + * This does NOT take leap seconds into account. + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; + /** + * Convert a TimeT structure into a unix milli timestamp. + * This does NOT take leap seconds into account. + */ + export function timeToUnixNoLeapSecs(tm: TimeStruct): number; + /** + * Return the day-of-week. + * This does NOT take leap seconds into account. + */ + export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * Basic representation of a date and time + */ + export class TimeStruct { + /** + * Year, 1970-... + */ + year: number; + /** + * Month 1-12 + */ + month: number; + /** + * Day of month, 1-31 + */ + day: number; + /** + * Hour 0-23 + */ + hour: number; + /** + * Minute 0-59 + */ + minute: number; + /** + * Seconds, 0-59 + */ + second: number; + /** + * Milliseconds 0-999 + */ + milli: number; + /** + * Create a TimeStruct from a number of unix milliseconds + */ + static fromUnix(unixMillis: number): TimeStruct; + /** + * Create a TimeStruct from a JavaScript date + * + * @param d The date + * @param df Which functions to take (getX() or getUTCX()) + */ + static fromDate(d: Date, df: javascript.DateFunctions): TimeStruct; + /** + * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone + */ + static fromString(s: string): TimeStruct; + /** + * Constructor + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + constructor(/** + * Year, 1970-... + */ + year?: number, /** + * Month 1-12 + */ + month?: number, /** + * Day of month, 1-31 + */ + day?: number, /** + * Hour 0-23 + */ + hour?: number, /** + * Minute 0-59 + */ + minute?: number, /** + * Seconds, 0-59 + */ + second?: number, /** + * Milliseconds 0-999 + */ + milli?: number); + /** + * Validate a TimeStruct, returns false if invalid. + */ + validate(): boolean; + /** + * The day-of-year 0-365 + */ + yearDay(): number; + /** + * Returns this time as a unix millisecond timestamp + * Does NOT take leap seconds into account. + */ + toUnixNoLeapSecs(): number; + /** + * Deep equals + */ + equals(other: TimeStruct): boolean; + /** + * < operator + */ + lessThan(other: TimeStruct): boolean; + clone(): TimeStruct; + valueOf(): number; + /** + * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn + */ + toString(): string; + inspect(): string; + } +} + +declare module '__timezonecomplete/datetime' { + import basics = require("__timezonecomplete/basics"); + import duration = require("__timezonecomplete/duration"); + import javascript = require("__timezonecomplete/javascript"); + import timesource = require("__timezonecomplete/timesource"); + import timezone = require("__timezonecomplete/timezone"); + /** + * DateTime class which is time zone-aware + * and which can be mocked for testing purposes. + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: timesource.TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: timezone.TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * Non-existing local times are normalized by rounding up to the next DST offset. + * + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: timezone.TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * Non-existing local times are normalized by rounding up to the next DST offset. + * Note that the Date class has bugs and inconsistencies when constructing them with times around + * DST changes. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: javascript.DateFunctions, timeZone?: timezone.TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: timezone.TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: timezone.TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): timezone.TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): basics.WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): basics.WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: timezone.TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * Converting an unaware date to an aware date throws an exception. Use the constructor + * if you really need to do that. + * + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: timezone.TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + * This is because Date calculates getUTCX() from getX() applying local time zone. + */ + toDate(): Date; + /** + * Add a time duration relative to UTC. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * There is not DST handling. + * @return this + duration + */ + add(duration: duration.Duration): DateTime; + /** + * Add an amount of time relative to UTC, as regularly as possible. + * + * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month + * increments the utcMonth() field. + * Adding an amount of units leaves lower units intact. E.g. + * adding a month will leave the day() field untouched if possible. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + * + * In case of DST changes, the utc time fields are still untouched but local + * time fields may shift. + */ + add(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the time fields may additionally + * increase by the DST offset, if a non-existing local time would + * be reached otherwise. + * + * Adding a unit of time will leave lower-unit fields intact, unless the result + * would be a non-existing time. Then an extra DST offset is added. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + */ + addLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: duration.Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): duration.Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { /** * Time duration. Create one e.g. like this: var d = Duration.hours(1). * Note that time durations do not take leap seconds etc. into account: @@ -174,154 +674,18 @@ declare module 'timezonecomplete' { * added as necessary */ toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; } - /** - * The type of time zone - */ - export enum TimeZoneKind { - /** - * Local time offset as determined by JavaScript Date class. - */ - Local = 0, - /** - * Fixed offset from UTC, without DST. - */ - Offset = 1, - /** - * IANA timezone managed through Olsen TZ database. Includes - * DST if applicable. - */ - Proper = 2, - } - /** - * Time zone. The object is immutable because it is cached: - * requesting a time zone twice yields the very same object. - * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), - * i.e. offset 90 means +01:30. - * - * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, - * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST - * applied depending on the time zone rules. - */ - export class TimeZone { - /** - * The local time zone for a given date. Note that - * the time zone varies with the date: amsterdam time for - * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 - */ - static local(): TimeZone; - /** - * The UTC time zone. - */ - static utc(): TimeZone; - /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 - */ - static zone(offset: number): TimeZone; - /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - */ - static zone(s: string): TimeZone; - /** - * The time zone identifier. Can be an offset "-01:30" or an - * IANA time zone name "Europe/Amsterdam", or "localtime" for - * the local time zone. - */ - name(): string; - /** - * The kind of time zone (Local/Offset/Proper) - */ - kind(): TimeZoneKind; - /** - * Equality operator. Maps zero offsets and different names for UTC onto - * each other. Other time zones are not mapped onto each other. - */ - equals(other: TimeZone): boolean; - /** - * Is this zone equivalent to UTC? - */ - isUtc(): boolean; - /** - * Calculate timezone offset from a UTC time. - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ - offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Calculate timezone offset from a zone-local time (NOT a UTC time). - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time. - */ - offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForUtcDate(date: Date, funcs: DateFunctions): number; - /** - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForZoneDate(date: Date, funcs: DateFunctions): number; - /** - * The time zone identifier (normalized). - * Either "localtime", IANA name, or "+hh:mm" offset. - */ - toString(): string; - /** - * Convert an offset number into an offset string - * @param offset The offset in minutes from UTC e.g. 90 minutes - * @return the offset in ISO notation "+01:30" for +90 minutes - */ - static offsetToString(offset: number): string; - /** - * String to offset conversion. - * @param s Formats: "-01:00", "-0100", "-01", "Z" - * @return offset w.r.t. UTC in minutes - */ - static stringToOffset(s: string): number; - } - /** - * For testing purposes, we often need to manipulate what the current - * time is. This is an interface for a custom time source object - * so in tests you can use a custom time source. - */ - export interface TimeSource { - /** - * Return the current date+time as a javascript Date object - */ - now(): Date; - } - /** - * Default time source, returns actual time - */ - export class RealTimeSource implements TimeSource { - now(): Date; - } +} + +declare module '__timezonecomplete/javascript' { /** * Indicates how a Date object should be interpreted. * Either we can take getYear(), getMonth() etc for our field - * values, or we can take getUTCYear() etc to do that. + * values, or we can take getUTCYear(), getUtcMonth() etc to do that. */ export enum DateFunctions { /** @@ -333,275 +697,11 @@ declare module 'timezonecomplete' { */ GetUTC = 1, } - /** - * Day-of-week. Note the enum values correspond to JavaScript day-of-week: - * Sunday = 0, Monday = 1 etc - */ - export enum WeekDay { - Sunday = 0, - Monday = 1, - Tuesday = 2, - Wednesday = 3, - Thursday = 4, - Friday = 5, - Saturday = 6, - } - /** - * Our very own DateTime class which is time zone-aware - * and which can be mocked for testing purposes - */ - export class DateTime { - /** - * Actual time source in use. Setting this property allows to - * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() - * use this property for obtaining the current time. - */ - static timeSource: TimeSource; - /** - * Current date+time in local time (derived from DateTime.timeSource.now()). - */ - static nowLocal(): DateTime; - /** - * Current date+time in UTC time (derived from DateTime.timeSource.now()). - */ - static nowUtc(): DateTime; - /** - * Current date+time in the given time zone (derived from DateTime.timeSource.now()). - * @param timeZone The desired time zone. - */ - static now(timeZone: TimeZone): DateTime; - /** - * Constructor. Creates current time in local timezone. - */ - constructor(); - /** - * Constructor - * @param isoString String in ISO 8601 format. Instead of ISO time zone, - * it may include a space and then and IANA time zone. - * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) - * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) - * or "2007-04-05T12:30:40.500Z" (UTC) - * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) - * @param timeZone if given, the date in the string is assumed to be in this time zone. - * Note that it is NOT CONVERTED to the time zone. Useful - * for strings without a time zone - */ - constructor(isoString: string, timeZone?: TimeZone); - /** - * Constructor. You provide a date, then you say whether to take the - * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, - * and then you state which time zone that date is in. - * - * @param date A date object. - * @param getters Specifies which set of Date getters contains the date in the given time zone: the - * Date.getXxx() methods or the Date.getUTCXxx() methods. - * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) - */ - constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); - /** - * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. - * Use the add(duration) or sub(duration) for arithmetic. - * @param year The full year (e.g. 2014) - * @param month The month [1-12] (note this deviates from JavaScript Date) - * @param day The day of the month [1-31] - * @param hour The hour of the day [0-24) - * @param minute The minute of the hour [0-59] - * @param second The second of the minute [0-59] - * @param millisecond The millisecond of the second [0-999] - * @param timeZone The time zone, or null (for unaware dates) - */ - constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); - /** - * Constructor - * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 - * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). - */ - constructor(unixTimestamp: number, timeZone?: TimeZone); - /** - * @return a copy of this object - */ - clone(): DateTime; - /** - * @return The time zone that the date is in. May be null for unaware dates. - */ - zone(): TimeZone; - /** - * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. - */ - offset(): number; - /** - * @return The full year e.g. 2014 - */ - year(): number; - /** - * @return The month 1-12 (note this deviates from JavaScript Date) - */ - month(): number; - /** - * @return The day of the month 1-31 - */ - day(): number; - /** - * @return The hour 0-23 - */ - hour(): number; - /** - * @return the minutes 0-59 - */ - minute(): number; - /** - * @return the seconds 0-59 - */ - second(): number; - /** - * @return the milliseconds 0-999 - */ - millisecond(): number; - /** - * @return the day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - weekDay(): WeekDay; - /** - * @return Milliseconds since 1970-01-01T00:00:00.000Z - */ - unixUtcMillis(): number; - /** - * @return The full year e.g. 2014 - */ - utcYear(): number; - /** - * @return The UTC month 1-12 (note this deviates from JavaScript Date) - */ - utcMonth(): number; - /** - * @return The UTC day of the month 1-31 - */ - utcDay(): number; - /** - * @return The UTC hour 0-23 - */ - utcHour(): number; - /** - * @return The UTC minutes 0-59 - */ - utcMinute(): number; - /** - * @return The UTC seconds 0-59 - */ - utcSecond(): number; - /** - * @return The UTC milliseconds 0-999 - */ - utcMillisecond(): number; - /** - * @return the UTC day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - utcWeekDay(): WeekDay; - /** - * Convert this date to the given time zone (in-place). - * Throws if this date does not have a time zone. - * @return this (for chaining) - */ - convert(zone?: TimeZone): DateTime; - /** - * Returns this date converted to the given time zone. - * Unaware dates can only be converted to unaware dates (clone) - * For unaware dates, an exception is thrown - * @param zone The new time zone. This may be null to create unaware date. - * @return The converted date - */ - toZone(zone?: TimeZone): DateTime; - /** - * Convert to JavaScript date with the zone time in the getX() methods. - * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. - */ - toDate(): Date; - /** - * Add a time duration. Note that this simply adds a number - * of milliseconds to UTC and converts back to zone(), - * so in the presence of e.g. leap seconds there may be a - * shift in the seconds field if you add an hour. - * There is not DST handling and no leap second handling. - * @return this + duration - */ - add(duration: Duration): DateTime; - /** - * Add an amount of time to UTC, taking leap seconds etc into account. - * Adding e.g. 1 hour will increment the utcHour() field - * date by one. In case of DST changes, the local hour() field - * may not increase or increase by 2 hours. So if you add a month, the - * local time may vary by an hour. There will not be a shift - * in seconds due to leap seconds. - */ - add(amount: number, unit: TimeUnit): DateTime; - /** - * Add an amount of time to the zone time, as regularly as possible. - * Adding e.g. 1 hour will increment the hour() field of the zone - * date by one. In case of DST changes, the utcHour() field may - * increase by 1 or increase by 2. Adding a day will leave the time portion - * intact. However, adding an hour around a forward DST change adds two hours, - * since there is a zone time (2AM in Holland) that does not exist. - */ - addLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Same as add(-1*duration); - */ - sub(duration: Duration): DateTime; - /** - * Same as add(-1*amount, unit); - */ - sub(amount: number, unit: TimeUnit): DateTime; - /** - * Same as addLocal(-1*amount, unit); - */ - subLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Time difference between two DateTimes - * @return this - other - */ - diff(other: DateTime): Duration; - /** - * @return True iff (this < other) - */ - lessThan(other: DateTime): boolean; - /** - * @return True iff (this <= other) - */ - lessEqual(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time in UTC - */ - equals(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time and - * have the same zone - */ - identical(other: DateTime): boolean; - /** - * @return True iff this > other - */ - greaterThan(other: DateTime): boolean; - /** - * @return True iff this >= other - */ - greaterEqual(other: DateTime): boolean; - /** - * Proper ISO 8601 format string with any IANA zone converted to ISO offset - * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam - */ - toIsoString(): string; - /** - * Modified ISO 8601 format string with IANA name if applicable. - * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" - */ - toString(): string; - /** - * Modified ISO 8601 format string in UTC without time zone info - */ - toUtcString(): string; - } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import datetime = require("__timezonecomplete/datetime"); /** * Specifies how the period should repeat across the day * during DST changes. @@ -651,11 +751,11 @@ declare module 'timezonecomplete' { * @param dst Specifies how to handle Daylight Saving Time. Not relevant * if the time zone of the start datetime does not have DST. */ - constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + constructor(start: datetime.DateTime, amount: number, unit: basics.TimeUnit, dst: PeriodDst); /** * The start date */ - start(): DateTime; + start(): datetime.DateTime; /** * The amount of units */ @@ -663,7 +763,7 @@ declare module 'timezonecomplete' { /** * The unit */ - unit(): TimeUnit; + unit(): basics.TimeUnit; /** * The dst handling mode */ @@ -676,7 +776,7 @@ declare module 'timezonecomplete' { * @return the first date matching the period after fromDate, given * in the same zone as the fromDate. */ - findFirst(fromDate: DateTime): DateTime; + findFirst(fromDate: datetime.DateTime): datetime.DateTime; /** * Returns the next timestamp in the period. The given timestamp must * be at a period boundary, otherwise the answer is incorrect. @@ -686,17 +786,219 @@ declare module 'timezonecomplete' { * @param count Optional, must be >= 1 and whole. * @return (prev + count * period), in the same timezone as prev. */ - findNext(prev: DateTime, count?: number): DateTime; + findNext(prev: datetime.DateTime, count?: number): datetime.DateTime; /** - * Returns an ISO duration string - * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + * Returns an ISO duration string e.g. + * 2014-01-01T12:00:00.000+01:00/P1H + * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) + * 2014-01-01T12:00:00.000+01:00/P1M (one month) */ toIsoString(): string; /** * A string representation e.g. - * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". */ toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/timesource' { + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } +} + +declare module '__timezonecomplete/timezone' { + import javascript = require("__timezonecomplete/javascript"); + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Option for TimeZone#normalizeLocal() + */ + export enum NormalizeOption { + /** + * Normalize non-existing times by ADDING the DST offset + */ + Up = 0, + /** + * Normalize non-existing times by SUBTRACTING the DST offset + */ + Down = 1, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + */ + constructor(name: string); + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Does this zone have Daylight Saving Time at all? + */ + hasDst(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Normalizes non-existing local times by adding a forward offset change. + * During a forward standard offset change or DST offset change, some amount of + * local time is skipped. Therefore, this amount of local time does not exist. + * This function adds the amount of forward change to any non-existing time. After all, + * this is probably what the user meant. + * + * @param localUnixMillis Unix timestamp in zone time + * @param opt (optional) Round up or down? Default: up + * + * @returns Unix timestamp in zone time, normalized. + */ + normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; } } From 0ac4c6c592b3bcfa4dfa84c3b7d831384aac50cb Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 14:19:58 +0200 Subject: [PATCH 235/277] Adjusted tests for 1.4.6 --- timezonecomplete/timezonecomplete-tests.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index 142b3f25a..9f3833f71 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -2,9 +2,18 @@ import tc = require("timezonecomplete"); -var b: boolean = tc.isLeapYear(2014); -var n: number = tc.daysInMonth(2014, 10); -var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); +n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); // DURATION From ee6f317c09bebe1e398b155793338967f6efd34c Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 15 Aug 2014 15:51:08 +0200 Subject: [PATCH 236/277] Updated code to align to best practices Removed optional members in callbacks Removed explicit type inference for DT tests --- dropboxjs/dropboxjs-tests.ts | 4 ++-- dropboxjs/dropboxjs.d.ts | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts index efc6a3693..ad8e608a4 100644 --- a/dropboxjs/dropboxjs-tests.ts +++ b/dropboxjs/dropboxjs-tests.ts @@ -37,7 +37,7 @@ browserClient.authenticate((error:any, client:Dropbox.Client) => { alert(data); // data has the file's contents }); - client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries?: Dropbox.File.Stat[]) => { + client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries: Dropbox.File.Stat[]) => { if (error) { alert(error); // Something went wrong. } @@ -46,7 +46,7 @@ browserClient.authenticate((error:any, client:Dropbox.Client) => { }); }); -var serverClient:Dropbox.Client = new Dropbox.Client({ +var serverClient = new Dropbox.Client({ key: "your-key-here", secret: "your-secret-here" }); diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index c40a69f4b..ab3dbe2ee 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -455,12 +455,12 @@ declare module Dropbox { resumableUploadStep(data: any, cursor: Http.UploadCursor, callback: ResumableUploadStepCallback): XMLHttpRequest; resumableUploadFinish(path: string, cursor: Http.UploadCursor, callback: ClientFileWriteCallback): XMLHttpRequest; resumableUploadFinish(path: string, cursor: Http.UploadCursor, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; - stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries?: File.Stat[]) => void): XMLHttpRequest; - metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; - metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries?: File.Stat[]) => void): void; + stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; + metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; makeUrl(path: string, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; makeUrl(path: string, options: MakeURLOptions, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; history(path: string, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; From a2f96a4233934ff0bc1b42a873f1ed6a90ec0b12 Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Fri, 15 Aug 2014 15:54:09 +0200 Subject: [PATCH 237/277] Fixed unittest failure on old tests. --- timezonecomplete/timezonecomplete-1.2.0-tests.ts | 4 ++-- timezonecomplete/timezonecomplete-1.2.0.d.ts | 2 +- timezonecomplete/timezonecomplete-1.3.0-tests.ts | 4 ++-- timezonecomplete/timezonecomplete-1.3.0.d.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/timezonecomplete/timezonecomplete-1.2.0-tests.ts b/timezonecomplete/timezonecomplete-1.2.0-tests.ts index 03f94e44b..3ed4db796 100644 --- a/timezonecomplete/timezonecomplete-1.2.0-tests.ts +++ b/timezonecomplete/timezonecomplete-1.2.0-tests.ts @@ -1,6 +1,6 @@ -/// +/// -import tc = require("timezonecomplete"); +import tc = require("timezonecomplete-1.2.0"); var b: boolean = tc.isLeapYear(2014); var n: number = tc.daysInMonth(2014, 10); diff --git a/timezonecomplete/timezonecomplete-1.2.0.d.ts b/timezonecomplete/timezonecomplete-1.2.0.d.ts index 2f1b969bc..1a39be00e 100644 --- a/timezonecomplete/timezonecomplete-1.2.0.d.ts +++ b/timezonecomplete/timezonecomplete-1.2.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle 0.1.1 -declare module 'timezonecomplete' { +declare module 'timezonecomplete-1.2.0' { /** * @return True iff the given year is a leap year. */ diff --git a/timezonecomplete/timezonecomplete-1.3.0-tests.ts b/timezonecomplete/timezonecomplete-1.3.0-tests.ts index 142b3f25a..08145d275 100644 --- a/timezonecomplete/timezonecomplete-1.3.0-tests.ts +++ b/timezonecomplete/timezonecomplete-1.3.0-tests.ts @@ -1,6 +1,6 @@ -/// +/// -import tc = require("timezonecomplete"); +import tc = require("timezonecomplete-1.3.0"); var b: boolean = tc.isLeapYear(2014); var n: number = tc.daysInMonth(2014, 10); diff --git a/timezonecomplete/timezonecomplete-1.3.0.d.ts b/timezonecomplete/timezonecomplete-1.3.0.d.ts index 6fbea6f6f..d4960def4 100644 --- a/timezonecomplete/timezonecomplete-1.3.0.d.ts +++ b/timezonecomplete/timezonecomplete-1.3.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by dts-bundle v0.2.0 -declare module 'timezonecomplete' { +declare module 'timezonecomplete-1.3.0' { /** * @return True iff the given year is a leap year. */ From d7d5f7fc987c01049a19ef2af26daa8eb05f1e35 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 16 Aug 2014 12:32:41 +1000 Subject: [PATCH 238/277] Dropbox: Document reason for dummy class https://github.com/Microsoft/TypeScript/issues/371 --- dropboxjs/dropboxjs.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts index ab3dbe2ee..f9a2c9a40 100644 --- a/dropboxjs/dropboxjs.d.ts +++ b/dropboxjs/dropboxjs.d.ts @@ -290,6 +290,7 @@ declare module Dropbox { } module AuthDriver { + /** Do not use class! TypeScript definition implementation detail : https://github.com/Microsoft/TypeScript/issues/371 */ class IAuthDriver { doAuthorize(authUrl: string, stateParam: string, client: Client, callback?: QueryParamsCallback): void; } @@ -504,4 +505,4 @@ declare module Dropbox { appHash(): string; } -} \ No newline at end of file +} From 59ccd2392f65b87ce679f824bc291a8ada657e19 Mon Sep 17 00:00:00 2001 From: damianog Date: Sun, 17 Aug 2014 11:09:59 +0200 Subject: [PATCH 239/277] Update express.d.ts deprecate res.sendfile deprecate `res.sendfile` -- use `res.sendFile` instead --- express/express.d.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index d9551e22b..735e6db0e 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -490,9 +490,9 @@ declare module "express" { * * Examples: * - * The following example illustrates how `res.sendfile()` may + * 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 + * 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){ @@ -501,13 +501,18 @@ declare module "express" { * * req.user.mayViewFilesFrom(uid, function(yes){ * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); + * 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; + sendfile(path: string): void; sendfile(path: string, options: any): void; sendfile(path: string, fn: Errback): void; From 8c5eb7a46fdc787376cd9f6987a9c1d6d0c2086b Mon Sep 17 00:00:00 2001 From: Sergey Zarouski Date: Sun, 17 Aug 2014 22:08:46 -0400 Subject: [PATCH 240/277] add _.create to LoDashStatic Something is better then nothing, adding _.create method --- lodash/lodash.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index a4de09279..3e3fd43d7 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6210,6 +6210,16 @@ declare module _ { noop(): void; } + //_.create + interface LoDashStatic { + /** + * Creates an object that inherits from the given prototype object. If a properties object is provided its own enumerable properties are assigned to the created object. + * @param prototype The object to inherit from. + * @param properties The properties to assign to the object. + */ + create(prototype: Object, properties?: Object): Object; + } + interface ListIterator { (value: T, index: number, list: T[]): TResult; } From 1b08cdb2ead58cdc852628bd27b09c8c80f7581a Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Mon, 18 Aug 2014 11:24:47 +0900 Subject: [PATCH 241/277] Fixed the bug about EventDispatcher class. And changed JSonLoaderResultGeometry class because an interface that inherits a class causes an error in WebStorm (probably IDE's bug). --- threejs/three.d.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 5397d2561..2eb17c19b 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -469,6 +469,12 @@ declare module THREE { */ dispose(): void; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; } /** @@ -928,12 +934,19 @@ declare module THREE { computeLineDistances(): void; makeGroups(usesFaceMaterial: boolean, maxVerticesInGroup: number): void; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; } /** * Base class for scene graph objects */ - export class Object3D extends EventDispatcher { + export class Object3D { constructor(); /** @@ -1208,6 +1221,14 @@ declare module THREE { * @param angle The angle in radians. */ rotateOnAxis(axis: Vector3, angle: number): Object3D; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } /** @@ -1738,6 +1759,14 @@ declare module THREE { } + /* + * GeometryLoader class is experimental, and it is not yet included in the compiled source code. + * + export class GeometryLoader { + + } + */ + export class Cache{ constructor(); @@ -1783,7 +1812,7 @@ declare module THREE { } - export interface JSonLoaderResultGeometry extends Geometry { + export class JSonLoaderResultGeometry extends Geometry { animation: AnimationData; } @@ -1969,6 +1998,13 @@ declare module THREE { dispose(): void; setValues(values: Object): void; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; } export interface LineBasicMaterialParameters { @@ -2079,6 +2115,8 @@ declare module THREE { clone(): MeshDepthMaterial; } + // MeshFaceMaterial does not inherit the Material class in the original code. However, it should treat as Material class. + // See tests/canvas/canvas_materials.ts. export class MeshFaceMaterial extends Material { constructor(materials?: Material[]); materials: Material[]; @@ -4470,6 +4508,13 @@ declare module THREE { generateMipmaps: boolean; clone(): WebGLRenderTarget; dispose(): void; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; } export class WebGLRenderTargetCube extends WebGLRenderTarget { @@ -4837,6 +4882,13 @@ declare module THREE { static DEFAULT_IMAGE: any; static DEFAULT_MAPPING: any; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; } // Extras ///////////////////////////////////////////////////////////////////// From 87004e74a559a7aa160d0bafce50a28da1caf176 Mon Sep 17 00:00:00 2001 From: dinesh Date: Mon, 18 Aug 2014 12:00:16 +0800 Subject: [PATCH 242/277] Made the functions once, debounce, throttle, after to accept function with generics signature. The function returened from these functions will have signature as the functions passed into them, compiler should be made aware of this. --- underscore/underscore-tests.ts | 10 ++-- underscore/underscore.d.ts | 94 +++++++++++++++++----------------- 2 files changed, 52 insertions(+), 52 deletions(-) diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index 8b638ee50..2e550ee82 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -140,18 +140,18 @@ _.delay(log, 1000, 'logged later'); _.defer(function () { alert('deferred'); }); -var updatePosition = () => alert('updating position...'); +var updatePosition = (param:string) => alert('updating position... Param: ' + param); var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled); -var calculateLayout = () => alert('calculating layout...'); +var calculateLayout = (param:string) => alert('calculating layout... Param: ' + param); var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); -var createApplication = () => alert('creating application...'); +var createApplication = (param:string) => alert('creating application... Param: ' + param); var initialize = _.once(createApplication); -initialize(); -initialize(); +initialize("me"); +initialize("me"); var notes: any[]; var render = () => alert("rendering..."); diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 9736c2879..e17c6b662 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1033,62 +1033,62 @@ interface UnderscoreStatic { ...arguments: any[]): void; /** - * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, - * will only actually call the original function at most once per every wait milliseconds. Useful for - * rate-limiting events that occur faster than you can keep up with. - * By default, throttle will execute the function as soon as you call it for the first time, and, - * if you call it again any number of times during the wait period, as soon as that period is over. - * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable - * the execution on the trailing-edge, pass {trailing: false}. - * @param func Function to throttle `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. - * @return `fn` with a throttle of `wait`. - **/ - throttle( - func: any, + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * By default, throttle will execute the function as soon as you call it for the first time, and, + * if you call it again any number of times during the wait period, as soon as that period is over. + * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable + * the execution on the trailing-edge, pass {trailing: false}. + * @param func Function to throttle `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. + * @return `fn` with a throttle of `wait`. + **/ + throttle( + func: T, wait: number, - options?: _.ThrottleSettings): Function; + options?: _.ThrottleSettings): T; /** - * Creates and returns a new debounced version of the passed function that will postpone its execution - * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing - * behavior that should only happen after the input has stopped arriving. For example: rendering a preview - * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. - * - * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead - * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double - *-clicks on a "submit" button from firing a second time. - * @param fn Function to debounce `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. - * @return Debounced version of `fn` that waits `wait` ms when invoked. - **/ - debounce( - fn: Function, + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing + * behavior that should only happen after the input has stopped arriving. For example: rendering a preview + * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `wait` ms when invoked. + **/ + debounce( + fn: T, wait: number, - immediate?: boolean): Function; + immediate?: boolean): T; /** - * Creates a version of the function that can only be called one time. Repeated calls to the modified - * function will have no effect, returning the value from the original call. Useful for initialization - * functions, instead of having to set a boolean flag and then check it later. - * @param fn Function to only execute once. - * @return Copy of `fn` that can only be invoked once. - **/ - once(fn: Function): Function; + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ + once(fn: T): T; /** - * Creates a version of the function that will only be run after first being called count times. Useful - * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, - * before proceeding. - * @param count Number of times to be called before actually executing. - * @fn The function to defer execution `count` times. - * @return Copy of `fn` that will not execute until it is invoked `count` times. - **/ - after( + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param count Number of times to be called before actually executing. + * @fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ + after( count: number, - fn: Function): Function; + fn: T): T; /** * Wraps the first function inside of the wrapper function, passing it as the first argument. This allows From 5ee094dbae985fdcf91afb63a91cce59bdf7558a Mon Sep 17 00:00:00 2001 From: dinesh Date: Mon, 18 Aug 2014 12:02:47 +0800 Subject: [PATCH 243/277] Corrected the auto spacing created by WebStorm IDE --- underscore/underscore.d.ts | 76 +++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index e17c6b662..2d7361dda 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1033,59 +1033,59 @@ interface UnderscoreStatic { ...arguments: any[]): void; /** - * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, - * will only actually call the original function at most once per every wait milliseconds. Useful for - * rate-limiting events that occur faster than you can keep up with. - * By default, throttle will execute the function as soon as you call it for the first time, and, - * if you call it again any number of times during the wait period, as soon as that period is over. - * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable - * the execution on the trailing-edge, pass {trailing: false}. - * @param func Function to throttle `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. - * @return `fn` with a throttle of `wait`. - **/ + * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, + * will only actually call the original function at most once per every wait milliseconds. Useful for + * rate-limiting events that occur faster than you can keep up with. + * By default, throttle will execute the function as soon as you call it for the first time, and, + * if you call it again any number of times during the wait period, as soon as that period is over. + * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable + * the execution on the trailing-edge, pass {trailing: false}. + * @param func Function to throttle `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. + * @return `fn` with a throttle of `wait`. + **/ throttle( func: T, wait: number, options?: _.ThrottleSettings): T; /** - * Creates and returns a new debounced version of the passed function that will postpone its execution - * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing - * behavior that should only happen after the input has stopped arriving. For example: rendering a preview - * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. - * - * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead - * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double - *-clicks on a "submit" button from firing a second time. - * @param fn Function to debounce `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. - * @return Debounced version of `fn` that waits `wait` ms when invoked. - **/ + * Creates and returns a new debounced version of the passed function that will postpone its execution + * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing + * behavior that should only happen after the input has stopped arriving. For example: rendering a preview + * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. + * + * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead + * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double + *-clicks on a "submit" button from firing a second time. + * @param fn Function to debounce `waitMS` ms. + * @param wait The number of milliseconds to wait before `fn` can be invoked again. + * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. + * @return Debounced version of `fn` that waits `wait` ms when invoked. + **/ debounce( fn: T, wait: number, immediate?: boolean): T; /** - * Creates a version of the function that can only be called one time. Repeated calls to the modified - * function will have no effect, returning the value from the original call. Useful for initialization - * functions, instead of having to set a boolean flag and then check it later. - * @param fn Function to only execute once. - * @return Copy of `fn` that can only be invoked once. - **/ + * Creates a version of the function that can only be called one time. Repeated calls to the modified + * function will have no effect, returning the value from the original call. Useful for initialization + * functions, instead of having to set a boolean flag and then check it later. + * @param fn Function to only execute once. + * @return Copy of `fn` that can only be invoked once. + **/ once(fn: T): T; /** - * Creates a version of the function that will only be run after first being called count times. Useful - * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, - * before proceeding. - * @param count Number of times to be called before actually executing. - * @fn The function to defer execution `count` times. - * @return Copy of `fn` that will not execute until it is invoked `count` times. - **/ + * Creates a version of the function that will only be run after first being called count times. Useful + * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, + * before proceeding. + * @param count Number of times to be called before actually executing. + * @fn The function to defer execution `count` times. + * @return Copy of `fn` that will not execute until it is invoked `count` times. + **/ after( count: number, fn: T): T; From 3f2d6b33b1ad83a4dc44bb0734fe38a30958144e Mon Sep 17 00:00:00 2001 From: froginvasion Date: Mon, 18 Aug 2014 10:51:24 +0200 Subject: [PATCH 244/277] Removed two missing properties from kineticjs Both `Polygon` and `Transition` dont seem to be present anymore in the current version of KineticJS. I'm not an expert of KineticJS, which means I could be wrong of course. --- kineticjs/kineticjs.d.ts | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index b5d56e846..1bdd79c61 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -300,15 +300,6 @@ declare module Kinetic { setData(SVG: string): any; } - var Polygon: { - new (config: PolygonConfig): IPolygon; - } - - interface IPolygon extends IShape { - getPoints(): any; - setPoints(points: any): any; - } - var RegularPolygon: { new (config: RegularPolygonConfig): IRegularPolygon; } @@ -405,14 +396,6 @@ declare module Kinetic { setTextStrokeWidth(textStrokeWidth: number): any; } - var Transition: { - new (node: Node, config: any): ITransition; - } - interface ITransition { - start(): any; - stop(): any; - } - var Animation: { new (...args: any[]): IAnimation; } @@ -485,10 +468,6 @@ declare module Kinetic { dash?: number[]; } - interface PolygonConfig extends DrawOptionsConfig, ObjectOptionsConfig { - points: any; - } - interface RegularPolygonConfig extends DrawOptionsConfig, ObjectOptionsConfig { sides: number; radius: number; From 094c4b575002b60d09c010259f71e19e949d3a9c Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Mon, 18 Aug 2014 15:33:03 +0200 Subject: [PATCH 245/277] Added definitions for source-map --- CONTRIBUTORS.md | 1 + source-map/source-map-tests.ts | 165 +++++++++++++++++++++++++++++++++ source-map/source-map.d.ts | 90 ++++++++++++++++++ 3 files changed, 256 insertions(+) create mode 100644 source-map/source-map-tests.ts create mode 100644 source-map/source-map.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index b8aecd835..cd95442e8 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -325,6 +325,7 @@ All definitions files include a header with the author and editors, so at some p * [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) * [sockjs-node](https://github.com/sockjs/sockjs-node) (by [Phil McCloghry-Laing](https://github.com/pmccloghrylaing)) * [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [source-map](https://github.com/mozilla/source-map) (by [Morten Houston Ludvigsen](https://github.com/MortenHoustonLudvigsen)) * [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [sqlite3](https://github.com/mapbox/node-sqlite3) (by [Nick Malaguti](https://github.com/nmalaguti)) * [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) diff --git a/source-map/source-map-tests.ts b/source-map/source-map-tests.ts new file mode 100644 index 000000000..f7ad78e85 --- /dev/null +++ b/source-map/source-map-tests.ts @@ -0,0 +1,165 @@ +import SourceMap = require('source-map'); + +function testSourceMapConsumer() { + function testConstructor() { + var scm: SourceMap.SourceMapConsumer; + + // create with full RawSourceMap + scm = new SourceMap.SourceMapConsumer({ + version: 'foo', + sources: ['foo', 'bar'], + names: ['foo', 'bar'], + sourcesContent: 'foo', + mappings: 'foo' + }); + + // create with partial RawSourceMap + scm = new SourceMap.SourceMapConsumer({ + version: 'foo', + sources: ['foo', 'bar'], + names: ['foo', 'bar'], + mappings: 'foo' + }); + } + + function testOriginalPositionFor(scm: SourceMap.SourceMapConsumer) { + var origPos: SourceMap.MappedPosition; + origPos = scm.originalPositionFor({ line: 42, column: 42 }); + } + + function testGeneratedPositionFor(scm: SourceMap.SourceMapConsumer) { + var genPos: SourceMap.Position; + genPos = scm.generatedPositionFor({ line: 42, column: 42, source: 'foo' }); + genPos = scm.generatedPositionFor({ line: 42, column: 42, source: 'foo', name: 'bar' }); + } + + function testSourceContentFor(scm: SourceMap.SourceMapConsumer) { + var content: string; + content = scm.sourceContentFor('foo'); + } + + function testEachMapping(scm: SourceMap.SourceMapConsumer) { + var x: SourceMap.MappingItem; + var context: {}; + + scm.eachMapping(mapping => { x = mapping; }); + scm.eachMapping(mapping => { x = mapping; }, context); + scm.eachMapping(mapping => { x = mapping; }, context, SourceMap.SourceMapConsumer.GENERATED_ORDER); + scm.eachMapping(mapping => { x = mapping; }, context, SourceMap.SourceMapConsumer.ORIGINAL_ORDER); + } +} + +function testSourceMapGenerator() { + function testConstructor() { + var generator: SourceMap.SourceMapGenerator; + + generator = new SourceMap.SourceMapGenerator(); + generator = new SourceMap.SourceMapGenerator({ + file: 'foo' + }); + generator = new SourceMap.SourceMapGenerator({ + sourceRoot: 'foo' + }); + generator = new SourceMap.SourceMapGenerator({ + file: 'foo', + sourceRoot: 'bar' + }); + } + + function testFromSourceMap(generator: SourceMap.SourceMapGenerator, scm: SourceMap.SourceMapConsumer) { + generator = SourceMap.SourceMapGenerator.fromSourceMap(scm); + } + + function testAddMapping(generator: SourceMap.SourceMapGenerator) { + generator.addMapping({ + generated: { line: 42, column: 42 }, + original: { line: 42, column: 42 }, + source: 'foo', + name: 'foo' + }); + + generator.addMapping({ + generated: { line: 42, column: 42 }, + original: { line: 42, column: 42 }, + source: 'foo' + }); + } + + function testSetSourceContent(generator: SourceMap.SourceMapGenerator) { + generator.setSourceContent('foo', 'bar'); + } + + function testApplySourceMap(generator: SourceMap.SourceMapGenerator, scm: SourceMap.SourceMapConsumer) { + generator.applySourceMap(scm); + generator.applySourceMap(scm, 'foo'); + generator.applySourceMap(scm, 'foo', 'bar'); + } + + function testToString(generator: SourceMap.SourceMapGenerator) { + var str: string; + str = generator.toString(); + } +} + +function testSourceNode() { + function testConstructor() { + var node: SourceMap.SourceNode; + + node = new SourceMap.SourceNode(); + node = new SourceMap.SourceNode(42, 42, 'foo'); + node = new SourceMap.SourceNode(42, 42, 'foo', 'bar'); + node = new SourceMap.SourceNode(42, 42, 'foo', 'bar', 'slam'); + } + + function testFromStringWithSourceMap(scm: SourceMap.SourceMapConsumer) { + var node: SourceMap.SourceNode; + + node = SourceMap.SourceNode.fromStringWithSourceMap('foo', scm); + node = SourceMap.SourceNode.fromStringWithSourceMap('foo', scm, 'bar'); + } + + function testAdd(node: SourceMap.SourceNode) { + node.add('foo'); + } + + function testPrepend(node: SourceMap.SourceNode) { + node.prepend('foo'); + } + + function testSetSourceContent(node: SourceMap.SourceNode) { + node.setSourceContent('foo', 'bar'); + } + + function testWalk(node: SourceMap.SourceNode) { + var chunk: string; + var mapping: SourceMap.MappedPosition; + + node.walk((c, m) => { chunk = c; mapping = m; }); + } + + function testWalkSourceContents(node: SourceMap.SourceNode) { + var file: string; + var content: string; + + node.walkSourceContents((f, c) => { file = f; content = c; }); + } + + function testJoin(node: SourceMap.SourceNode) { + node = node.join('foo'); + } + + function testReplaceRight(node: SourceMap.SourceNode) { + node = node.replaceRight('foo', 'bar'); + } + + function testToString(node: SourceMap.SourceNode) { + var str: string; + str = node.toString(); + } + + function testToStringWithSourceMap(node: SourceMap.SourceNode, sos: SourceMap.StartOfSourceMap) { + var result: SourceMap.CodeWithSourceMap; + result = node.toStringWithSourceMap(); + result = node.toStringWithSourceMap(sos); + } +} \ No newline at end of file diff --git a/source-map/source-map.d.ts b/source-map/source-map.d.ts new file mode 100644 index 000000000..a1d8e208b --- /dev/null +++ b/source-map/source-map.d.ts @@ -0,0 +1,90 @@ +// Type definitions for source-map v0.1.38 +// Project: https://github.com/mozilla/source-map +// Definitions by: Morten Houston Ludvigsen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module SourceMap { + interface StartOfSourceMap { + file?: string; + sourceRoot?: string; + } + + interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: Array; + names: Array; + sourcesContent?: string; + mappings: string; + } + + interface Position { + line: number; + column: number; + } + + interface MappedPosition extends Position { + source: string; + name?: string; + } + + interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; + } + + interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; + } + + interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; + } + + class SourceMapConsumer { + public static GENERATED_ORDER: number; + public static ORIGINAL_ORDER: number; + + constructor(rawSourceMap: RawSourceMap); + public originalPositionFor(generatedPosition: Position): MappedPosition; + public generatedPositionFor(originalPosition: MappedPosition): Position; + public sourceContentFor(source: string): string; + public eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; + } + + class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + public static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + public addMapping(mapping: Mapping): void; + public setSourceContent(sourceFile: string, sourceContent: string): void; + public applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + public toString(): string; + } + + class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + public static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + public add(chunk: string): void; + public prepend(chunk: string): void; + public setSourceContent(sourceFile: string, sourceContent: string): void; + public walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + public walkSourceContents(fn: (file: string, content: string) => void): void; + public join(sep: string): SourceNode; + public replaceRight(pattern: string, replacement: string): SourceNode; + public toString(): string; + public toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; + } +} + +declare module 'source-map' { + export = SourceMap; +} From f8002652941e2d05285bfbe550efaf07697c9162 Mon Sep 17 00:00:00 2001 From: Kevin Weeks Date: Mon, 18 Aug 2014 14:39:59 -0700 Subject: [PATCH 246/277] Reduced type severity of templateProvider in IState interface templateProvider can be an annotated function (any[]) like controllerProvider, so any is a more appropriate typing. --- angular-ui/angular-ui-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 0f8eb5c57..005bf8b90 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -11,7 +11,7 @@ declare module ng.ui { name?: string; template?: any; templateUrl?: any; - templateProvider?: () => string; + templateProvider?: any; controller?: any; controllerAs?: string; controllerProvider?: any; From e49b7e4223870e816fe3dc6edbb59d0a9d6505b3 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Tue, 19 Aug 2014 03:03:59 -0300 Subject: [PATCH 247/277] prepare for angular 1.3 --- angularjs/angular.d.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index cacf7647b..ca964d9fa 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -267,12 +267,16 @@ declare module ng { $dirty: boolean; $valid: boolean; $invalid: boolean; + $submitted: boolean; $error: any; $addControl(control: ng.INgModelController): void; $removeControl(control: ng.INgModelController): void; $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; $setDirty(): void; $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; } /////////////////////////////////////////////////////////////////////////// @@ -285,6 +289,13 @@ declare module ng { // Documentation states viewValue and modelValue to be a string but other // types do work and it's common to use them. $setViewValue(value: any): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(revalidate?: boolean): void; + $isEmpty(value: any): boolean; + $viewValue: any; $modelValue: any; @@ -293,12 +304,23 @@ declare module ng { $formatters: IModelFormatter[]; $viewChangeListeners: IModelViewChangeListener[]; $error: any; + $name: string; + + $touched: boolean; + $untouched: boolean; + + $validators: IModelValidators; + $pristine: boolean; $dirty: boolean; $valid: boolean; $invalid: boolean; } + interface IModelValidators { + [index: string]: (...args: any[]) => boolean; + } + interface IModelParser { (value: any): any; } @@ -312,7 +334,7 @@ declare module ng { } /////////////////////////////////////////////////////////////////////////// - // Scope and RootScope + // Scope and RootScope // see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// interface IRootScopeService { From 76463ce678b1751ad4e197823248ffdbd686f6bd Mon Sep 17 00:00:00 2001 From: ZauberNerd Date: Tue, 19 Aug 2014 10:50:30 +0200 Subject: [PATCH 248/277] Corrected type annotations and method signatures for ZyngaScroller --- scroller/scroller.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scroller/scroller.d.ts b/scroller/scroller.d.ts index 09cbbc291..b1312ff35 100644 --- a/scroller/scroller.d.ts +++ b/scroller/scroller.d.ts @@ -38,10 +38,10 @@ declare class Scroller { finishPullToRefresh(): void; getValues(): ScrollValuesWithZoom; getScrollMax(): ScrollValues; - zoomTo(level: number, animate?: boolean, originLeft?: boolean, originTop?: boolean): void; - zoomBy(factor: number, animate?: boolean, originLeft?: boolean, originTop?: boolean): void; - scrollTo(left?: number, top?: number, animate?: number, zoom?: number): void; - scrollBy(left?: number, top?: number, animate?: number): void; + zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + scrollTo(left?: number, top?: number, animate?: boolean, zoom?: number): void; + scrollBy(left?: number, top?: number, animate?: boolean): void; doMouseZoom(wheelDelta: number, timeStamp: number, pageX: number, pageY: number): void; doTouchStart(touches: any[], timeStamp: number): void; From a422e8fc073c5adee3ac7796d63d9d0815a4e394 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Tue, 19 Aug 2014 19:35:30 +0900 Subject: [PATCH 249/277] add csurf type file --- csurf/csurf.d.ts | 30 ++++++++++++++++++++++++++++++ passport/passport.d.ts | 29 ++++++++++++----------------- 2 files changed, 42 insertions(+), 17 deletions(-) create mode 100644 csurf/csurf.d.ts diff --git a/csurf/csurf.d.ts b/csurf/csurf.d.ts new file mode 100644 index 000000000..3a95435d7 --- /dev/null +++ b/csurf/csurf.d.ts @@ -0,0 +1,30 @@ +// Type definitions for csurf +// Project: http://expressjs.com +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + csrfToken(): string; + } +} + +declare module "csurf" { + import express = require('express'); + + function csurf(options?: { + value?: (req: express.Request) => string; + cookie?: csurf.CookieOptions; + }): express.RequestHandler; + + module csurf { + export interface CookieOptions extends express.CookieOptions { + key: string; + } + } + + export = csurf; +} + diff --git a/passport/passport.d.ts b/passport/passport.d.ts index fc3dd786f..6d03093eb 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -8,6 +8,18 @@ declare module Express { export interface Request { session?: any; + + // These declarations are merged into express's Request type + login(user: any, done: (err: any) => void): void; + login(user: any, options: Object, done: (err: any) => void): void; + logIn(user: any, done: (err: any) => void): void; + logIn(user: any, options: Object, done: (err: any) => void): void; + + logout(): void; + logOut(): void; + + isAuthenticated(): boolean; + isUnauthenticated(): boolean; } } @@ -68,20 +80,3 @@ declare module 'passport' { } } -declare module Express { - export interface Request { - - // These declarations are merged into express's Request type - login(user: any, done: (err: any) => void): void; - login(user: any, options: Object, done: (err: any) => void): void; - logIn(user: any, done: (err: any) => void): void; - logIn(user: any, options: Object, done: (err: any) => void): void; - - logout(): void; - logOut(): void; - - isAuthenticated(): boolean; - isUnauthenticated(): boolean; - } -} - From 688f734b69f454c90191f0f1caad0b05610ff446 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Tue, 19 Aug 2014 19:37:13 +0900 Subject: [PATCH 250/277] add semicolon --- 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 d9551e22b..9d5d3d33a 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -821,7 +821,7 @@ declare module "express" { (name: string): string; // Getter (name: string, ...handlers: RequestHandler[]): Application; (name: RegExp, ...handlers: RequestHandler[]): Application; - } + }; /** * Return the app's absolute pathname From 451f712613ab0effc1318a5d55e047764d1c53ac Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Wed, 20 Aug 2014 00:27:36 +0900 Subject: [PATCH 251/277] change Project URL --- csurf/csurf.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csurf/csurf.d.ts b/csurf/csurf.d.ts index 3a95435d7..cc78f9599 100644 --- a/csurf/csurf.d.ts +++ b/csurf/csurf.d.ts @@ -1,5 +1,5 @@ // Type definitions for csurf -// Project: http://expressjs.com +// Project: https://www.npmjs.org/package/csurf // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/borisyankov/DefinitelyTyped From 10ba3e4655afc34a46ec7fd648b505def74ba982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Bru=CC=88ckner?= Date: Tue, 19 Aug 2014 16:41:08 -0400 Subject: [PATCH 252/277] Added Chroma.js definitions --- CONTRIBUTORS.md | 1 + chroma-js/chroma-js-tests.ts | 120 +++++++++++++ chroma-js/chroma-js.d.ts | 317 +++++++++++++++++++++++++++++++++++ 3 files changed, 438 insertions(+) create mode 100644 chroma-js/chroma-js-tests.ts create mode 100644 chroma-js/chroma-js.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index b8aecd835..d7a87dd49 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -46,6 +46,7 @@ All definitions files include a header with the author and editors, so at some p * [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)) +* [Chroma.js](https://github.com/gka/chroma.js) (by [Sebastian Brückner](https://github.com/invliD)) * [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber) and [otiai10](https://github.com/otiai10)) * [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay)) * [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik)) diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts new file mode 100644 index 000000000..3240ac11f --- /dev/null +++ b/chroma-js/chroma-js-tests.ts @@ -0,0 +1,120 @@ +/// + +function test_chroma() { + chroma("red"); + chroma("#ff0000"); + chroma("#f00"); + chroma("FF0000"); + chroma(255, 0, 0); + chroma([255, 0, 0]); + chroma(0, 1, 0.5, 'hsl'); + chroma([0, 1, 0.5], 'hsl'); + chroma(0, 1, 1, 'hsv'); + chroma("rgb(255,0,0)"); + chroma("rgb(100%,0%,0%)"); + chroma("hsl(0,100%,50%)"); + chroma(53.24, 80.09, 67.20, 'lab'); + chroma(53.24, 104.55, 40, 'lch'); + chroma(1, 0, 0, 'gl'); + + chroma.hex("#ff0000"); + chroma.hex("red"); + chroma.hex("rgb(255, 0, 0)"); + + chroma.rgb(255, 0, 0); + chroma.hsl(0, 1, 0.5); + chroma.hsv(120, 0.5, 0.5); + chroma.lab(53.24, 80.09, 67.20); + chroma.lch(53.24, 104.55, 40); + chroma.gl(1, 0, 0); + + chroma.interpolate('white', 'black', 0) // #ffffff + chroma.interpolate('white', 'black', 1) // #000000 + chroma.interpolate('white', 'black', 0.5) // #7f7f7f + chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 + chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 + + chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" + + var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); + bezInterpolator(0).hex() // #ffffff + bezInterpolator(0.33).hex() // #ffcc67 + bezInterpolator(0.66).hex() // #b65f1a + bezInterpolator(1).hex() // #000000 + + chroma.luminance('black') // 0 + chroma.luminance('white') // 1 + chroma.luminance('#ff0000') // 0.2126 + + chroma.contrast('white', 'navy') // 16.00 – ok + chroma.contrast('white', 'yellow') // 1.07 – not ok! +} + +function test_color() { + chroma('red').hex() // "#FF0000"" + chroma('red').rgb() // [255, 0, 0] + chroma('red').hsv() // [0, 1, 1] + chroma('red').hsl() // [0, 1, 0.5] + chroma('red').lab() // [53.2407, 80.0924, 67.2031] + chroma('red').lch() // [53.2407, 104.5517, 39.9990] + chroma('red').rgba() // [255, 0, 0, 1] + chroma('red').css() // "rgb(255,0,0)" + chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" + chroma('red').css('hsl') // "hsl(0,100%,50%)" + chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" + chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" + + var red = chroma('red'); + red.alpha(0.5); + red.css(); // rgba(255,0,0,0.5); + + chroma('red').darken().hex() // #BC0000 + chroma('red').brighten().hex() // #FF603B + chroma('#eecc99').saturate().hex() // #fcc973 + chroma('red').desaturate().hex() // #ec3d23 + + chroma('black').luminance() // 0 + chroma('white').luminance() // 1 + chroma('red').luminance() // 0.2126 +} + +function test_scale() { + var scale = chroma.scale(['lightyellow', 'navy']); + scale(0.5); // #7F7FB0 + + chroma.scale('RdYlBu'); + + var col = scale(0.5); + col.hex(); // #7F7FB0 + col.rgb(); // [127.5, 127.5, 176] + + scale = chroma.scale(['lightyellow', 'navy']).out('hex'); + scale(0.5); // "#7F7FB0" + + var scale = chroma.scale(['lightyellow', 'navy']); + scale.mode('hsv')(0.5); // #54C08A + scale.mode('hsl')(0.5); // #31FF98 + scale.mode('lab')(0.5); // #967CB2 + scale.mode('lch')(0.5); // #D26662 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); + scale(200); // #7F7FB0 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); + scale(98); // #7F7FB0 + scale(99); // #7F7FB0 + scale(100); // #AAAAC0 + scale(101); // #AAAAC0 + + chroma.scale(['#eee', '#900']).domain([0, 400], 7); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); + chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] + + chroma.scale().range(['lightyellow', 'navy']); + + chroma.scale(['lightyellow', 'navy']).correctLightness(true); + + chroma.scale('RdYlGn').domain([0,1], 5).colors() +} diff --git a/chroma-js/chroma-js.d.ts b/chroma-js/chroma-js.d.ts new file mode 100644 index 000000000..94b32ae81 --- /dev/null +++ b/chroma-js/chroma-js.d.ts @@ -0,0 +1,317 @@ +// Type definitions for Chroma.js v0.5.6 +// Project: https://github.com/gka/chroma.js +// Definitions by: Sebastian Brückner +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * Chroma.js is a tiny library for all kinds of color conversions and color scales. + */ +declare module Chroma { + + export interface ChromaStatic { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + * @return the color object. + */ + (color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (values: number[], colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + color(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: string): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: string): number; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(color: string): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.css(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + hex(color: string): Color; + + rgb(red: number, green: number, blue: number, alpha?: number): Color; + hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; + hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; + lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + gl(red: number, green: number, blue: number, alpha?: number): Color; + + interpolate: InterpolateFunction; + mix: InterpolateFunction; + + luminance(color: Color): number; + luminance(color: string): number; + + /** + * Creates a color scale using a pre-defined color scale. + * + * @param name The name of the color scale. + * @return the resulting color scale. + */ + scale(name: string): Scale; + + /** + * Creates a color scale function from the given set of colors. + * + * @param colors An Array of at least two color names or hex values. + * @return the resulting color scale. + */ + scale(colors?: string[]): Scale; + + scales: PredefinedScales; + } + + interface InterpolateFunction { + (color1: Color, color2: Color, f: number, mode?: string): Color; + (color1: Color, color2: string, f: number, mode?: string): Color; + (color1: string, color2: Color, f: number, mode?: string): Color; + (color1: string, color2: string, f: number, mode?: string): Color; + + bezier(colors: any[]): (t: number) => Color; + } + + interface PredefinedScales { + [key: string]: Scale; + + cool: Scale; + hot: Scale; + } + + export interface Color { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + */ + new(color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. + * + * @param a + * @param b + * @param c + * @param alpha The alpha value of the color. + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(values: number[], colorSpace: string): Color; + + /** + * Convert this color to CSS hex representation. + * + * @return this color's hex representation. + */ + hex(): string; + + /** + * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). + */ + luminance(): number; + + /** + * @return the X11 name of this color or its hex value if it does not have a name. + */ + name(): string; + + /** + * @return the alpha value of the color. + */ + alpha(): number; + + /** + * Set the alpha value. + * + * @param alpha The alpha value. + * @return this + */ + alpha(alpha: number): Color; + + css(mode?: string): string; + + interpolate(color: Color, f: number, mode?: string): Color; + interpolate(color: string, f: number, mode?: string): Color; + + premultiply(): Color; + + rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; + lab(): number[]; + lch(): number[]; + hsi(): number[]; + gl(): number[]; + + darken(amount?: number): Color; + darker(amount: number): Color; + brighten(amount?: number): Color; + brighter(amount: number): Color; + saturate(amount?: number): Color; + desaturate(amount?: number): Color; + + toString(): string; + } + + export interface Scale { + /** + * Interpolate a color using the currently set range and domain. + * + * @param value The value to use for interpolation. + * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). + */ + (value: number): any; + + /** + * Retreive all possible colors generated by this scale if it has distinct classes. + * + * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". + * @return an array of colors in the type specified by mode. + */ + colors(mode?: string): any[]; + + correctLightness(): boolean; + + /** + * Enable or disable automatic lightness correction of this scale. + * + * @param Whether to enable or disable automatic lightness correction. + * @return this + */ + correctLightness(enable: boolean): Scale; + + /** + * Get the current domain. + * + * @return The current domain. + */ + domain(): number[]; + + /** + * Set the domain. + * + * @param domain An Array of at least two numbers (min and max). + * @param classes The number of fixed classes to create between min and max. + * @param mode The scale to use. Examples: log, quantiles, k-means. + * @return this + */ + domain(domain: number[], classes?: number, mode?: string): Scale; + + /** + * Specify in which color space the colors should be interpolated. Defaults to "rgb". + * You can use any of the following spaces: rgb, hsv, hsl, lab, lch + * + * @param colorSpace The color space to use for interpolation. + * @return this + */ + mode(colorSpace: string): Scale; + + /** + * Set the output mode of this Scale. + * + * @param mode The output mode to use. Must be one of Color's getters. + * @return this + */ + out(mode: string): Scale; + + /** + * Set the color range after initialization. + * + * @param colors An Array of at least two color names or hex values. + * @return this + */ + range(colors: string[]): Scale; + } + +} + +declare var chroma: Chroma.ChromaStatic; From 376e27131e3ec6a2336bbd2fe3dae2809a213458 Mon Sep 17 00:00:00 2001 From: Brett Morgan Date: Wed, 20 Aug 2014 10:22:05 +1000 Subject: [PATCH 253/277] Adding promises to GAPI --- gapi/gapi.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/gapi/gapi.d.ts b/gapi/gapi.d.ts index 8a9206663..d9d6fb90b 100644 --- a/gapi/gapi.d.ts +++ b/gapi/gapi.d.ts @@ -141,6 +141,23 @@ declare module gapi.client { statusText: string; } ) => any):void; + /** + * HttpRequest supports promises. + */ + then(success:(response:{ + result:T; + body:string; + headers?: any[]; + status?: number; + statusText?: string + })=>void, + failure:(response:{ + result:T; + body:string; + headers?: any[]; + status?: number; + statusText?: string + })=>void): void; } /** * Represents an HTTP Batch operation. Individual HTTP requests are added with the add method and the batch is executed using execute. From db5232d423b22a42df275c1c499674f180d876f9 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Tue, 19 Aug 2014 22:08:36 -0300 Subject: [PATCH 254/277] squash! prepare for angular 1.3 add legacy for version 1.2 and move test files --- angularjs/angular.d.ts | 2 +- angularjs/legacy/angular-1.2-tests.ts | 571 ++++++++++++ angularjs/legacy/angular-1.2.d.ts | 1182 +++++++++++++++++++++++++ 3 files changed, 1754 insertions(+), 1 deletion(-) create mode 100644 angularjs/legacy/angular-1.2-tests.ts create mode 100644 angularjs/legacy/angular-1.2.d.ts diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index ca964d9fa..34e2fe8bf 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS 1.2+ +// Type definitions for Angular JS 1.3+ // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/angularjs/legacy/angular-1.2-tests.ts b/angularjs/legacy/angular-1.2-tests.ts new file mode 100644 index 000000000..d0f60609a --- /dev/null +++ b/angularjs/legacy/angular-1.2-tests.ts @@ -0,0 +1,571 @@ +/// + +// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369 +// https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2012 Witold Szczerba + * License: MIT + */ + +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. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } + + $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'); + $http(config).then(function (response) { + deferred.resolve(response); + }); + } + function retryAll() { + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); + } + this.buffer = []; + } + + return { + loginConfirmed: function () { + $rootScope.$broadcast('event:auth-loginConfirmed'); + retryAll(); + } + } + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) + +/** + * $http interceptor. + * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. + */ + .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider: any) { + + var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + function success(response: ng.IHttpPromiseCallbackArg) { + return response; + } + + function error(response: ng.IHttpPromiseCallbackArg) { + if (response.status === 401) { + var deferred = $q.defer(); + authServiceProvider.pushToBuffer(response.config, deferred); + $rootScope.$broadcast('event:auth-loginRequired'); + return deferred.promise; + } + // otherwise + return $q.reject(response); + } + + return function (promise: ng.IHttpPromise) { + return promise.then(success, error); + } + + }]; + $httpProvider.responseInterceptors.push(interceptor); + }]); + + +module HttpAndRegularPromiseTests { + interface Person { + firstName: string; + lastName: string; + } + + interface ExpectedResponse extends Person { } + + interface SomeControllerScope extends ng.IScope { + person: Person; + theAnswer: number; + letters: string[]; + snack: string; + nothing?: string; + } + + var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { + $http.get("http://somewhere/some/resource") + .success((data: ExpectedResponse) => { + $scope.person = data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would type check + $scope.person = response.data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would NOT type check + $scope.person = response.data; + }); + + var aPromise: ng.IPromise = $q.when({ firstName: "Jack", lastName: "Sparrow" }); + aPromise.then((person: Person) => { + $scope.person = person; + }); + + var bPromise: ng.IPromise = $q.when(42); + bPromise.then((answer: number) => { + $scope.theAnswer = answer; + }); + + var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + cPromise.then((letters: string[]) => { + $scope.letters = letters; + }); + + // When $q.when is passed an IPromise, it returns an IPromise + var dPromise: ng.IPromise = $q.when($q.when("ALBATROSS!")); + 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 + var anotherController: Function = ($scope: SomeControllerScope, $http: + ng.IHttpService, $q: ng.IQService) => { + + var buildFooData: Function = () => 42; + + var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { + $http.get('/foo', buildFooData()) + .success(callback); + } + + doFoo((data: any) => console.log(data)); + } +} + +// Test for AngularJS Syntax + +module My.Namespace { + export var x: any; // need to export something for module to kick in +} + +// IModule Registering Test +var mod = angular.module('tests', []); +mod.controller('name', function ($scope: ng.IScope) { }) +mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.controller(My.Namespace); +mod.directive('name', function ($scope: ng.IScope) { }) +mod.directive('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.directive(My.Namespace); +mod.factory('name', function ($scope: ng.IScope) { }) +mod.factory('name', ['$scope', function ($scope: ng.IScope) { }]) +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) { 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) { }) +mod.service('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.service(My.Namespace); +mod.constant('name', 23); +mod.constant('name', "23"); +mod.constant(My.Namespace); +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; +foo.then((x) => { + // x is inferred to be a number + return "asdf"; +}).then((x) => { + // x is inferred to be string + x.length; + return 123; +}).then((x) => { + // x is infered to be a number + x.toFixed(); + return; +}).then((x) => { + // x is infered to be void + // Typescript will prevent you to actually use x as a local variable + // Try object: + return { a: 123 }; +}).then((x) => { + // Object is inferred here + x.a = 123; + //Try a promise + var y: ng.IPromise; + return y; +}).then((x) => { + // x is infered to be a number, which is the resolved value of a promise + x.toFixed(); +}); + + +var httpFoo: ng.IHttpPromise; +httpFoo.then((x) => { + // When returning a promise the generic type must be inferred. + var innerPromise : ng.IPromise; + return innerPromise; +}).then((x) => { + // must still be number. + x.toFixed(); +}); + + +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log: string[] = []; + 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(); +var isolateScope: ng.IScope = element.isolateScope(); + + + +function test_IAttributes(attributes: ng.IAttributes){ + return attributes; +} + +test_IAttributes({ + $addClass: function (classVal){}, + $removeClass: function(classVal){}, + $set: function(key, value){}, + $observe: function(name, fn){ + return fn; + }, + $attr: {} +}); + +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + post: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective(); + } + + link(scope: ng.IScope) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + pre: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective2(); + } + + link(scope: ng.IScope) { + + } +} + +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}}' + }; + }); + +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) { + + return { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { + 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: ng.IScope, element: ng.IAugmentedJQuery) { + 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: ng.IScope) { + 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: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/legacy/angular-1.2.d.ts b/angularjs/legacy/angular-1.2.d.ts new file mode 100644 index 000000000..a1a4cb15b --- /dev/null +++ b/angularjs/legacy/angular-1.2.d.ts @@ -0,0 +1,1182 @@ +// Type definitions for Angular JS 1.2+ +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: ng.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng { + + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + + // All service providers extend this interface + interface IServiceProvider { + $get: any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; + bootstrap(element: Document, modules?: any[]): auto.IInjectorService; + copy(source: any, destination?: any): any; + 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; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + + /** + * 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. + */ + module( + name: string, + requires?: string[], + configFn?: Function): IModule; + + noop(...args: any[]): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + animation(name: string, animationFactory: Function): IModule; + animation(name: string, inlineAnnotatedFunction: any[]): IModule; + 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. + */ + constant(name: string, value: any): IModule; + 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). + */ + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; + controller(object : Object): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + directive(name: string, inlineAnnotatedFunction: any[]): IModule; + 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}). + */ + factory(name: string, inlineAnnotatedFunction: any[]): IModule; + factory(object: Object): IModule; + 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; + provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(inlineAnnotatedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotatedConstructor: any[]): IModule; + service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ + value(name: string, value: any): IModule; + value(object: Object): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + // this is necessary to be able to access the scoped attributes. it's not very elegant + // because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + // this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + [name: string]: any; + + // Adds the CSS class value specified by the classVal parameter to the + // element. If animations are enabled then an animation will be triggered + // for the class addition. + $addClass(classVal: string): void; + + // Removes the CSS class value specified by the classVal parameter from the + // element. If animations are enabled then an animation will be triggered for + // the class removal. + $removeClass(classVal: string): void; + + // Set DOM element attribute value. + $set(key: string, value: any): void; + + // Observes an interpolated attribute. + // The observer function will be invoked once during the next $digest + // following compilation. The observer is then invoked whenever the + // interpolated value changes. + $observe(name: string, fn:(value?:any)=>any): Function; + + // A map of DOM element attribute names to the normalized name. This is needed + // to do reverse lookup from normalized name back to actual name. + $attr: Object; + } + + /** + * 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; + $invalid: boolean; + $error: any; + $addControl(control: ng.INgModelController): void; + $removeControl(control: ng.INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; + $setDirty(): void; + $setPristine(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + // Documentation states viewValue and modelValue to be a string but other + // types do work and it's common to use them. + $setViewValue(value: any): void; + $viewValue: any; + + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; + $error: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /////////////////////////////////////////////////////////////////////////// + // 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; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): IAngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string, args?: Object): any; + $eval(expression: (scope: IScope) => any, args?: Object): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean): IScope; + + $on(name: string, listener: (event: IAngularEvent, ...args: 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; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + + $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: {(scope: IScope) : any}[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $parent: IScope; + + $root: IRootScopeService; + this: IRootScopeService; + + $id: string; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { + [index: string]: any; + } + + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; + name: string; + preventDefault: Function; + defaultPrevented: boolean; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + interface IFilterService { + (name: string): Function; + } + + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + interface ILogProvider { + debugEnabled(enabled: boolean): ILogProvider; + debugEnabled(): boolean; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + // see http://docs.angularjs.org/api/ng.$parseProvider + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface IParseProvider { + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; + + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + path(): string; + path(newPath: string): ILocationService; + port(): number; + protocol(): string; + replace(): ILocationService; + search(): any; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends IAugmentedJQuery {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ + 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 }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + 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; + } + + interface IPromise { + then(successCallback: (promiseValue: T) => IHttpPromise, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult, notifyCallback?: (state: any) => any): IPromise; + + + catch(onRejected: (reason: any) => IHttpPromise): IPromise; + catch(onRejected: (reason: any) => IPromise): IPromise; + catch(onRejected: (reason: any) => TResult): IPromise; + + finally(finallyCallback: ()=>any):IPromise; + } + + interface IDeferred { + resolve(value?: T): void; + reject(reason?: any): void; + notify(state?:any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + interface ICacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + + // Methods bellow are not documented + info(): any; + get (cacheId: string): ICacheObject; + } + + interface ICacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get (key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + } + + interface ICloneAttachFunction { + // Let's hint but not force cloneAttachFn's signature + (clonedElement?: JQuery, scope?: IScope): any; + } + + // This corresponds to the "publicLinkFn" returned by $compile. + interface ITemplateLinkingFunction { + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + // This corresponds to $transclude (and also the transclude function passed to link). + interface ITranscludeFunction { + // If the scope is provided, then the cloneAttachFn must be as well. + (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; + // If one argument is provided, then it's assumed to be the cloneAttachFn. + (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + } + + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$http + */ + interface IHttpService { + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * 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 + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * 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 + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ + defaults: IRequestConfig; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: any[]; + } + + /** + * Object describing the request to be made and how it should be processed. + * 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. + */ + params?: any; + + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. + */ + headers?: any; + + /** + * Name of HTTP header to populate with the XSRF token. + */ + xsrfHeaderName?: string; + + /** + * Name of cookie containing the XSRF token. + */ + xsrfCookieName?: string; + + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ + cache?: any; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ + withCredentials?: boolean; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. + */ + transformRequest?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. + */ + transformResponse?: any; + + /** + * {number|Promise} + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: any; + + /** + * See requestType. + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: (headerName: string) => string; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise { + success(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; + interceptors: any[]; + responseInterceptors: any[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // SCEService + // see http://docs.angularjs.org/api/ng.$sce + /////////////////////////////////////////////////////////////////////////// + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; + } + + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + link?: IDirectiveLinkFn; + name?: string; + priority?: number; + replace?: boolean; + require?: any; + restrict?: string; + scope?: any; + template?: any; + templateUrl?: any; + terminal?: boolean; + transclude?: any; + } + + /////////////////////////////////////////////////////////////////////////// + // angular.element + // when calling angular.element, angular returns a jQuery object, + // augmented with additional methods like e.g. scope. + // see: http://docs.angularjs.org/api/angular.element + /////////////////////////////////////////////////////////////////////////// + interface IAugmentedJQueryStatic extends JQueryStatic { + (selector: string, context?: any): IAugmentedJQuery; + (element: Element): IAugmentedJQuery; + (object: {}): IAugmentedJQuery; + (elementArray: Element[]): IAugmentedJQuery; + (object: JQuery): IAugmentedJQuery; + (func: Function): IAugmentedJQuery; + (array: any[]): IAugmentedJQuery; + (): IAugmentedJQuery; + } + + interface IAugmentedJQuery extends JQuery { + // TODO: events, how to define? + //$destroy + + find(selector: string): IAugmentedJQuery; + find(element: any): IAugmentedJQuery; + find(obj: JQuery): IAugmentedJQuery; + + controller(name: string): any; + injector(): any; + scope(): IScope; + isolateScope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + } + + /////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ng.$animate + /////////////////////////////////////////////////////////////////////// + interface IAnimateService { + addClass(element: JQuery, className: string, done?: Function): void; + enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + leave(element: JQuery, done?: Function): void; + move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + removeClass(element: JQuery, className: string, done?: Function): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string): any; + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // 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. + */ + constant(name: string, value: any): 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 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; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; + } + + } +} From 0e86e57b2374deb2f910ff3836db2fc4b83ad105 Mon Sep 17 00:00:00 2001 From: WojciechKrysiak Date: Wed, 20 Aug 2014 09:52:46 +0200 Subject: [PATCH 255/277] Update knockout.d.ts According to the documents $index is an observable. --- knockout/knockout.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 8b26c50b9..b8db00e3c 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -118,7 +118,7 @@ interface KnockoutBindingContext { $parents: any[]; $root: any; $data: any; - $index?: number; + $index?: KnockoutObservable; $parentContext?: KnockoutBindingContext; extend(properties: any): any; From fd019eed8b83a77dd7daf0c1a08db18cbabde0dd Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Wed, 20 Aug 2014 13:17:24 +0200 Subject: [PATCH 256/277] Add typings for version 1.5.1 --- .../timezonecomplete-1.4.6-tests.ts | 183 +++ timezonecomplete/timezonecomplete-1.4.6.d.ts | 1004 +++++++++++++++++ timezonecomplete/timezonecomplete-tests.ts | 12 + timezonecomplete/timezonecomplete.d.ts | 141 ++- 4 files changed, 1331 insertions(+), 9 deletions(-) create mode 100644 timezonecomplete/timezonecomplete-1.4.6-tests.ts create mode 100644 timezonecomplete/timezonecomplete-1.4.6.d.ts diff --git a/timezonecomplete/timezonecomplete-1.4.6-tests.ts b/timezonecomplete/timezonecomplete-1.4.6-tests.ts new file mode 100644 index 000000000..de0b73048 --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.4.6-tests.ts @@ -0,0 +1,183 @@ +/// + +import tc = require("timezonecomplete-1.4.6"); + +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); +n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-1.4.6.d.ts b/timezonecomplete/timezonecomplete-1.4.6.d.ts new file mode 100644 index 000000000..bd70278d5 --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.4.6.d.ts @@ -0,0 +1,1004 @@ +// Type definitions for timezonecomplete 1.4.6 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle v0.2.0 + +declare module 'timezonecomplete-1.4.6' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import dayOfYear = basics.dayOfYear; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + export import DateFunctions = javascript.DateFunctions; + import period = require("__timezonecomplete/period"); + export import Period = period.Period; + export import PeriodDst = period.PeriodDst; + export import periodDstToString = period.periodDstToString; + import timesource = require("__timezonecomplete/timesource"); + export import TimeSource = timesource.TimeSource; + export import RealTimeSource = timesource.RealTimeSource; + import timezone = require("__timezonecomplete/timezone"); + export import NormalizeOption = timezone.NormalizeOption; + export import TimeZoneKind = timezone.TimeZoneKind; + export import TimeZone = timezone.TimeZone; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * The days in a given year + */ + export function daysInYear(year: number): number; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns the day of the year of the given date [0..365]. January first is 0. + * + * @param year The year e.g. 1986 + * @param month Month 1-12 + * @param day Day of month 1-31 + */ + export function dayOfYear(year: number, month: number, day: number): number; + /** + * Returns the last instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the last occurrence of the week day in the month + */ + export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is >= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is <= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Convert a unix milli timestamp into a TimeT structure. + * This does NOT take leap seconds into account. + */ + export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; + /** + * Convert a year, month, day etc into a unix milli timestamp. + * This does NOT take leap seconds into account. + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; + /** + * Convert a TimeT structure into a unix milli timestamp. + * This does NOT take leap seconds into account. + */ + export function timeToUnixNoLeapSecs(tm: TimeStruct): number; + /** + * Return the day-of-week. + * This does NOT take leap seconds into account. + */ + export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * Basic representation of a date and time + */ + export class TimeStruct { + /** + * Year, 1970-... + */ + year: number; + /** + * Month 1-12 + */ + month: number; + /** + * Day of month, 1-31 + */ + day: number; + /** + * Hour 0-23 + */ + hour: number; + /** + * Minute 0-59 + */ + minute: number; + /** + * Seconds, 0-59 + */ + second: number; + /** + * Milliseconds 0-999 + */ + milli: number; + /** + * Create a TimeStruct from a number of unix milliseconds + */ + static fromUnix(unixMillis: number): TimeStruct; + /** + * Create a TimeStruct from a JavaScript date + * + * @param d The date + * @param df Which functions to take (getX() or getUTCX()) + */ + static fromDate(d: Date, df: javascript.DateFunctions): TimeStruct; + /** + * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone + */ + static fromString(s: string): TimeStruct; + /** + * Constructor + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + constructor(/** + * Year, 1970-... + */ + year?: number, /** + * Month 1-12 + */ + month?: number, /** + * Day of month, 1-31 + */ + day?: number, /** + * Hour 0-23 + */ + hour?: number, /** + * Minute 0-59 + */ + minute?: number, /** + * Seconds, 0-59 + */ + second?: number, /** + * Milliseconds 0-999 + */ + milli?: number); + /** + * Validate a TimeStruct, returns false if invalid. + */ + validate(): boolean; + /** + * The day-of-year 0-365 + */ + yearDay(): number; + /** + * Returns this time as a unix millisecond timestamp + * Does NOT take leap seconds into account. + */ + toUnixNoLeapSecs(): number; + /** + * Deep equals + */ + equals(other: TimeStruct): boolean; + /** + * < operator + */ + lessThan(other: TimeStruct): boolean; + clone(): TimeStruct; + valueOf(): number; + /** + * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn + */ + toString(): string; + inspect(): string; + } +} + +declare module '__timezonecomplete/datetime' { + import basics = require("__timezonecomplete/basics"); + import duration = require("__timezonecomplete/duration"); + import javascript = require("__timezonecomplete/javascript"); + import timesource = require("__timezonecomplete/timesource"); + import timezone = require("__timezonecomplete/timezone"); + /** + * DateTime class which is time zone-aware + * and which can be mocked for testing purposes. + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: timesource.TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: timezone.TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * Non-existing local times are normalized by rounding up to the next DST offset. + * + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: timezone.TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * Non-existing local times are normalized by rounding up to the next DST offset. + * Note that the Date class has bugs and inconsistencies when constructing them with times around + * DST changes. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: javascript.DateFunctions, timeZone?: timezone.TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: timezone.TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: timezone.TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): timezone.TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): basics.WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): basics.WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: timezone.TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * Converting an unaware date to an aware date throws an exception. Use the constructor + * if you really need to do that. + * + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: timezone.TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + * This is because Date calculates getUTCX() from getX() applying local time zone. + */ + toDate(): Date; + /** + * Add a time duration relative to UTC. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * There is not DST handling. + * @return this + duration + */ + add(duration: duration.Duration): DateTime; + /** + * Add an amount of time relative to UTC, as regularly as possible. + * + * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month + * increments the utcMonth() field. + * Adding an amount of units leaves lower units intact. E.g. + * adding a month will leave the day() field untouched if possible. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + * + * In case of DST changes, the utc time fields are still untouched but local + * time fields may shift. + */ + add(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the time fields may additionally + * increase by the DST offset, if a non-existing local time would + * be reached otherwise. + * + * Adding a unit of time will leave lower-unit fields intact, unless the result + * would be a non-existing time. Then an extra DST offset is added. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + */ + addLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: duration.Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): duration.Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/javascript' { + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear(), getUtcMonth() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import datetime = require("__timezonecomplete/datetime"); + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: datetime.DateTime, amount: number, unit: basics.TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): datetime.DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): basics.TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: datetime.DateTime): datetime.DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: datetime.DateTime, count?: number): datetime.DateTime; + /** + * Returns an ISO duration string e.g. + * 2014-01-01T12:00:00.000+01:00/P1H + * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) + * 2014-01-01T12:00:00.000+01:00/P1M (one month) + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/timesource' { + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } +} + +declare module '__timezonecomplete/timezone' { + import javascript = require("__timezonecomplete/javascript"); + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Option for TimeZone#normalizeLocal() + */ + export enum NormalizeOption { + /** + * Normalize non-existing times by ADDING the DST offset + */ + Up = 0, + /** + * Normalize non-existing times by SUBTRACTING the DST offset + */ + Down = 1, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + */ + constructor(name: string); + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Does this zone have Daylight Saving Time at all? + */ + hasDst(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Normalizes non-existing local times by adding a forward offset change. + * During a forward standard offset change or DST offset change, some amount of + * local time is skipped. Therefore, this amount of local time does not exist. + * This function adds the amount of forward change to any non-existing time. After all, + * this is probably what the user meant. + * + * @param localUnixMillis Unix timestamp in zone time + * @param opt (optional) Round up or down? Default: up + * + * @returns Unix timestamp in zone time, normalized. + */ + normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } +} + diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index 9f3833f71..86c3a9986 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -11,9 +11,12 @@ b = tc.isLeapYear(2014); n = tc.daysInMonth(2014, 10); n = tc.daysInYear(2014); n = tc.dayOfYear(2014, 1, 2); +w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); +n = tc.secondOfDay(13, 59, 59); +n = tc.weekOfMonth(2014, 1, 1); // DURATION @@ -97,6 +100,10 @@ n = dt.day(); n = dt.hour(); n = dt.minute(); n = dt.second(); +n = dt.weekNumber(); +n = dt.weekOfMonth(); +n = dt.secondOfDay(); +n = dt.dayOfYear(); n = dt.millisecond(); n = dt.unixUtcMillis(); n = dt.utcYear(); @@ -106,6 +113,11 @@ n = dt.utcHour(); n = dt.utcMinute(); n = dt.utcSecond(); n = dt.utcMillisecond(); +n = dt.utcWeekNumber(); +n = dt.utcWeekOfMonth(); +n = dt.utcSecondOfDay(); +n = dt.utcDayOfYear(); +s = dt.format("%Y-%m-%d"); dt.convert(tc.TimeZone.local()); dt = dt.toZone(tc.TimeZone.utc()); date = dt.toDate(); diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 46b202e8f..8cad4a35e 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,4 +1,4 @@ -// Type definitions for timezonecomplete 1.4.6 +// Type definitions for timezonecomplete 1.5.1 // Project: https://github.com/SpiritIT/timezonecomplete // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,10 +11,14 @@ declare module 'timezonecomplete' { export import isLeapYear = basics.isLeapYear; export import daysInMonth = basics.daysInMonth; export import daysInYear = basics.daysInYear; - export import dayOfYear = basics.dayOfYear; + export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; export import weekDayOnOrAfter = basics.weekDayOnOrAfter; export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + export import weekNumber = basics.weekNumber; + export import weekOfMonth = basics.weekOfMonth; + export import dayOfYear = basics.dayOfYear; + export import secondOfDay = basics.secondOfDay; import datetime = require("__timezonecomplete/datetime"); export import DateTime = datetime.DateTime; import duration = require("__timezonecomplete/duration"); @@ -93,6 +97,16 @@ declare module '__timezonecomplete/basics' { * @return the last occurrence of the week day in the month */ export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the first instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the first occurrence of the week day in the month + */ + export function firstWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; /** * Returns the day-of-month that is on the given weekday and which is >= the given day. * Throws if the month has no such day. @@ -103,6 +117,19 @@ declare module '__timezonecomplete/basics' { * Throws if the month has no such day. */ export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + export function weekOfMonth(year: number, month: number, day: number): number; + /** + * The ISO 8601 week number for the given date. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @param year Year e.g. 1988 + * @param month Month 1-12 + * @param day Day of month 1-31 + * + * @return Week number 1-53 + */ + export function weekNumber(year: number, month: number, day: number): number; /** * Convert a unix milli timestamp into a TimeT structure. * This does NOT take leap seconds into account. @@ -131,6 +158,10 @@ declare module '__timezonecomplete/basics' { * This does NOT take leap seconds into account. */ export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * N-th second in the day, counting from 0 + */ + export function secondOfDay(hour: number, minute: number, second: number): number; /** * Basic representation of a date and time */ @@ -332,6 +363,12 @@ declare module '__timezonecomplete/datetime' { * @return The time zone that the date is in. May be null for unaware dates. */ zone(): timezone.TimeZone; + /** + * Zone name abbreviation at this time + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * @return The abbreviation + */ + zoneAbbreviation(dstDependent?: boolean): string; /** * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. */ @@ -369,6 +406,36 @@ declare module '__timezonecomplete/datetime' { * week day numbers) */ weekDay(): basics.WeekDay; + /** + * Returns the day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + dayOfYear(): number; + /** + * The ISO 8601 week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + weekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + weekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + secondOfDay(): number; /** * @return Milliseconds since 1970-01-01T00:00:00.000Z */ @@ -397,6 +464,13 @@ declare module '__timezonecomplete/datetime' { * @return The UTC seconds 0-59 */ utcSecond(): number; + /** + * Returns the UTC day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + utcDayOfYear(): number; /** * @return The UTC milliseconds 0-999 */ @@ -406,6 +480,29 @@ declare module '__timezonecomplete/datetime' { * week day numbers) */ utcWeekDay(): basics.WeekDay; + /** + * The ISO 8601 UTC week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + utcWeekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + utcWeekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + utcSecondOfDay(): number; /** * Convert this date to the given time zone (in-place). * Throws if this date does not have a time zone. @@ -514,6 +611,7 @@ declare module '__timezonecomplete/datetime' { * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam */ toIsoString(): string; + format(formatString: string): string; /** * Modified ISO 8601 format string with IANA name if applicable. * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" @@ -523,6 +621,10 @@ declare module '__timezonecomplete/datetime' { * Used by util.inspect() */ inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; /** * Modified ISO 8601 format string in UTC without time zone info */ @@ -678,6 +780,10 @@ declare module '__timezonecomplete/duration' { * Used by util.inspect() */ inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; } } @@ -923,13 +1029,15 @@ declare module '__timezonecomplete/timezone' { hasDst(): boolean; /** * Calculate timezone offset from a UTC time. - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * * @return the offset of this time zone with respect to UTC at the given time, in minutes. */ offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; @@ -965,6 +1073,21 @@ declare module '__timezonecomplete/timezone' { * @param funcs: the set of functions to use: get() or getUTC() */ offsetForZoneDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * + * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. + */ + abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; /** * Normalizes non-existing local times by adding a forward offset change. * During a forward standard offset change or DST offset change, some amount of From 9456f1c5c149a9ebb54aac840ed32da59cdeafd2 Mon Sep 17 00:00:00 2001 From: fszlin Date: Wed, 20 Aug 2014 10:21:34 -0400 Subject: [PATCH 257/277] Add definition for parseObjectLiteral. --- knockout/knockout.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index b8db00e3c..66d2ddd94 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -525,6 +525,7 @@ interface KnockoutStatic { expressionRewriting: { bindingRewriteValidators: any; + parseObjectLiteral: { (objectLiteralString: string): any[] } }; ///////////////////////////////// From ae0cf5e7d20aa539400f543c35218c832be28ebb Mon Sep 17 00:00:00 2001 From: Ihor Kostiuk Date: Tue, 3 Jun 2014 23:36:11 +0300 Subject: [PATCH 258/277] chrome.desktopCapture and chrome.tabCapture --- chrome/chrome.d.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 23ee0d916..6d4b5c9ee 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -3,6 +3,8 @@ // Definitions by: Matthew Kimber , otiai10 // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + //////////////////// // Alarms //////////////////// @@ -537,6 +539,14 @@ declare module chrome.declarativeWebRequest { var onRequest: RequestedEvent; } +//////////////////// +// DesktopCapture +//////////////////// +declare module chrome.desktopCapture { + export function chooseDesktopMedia(sources: string[], targetTab?: chrome.tabs.Tab, callback?: (streamId: string) => void): void; + export function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; +} + //////////////////// // Dev Tools - Inspected Window //////////////////// @@ -1745,6 +1755,27 @@ declare module chrome.socket { export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; } +//////////////////// +// TabCapture +//////////////////// +declare module chrome.tabCapture { + interface CaptureInfo { + tabId: number; + status: string; + fullscreen: boolean; + } + + interface CaptureOptions { + audio?: boolean; + video?: boolean; + audioConstraints?: MediaTrackConstraints; + videoConstraints?: MediaTrackConstraints; + } + + export function capture(options: CaptureOptions, callback: (stream: LocalMediaStream) => void): void; + export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; +} + //////////////////// // Tabs //////////////////// From 98232c522c138cff786e271462f578ce244e3086 Mon Sep 17 00:00:00 2001 From: Ihor Kostiuk Date: Wed, 20 Aug 2014 17:59:02 +0300 Subject: [PATCH 259/277] srcUrl in OnClickData based on description from http://dev.opera.com/extensions/contextMenus.html (link from chrome doc doesn't work https://developer.chrome.com/extensions/contextMenusInternal#type-OnClickData) --- chrome/chrome.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 23ee0d916..1b28ede8e 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -294,6 +294,7 @@ declare module chrome.contextMenus { pageUrl: string; linkUrl?: string; parentMenuItemId?: any; + srcUrl?: string; } interface CreateProperties { From 63d0061afb26fa84d0d7aa5c4f4ea08da9cf357c Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Thu, 21 Aug 2014 20:43:33 +0900 Subject: [PATCH 260/277] modify method signature --- node/node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 282120dc6..be3813ade 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1110,7 +1110,7 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; export function randomBytes(size: number): Buffer; export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; From d5bf84fdb8538633c241b3b300545e8b98eb30ed Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Thu, 21 Aug 2014 17:43:47 +0600 Subject: [PATCH 261/277] Updated definition for the Duration.humanize See the docs there http://momentjs.com/docs/#/durations/humanize/ --- moment/moment.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 20e921c32..0ec575fd8 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -28,7 +28,7 @@ interface MomentInput { interface Duration { - humanize(): string; + humanize(withSuffix?: boolean): string; milliseconds(): number; asMilliseconds(): number; From 0446dc4b625840653b894d10b4c9b0586709e167 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Thu, 21 Aug 2014 20:44:04 +0900 Subject: [PATCH 262/277] add optional variable --- passport/passport.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 6d03093eb..977323140 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -8,6 +8,7 @@ declare module Express { export interface Request { session?: any; + authInfo?: any; // These declarations are merged into express's Request type login(user: any, done: (err: any) => void): void; From aa8615f8f29ee2ea8cd7969a41718331667b1be8 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Thu, 21 Aug 2014 20:44:20 +0900 Subject: [PATCH 263/277] fix bug --- request/request-tests.ts | 3 ++- request/request.d.ts | 6 +----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/request/request-tests.ts b/request/request-tests.ts index d422c3abc..986702c27 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -114,7 +114,8 @@ req = req.oauth(oauth); req = req.jar(jar); write = req.pipe(write); write = req.pipe(write, value); -req.write(); +req.pipe(req); +req.write(value); req.end(str); req.end(buffer); req.pause(); diff --git a/request/request.d.ts b/request/request.d.ts index e6a1d100e..5331fbd17 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -91,7 +91,7 @@ declare module 'request' { body: any; } - export interface Request { + export interface Request extends http.ClientRequest { getAgent(): http.Agent; //start(): void; //abort(): void; @@ -108,12 +108,8 @@ declare module 'request' { jar(jar: CookieJar): Request; pipe(dest: stream.Writable, opts?: any): stream.Writable; - write(): void; - end(chunk: string): void; - end(chunk: NodeBuffer): void; pause(): void; resume(): void; - abort(): void; destroy(): void; toJSON(): string; } From 777cfd5f3097370bb862ff270e15fc88c4b9b6c0 Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Thu, 21 Aug 2014 18:02:22 +0600 Subject: [PATCH 264/277] Added state field for the SignalR object --- signalr/signalr.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 7d1e64b74..4a503a84c 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -37,6 +37,7 @@ interface SignalR { messageId: string; url: string; qs: any; + state: number; (url: string, queryString?: any, logging?: boolean): SignalR; hubConnection(url?: string): SignalR; From 19e6407072a93eea6adbe6548a575329b680ef38 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Thu, 21 Aug 2014 21:09:38 +0900 Subject: [PATCH 265/277] modify exnteds interface --- request/request.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/request/request.d.ts b/request/request.d.ts index 5331fbd17..b204920a8 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -91,7 +91,7 @@ declare module 'request' { body: any; } - export interface Request extends http.ClientRequest { + export interface Request extends stream.Writable { getAgent(): http.Agent; //start(): void; //abort(): void; @@ -110,6 +110,7 @@ declare module 'request' { pipe(dest: stream.Writable, opts?: any): stream.Writable; pause(): void; resume(): void; + abort(): void; destroy(): void; toJSON(): string; } From c7c896884baaee682f7d58e233b31e65ae0a7031 Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Thu, 21 Aug 2014 21:25:29 +0200 Subject: [PATCH 266/277] Add SHellJS --- CONTRIBUTORS.md | 1 + shelljs/shelljs-tests.ts | 101 ++++++++ shelljs/shelljs.d.ts | 521 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 623 insertions(+) create mode 100644 shelljs/shelljs-tests.ts create mode 100644 shelljs/shelljs.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 99864cf67..10ebf956d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -315,6 +315,7 @@ All definitions files include a header with the author and editors, so at some p * [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) * [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) +* [ShellJS](http://shelljs.org) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [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)) diff --git a/shelljs/shelljs-tests.ts b/shelljs/shelljs-tests.ts new file mode 100644 index 000000000..d28b72398 --- /dev/null +++ b/shelljs/shelljs-tests.ts @@ -0,0 +1,101 @@ +// Tests for shelljs.d.ts +// Project: http://shelljs.org +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Tests taken from documentation samples. + +/// +/// + +import shell = require("shelljs"); + +if (!shell.which("git")) +{ + shell.echo("Sorry, this script requires git"); + shell.exit(1); +} + +// Copy files to release dir +shell.mkdir("-p", "out/Release"); +shell.cp("-R", "stuff/*", "out/Release"); + +// Replace macros in each .js file +shell.cd("lib"); +shell.ls("*.js").forEach( file => { + shell.sed("-i", "BUILD_VERSION", "v0.1.2", file); + shell.sed("-i", /.*REMOVE_THIS_LINE.*\n/, "", file); + shell.sed("-i", /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat("macro.js"), file); +}); + +shell.cd(".."); + +// Run external tool synchronously +if (shell.exec('git commit -am "Auto-commit"').code !== 0) +{ + shell.echo("Error: Git commit failed"); + shell.exit(1); +} + +shell.ls("projs/*.js"); +shell.ls("-R", "/users/me", "/tmp"); +shell.ls("-R", ["/users/me", "/tmp"]); // same as above + +shell.find("src", "lib"); +shell.find(["src", "lib"]); // same as above +shell.find(".").filter((file, i, n) => !!file.match(/\.js$/)); + +shell.cp("file1", "dir1"); +shell.cp("-Rf", ["/tmp/*", "/usr/local/*"], "/home/tmp"); // same as aboveshell. + +shell.rm("-rf", "/tmp/*"); +shell.rm("some_file.txt", "another_file.txt"); +shell.rm(["some_file.txt", "another_file.txt"]); // same as above + +shell.mv(["file1", "file2"], "dir/"); // same as above + +shell.mkdir("-p", "/tmp/a/b/c/d", "/tmp/e/f/g"); +shell.mkdir("-p", ["/tmp/a/b/c/d", "/tmp/e/f/g"]); // same as above + +if (shell.test("-d", "/tmp/a/b/c/d")) { /* do something with dir */ } +if (!shell.test("-f", "/tmp/a/b/c/d")) { /* do something with dir */ } + +var str = shell.cat("file*.txt"); +str = shell.cat("file1", "file2"); +str = shell.cat(["file1", "file2"]); // same as above + +shell.sed("-i", "PROGRAM_VERSION", "v0.1.3", "source.js"); +shell.sed(/.*DELETE_THIS_LINE.*\n/, "", "source.js"); + +shell.grep("-v", "GLOBAL_VARIABLE", "*.js"); +shell.grep("GLOBAL_VARIABLE", "*.js"); + +var nodeExec = shell.which("node"); + +shell.pushd("/etc"); // Returns /etc /usr +shell.pushd("+1"); // Returns /usr /etc + +shell.echo(process.cwd()); // '/usr' +shell.pushd("/etc"); // '/etc /usr' +shell.echo(process.cwd()); // '/etc' +shell.popd(); // '/usr' +shell.echo(process.cwd()); // '/usr' + +shell.ln("file", "newlink"); +shell.ln("-sf", "file", "existing"); + +var testPath = shell.env["path"]; + +var version = shell.exec("node --version").output; + +shell.chmod(755, "/Users/brandon"); +shell.chmod("755", "/Users/brandon"); // same as above +shell.chmod("u+x", "/Users/brandon"); + +shell.exit(0); + +var tmp = shell.tempdir(); // "/tmp" for most *nix platforms + +var errorlol = shell.error(); + +shell.config.fatal = true; +shell.config.silent = true; diff --git a/shelljs/shelljs.d.ts b/shelljs/shelljs.d.ts new file mode 100644 index 000000000..b3b732d05 --- /dev/null +++ b/shelljs/shelljs.d.ts @@ -0,0 +1,521 @@ +// Type definitions for ShellJS v0.3.0 +// Project: http://shelljs.org +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module "shelljs" +{ + /** + * Changes to directory dir for the duration of the script + * @param {string} dir Directory to change in. + */ + export function cd(dir: string): void; + + /** + * Returns the current directory. + * @return {string} The current directory. + */ + export function pwd(): string; + + /** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string[]} ...paths Paths to search. + * @return {string[]} An array of files in the given path(s). + */ + export function ls(...paths: string[]): string[]; + + /** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {string[]} ...paths Paths to search. + * @return {string[]} An array of files in the given path(s). + */ + export function ls(options: string, ...paths: string[]): string[]; + + /** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string[]} paths Paths to search. + * @return {string[]} An array of files in the given path(s). + */ + export function ls(paths: string[]): string[]; + + /** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {string[]} paths Paths to search. + * @return {string[]} An array of files in the given path(s). + */ + export function ls(options: string, paths: string[]): string[]; + + /** + * Returns array of all files (however deep) in the given paths. + * @param {string[]} ...path The path(s) to search. + * @return {string[]} An array of all files (however deep) in the given path(s). + */ + export function find(...path: string[]): string[]; + + /** + * Returns array of all files (however deep) in the given paths. + * @param {string[]} path The path(s) to search. + * @return {string[]} An array of all files (however deep) in the given path(s). + */ + export function find(path: string[]): string[]; + + /** + * Copies files. The wildcard * is accepted. + * @param {string} source The source. + * @param {string} dest The destination. + */ + export function cp(source: string, dest: string): void; + + /** + * Copies files. The wildcard * is accepted. + * @param {string[]} source The source. + * @param {string} dest The destination. + */ + export function cp(source: string[], dest: string): void; + + /** + * Copies files. The wildcard * is accepted. + * @param {string} options Available options: -f (force), -r, -R (recursive) + * @param {strin]} source The source. + * @param {string} dest The destination. + */ + export function cp(options: string, source: string, dest: string): void; + + /** + * Copies files. The wildcard * is accepted. + * @param {string} options Available options: -f (force), -r, -R (recursive) + * @param {string[]} source The source. + * @param {string} dest The destination. + */ + export function cp(options: string, source: string[], dest: string): void; + + /** + * Removes files. The wildcard * is accepted. + * @param {string[]} ...files Files to remove. + */ + export function rm(...files: string[]): void; + + /** + * Removes files. The wildcard * is accepted. + * @param {string[]} files Files to remove. + */ + export function rm(files: string[]): void; + + /** + * Removes files. The wildcard * is accepted. + * @param {string} options Available options: -f (force), -r, -R (recursive) + * @param {string[]} ...files Files to remove. + */ + export function rm(options: string, ...files: string[]): void; + + /** + * Removes files. The wildcard * is accepted. + * @param {string} options Available options: -f (force), -r, -R (recursive) + * @param {string[]} ...files Files to remove. + */ + export function rm(options: string, files: string[]): void; + + /** + * Moves files. The wildcard * is accepted. + * @param {string} source The source. + * @param {string} dest The destination. + */ + export function mv(source: string, dest: string): void; + + /** + * Moves files. The wildcard * is accepted. + * @param {string[]} source The source. + * @param {string} dest The destination. + */ + export function mv(source: string[], dest: string): void; + + /** + * Creates directories. + * @param {string[]} ...dir Directories to create. + */ + export function mkdir(...dir: string[]): void; + + /** + * Creates directories. + * @param {string[]} dir Directories to create. + */ + export function mkdir(dir: string[]): void; + + /** + * Creates directories. + * @param {string} options Available options: p (full paths, will create intermediate dirs if necessary) + * @param {string[]} ...dir The directories to create. + */ + export function mkdir(options: string, ...dir: string[]): void; + + /** + * Creates directories. + * @param {string} options Available options: p (full paths, will create intermediate dirs if necessary) + * @param {string[]} dir The directories to create. + */ + export function mkdir(options: string, dir: string[]): void; + + /** + * Evaluates expression using the available primaries and returns corresponding value. + * @param {string} option '-b': true if path is a block device; '-c': true if path is a character device; '-d': true if path is a directory; '-e': true if path exists; '-f': true if path is a regular file; '-L': true if path is a symboilc link; '-p': true if path is a pipe (FIFO); '-S': true if path is a socket + * @param {string} path The path. + * @return {boolean} See option parameter. + */ + export function test(option: string, path: string): boolean; + + /** + * Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). Wildcard * accepted. + * @param {string[]} ...files Files to use. + * @return {string} A string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). + */ + export function cat(...files: string[]): string; + + /** + * Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). Wildcard * accepted. + * @param {string[]} files Files to use. + * @return {string} A string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). + */ + export function cat(files: string[]): string; + + + // Does not work yet. + export interface String + { + /** + * Analogous to the redirection operator > in Unix, but works with JavaScript strings (such as those returned by cat, grep, etc). Like Unix redirections, to() will overwrite any existing file! + * @param {string} file The file to use. + */ + to(file: string): void; + + /** + * Analogous to the redirect-and-append operator >> in Unix, but works with JavaScript strings (such as those returned by cat, grep, etc). + * @param {string} file The file to append to. + */ + toEnd(file: string): void; + } + + /** + * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. + * @param {RegExp} searchRegex The regular expression to use for search. + * @param {string} replacement The replacement. + * @param {string} file The file to process. + * @return {string} The new string after replacement. + */ + export function sed(searchRegex: RegExp, replacement: string, file: string): string; + + /** + * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. + * @param {string} searchRegex The regular expression to use for search. + * @param {string} replacement The replacement. + * @param {string} file The file to process. + * @return {string} The new string after replacement. + */ + export function sed(searchRegex: string, replacement: string, file: string): string; + + /** + * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. + * @param {string} options Available options: -i (Replace contents of 'file' in-place. Note that no backups will be created!) + * @param {RegExp} searchRegex The regular expression to use for search. + * @param {string} replacement The replacement. + * @param {string} file The file to process. + * @return {string} The new string after replacement. + */ + export function sed(options: string, searchRegex: RegExp, replacement: string, file: string): string; + + /** + * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. + * @param {string} options Available options: -i (Replace contents of 'file' in-place. Note that no backups will be created!) + * @param {string} searchRegex The regular expression to use for search. + * @param {string} replacement The replacement. + * @param {string} file The file to process. + * @return {string} The new string after replacement. + */ + export function sed(options: string, searchRegex: string, replacement: string, file: string): string; + + /** + * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. + * @param {RegExp} regex_filter The regular expression to use. + * @param {string[]} ...files The files to process. + * @return {string} Returns a string containing all lines of the file that match the given regex_filter. + */ + export function grep(regex_filter: RegExp, ...files: string[]): string; + + /** + * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. + * @param {RegExp} regex_filter The regular expression to use. + * @param {string[]} ...files The files to process. + * @return {string} Returns a string containing all lines of the file that match the given regex_filter. + */ + export function grep(regex_filter: RegExp, files: string[]): string; + + /** + * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. + * @param {string} options Available options: -v (Inverse the sense of the regex and print the lines not matching the criteria.) + * @param {string} regex_filter The regular expression to use. + * @param {string[]} ...files The files to process. + * @return {string} Returns a string containing all lines of the file that match the given regex_filter. + */ + export function grep(options: string, regex_filter: string, ...files: string[]): string; + + /** + * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. + * @param {string} options Available options: -v (Inverse the sense of the regex and print the lines not matching the criteria.) + * @param {string} regex_filter The regular expression to use. + * @param {string[]} files The files to process. + * @return {string} Returns a string containing all lines of the file that match the given regex_filter. + */ + export function grep(options: string, regex_filter: string, files: string[]): string; + + /** + * Searches for command in the system's PATH. On Windows looks for .exe, .cmd, and .bat extensions. + * @param {string} command The command to search for. + * @return {string} Returns string containing the absolute path to the command. + */ + export function which(command: string): string; + + /** + * Prints string to stdout, and returns string with additional utility methods like .to(). + * @param {string[]} ...text The text to print. + * @return {string} Returns the string that was passed as argument. + */ + export function echo(...text: string[]): string; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {"+N"} dir Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(dir: "+N"): string[]; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {"-N"} dir Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(dir: "-N"): string[]; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {string} dir Makes the current working directory be the top of the stack, and then executes the equivalent of cd dir. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(dir: string): string[]; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) + * @param {"+N"} dir Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(options: string, dir: "+N"): string[]; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) + * @param {"-N"} dir Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(options: string, dir: "-N"): string[]; + + /** + * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) + * @param {string} dir Makes the current working directory be the top of the stack, and then executes the equivalent of cd dir. + * @return {string[]} Returns an array of paths in the stack. + */ + export function pushd(options: string, dir: string): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {"+N"} dir Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(dir: "+N"): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {"-N"} dir Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(dir: "-N"): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {string} dir You can only use -N and +N. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(dir: string): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) + * @param {"+N"} dir Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(options: string, dir: "+N"): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) + * @param {"-N"} dir Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(options: string, dir: "-N"): string[]; + + /** + * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) + * @param {string} dir You can only use -N and +N. + * @return {string[]} Returns an array of paths in the stack. + */ + export function popd(options: string, dir: string): string[]; + + /** + * Clears the directory stack by deleting all of the elements. + * @param {"-c"} options Clears the directory stack by deleting all of the elements. + * @return {string[]} Returns an array of paths in the stack, or a single path if +N or -N was specified. + */ + export function dirs(options: "-c"): string[]; + + /** + * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. + * @param {"+N"} options Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + * @return {string[]} Returns an array of paths in the stack, or a single path if +N or -N was specified. + */ + export function dirs(options: "+N"): string; + + /** + * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. + * @param {"-N"} options Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. + * @return {string[]} Returns an array of paths in the stack, or a single path if +N or -N was specified. + */ + export function dirs(options: "-N"): string; + + /** + * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. + * @param {string} options Available options: -c, -N, +N. You can only use those. + * @return {any} Returns an array of paths in the stack, or a single path if +N or -N was specified. + */ + export function dirs(options: string): any; + + /** + * Links source to dest. Use -f to force the link, should dest already exist. + * @param {string} source The source. + * @param {string} dest The destination. + */ + export function ln(source: string, dest: string): void; + + /** + * Links source to dest. Use -f to force the link, should dest already exist. + * @param {string} options Available options: s (symlink), f (force) + * @param {string} source The source. + * @param {string} dest The destination. + */ + export function ln(options: string, source: string, dest: string): void; + + /** + * Exits the current process with the given exit code. + * @param {number} code The exit code. + */ + export function exit(code: number): void; + + /** + * Object containing environment variables (both getter and setter). Shortcut to process.env. + */ + export var env: { [key: string]: string }; + + /* + + // Not yet implemented due to implementation issues (constant overloads and return types). + // See: https://github.com/arturadib/shelljs#execcommand--options--callback + + export function exec(command: string, options: ExecOptions, callback: (code: number, output: string) => any): any; + export function exec(command: string, options: ExecOptions): any; + + interface ExecOptions + { + silent: boolean; + async: boolean; + } + + */ + + /** + * Executes the given command synchronously. + * @param {string} command The commadn to execute. + * @return {ExecReturnValue} Returns an object containing the return code and output as string. + */ + export function exec(command: string): ExecReturnValue; + + interface ExecReturnValue + { + code: number; + output: string; + } + + /** + * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. + * - There is no "quiet" option since default behavior is to run silent. + * @param {number} octalMode The access mode. Octal. + * @param {string} file The file to use. + */ + export function chmod(octalMode: number, file: string): void; + + /** + * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. + * - There is no "quiet" option since default behavior is to run silent. + * @param {string} mode The access mode. Can be an octal string or a symbolic mode string. + * @param {string} file The file to use. + */ + export function chmod(mode: string, file: string): void; + + // Non-Unix commands + + /** + * Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's tempfile algorithm. + * @return {string} The temp file path. + */ + export function tempdir(): string; + + /** + * Tests if error occurred in the last command. + * @return {string} Returns null if no error occurred, otherwise returns string explaining the error + */ + export function error(): string; + + // Configuration + + interface ShellConfig + { + /** + * Suppresses all command output if true, except for echo() calls. Default is false. + * @type {boolean} + */ + silent: boolean; + + /** + * If true the script will die on errors. Default is false. + * @type {boolean} + */ + fatal: boolean; + } + + /** + * The shelljs configuration. + * @type {ShellConfig} + */ + export var config: ShellConfig; +} From a38d60a3dd5d36a14f7d76f9d25f994b92595b77 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Fri, 22 Aug 2014 12:37:27 +0900 Subject: [PATCH 267/277] add stream.Stream type --- node/node.d.ts | 4 ++++ request/request.d.ts | 14 ++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index be3813ade..4140a8c4b 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1121,6 +1121,10 @@ declare module "crypto" { declare module "stream" { import events = require("events"); + export interface Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + export interface ReadableOptions { highWaterMark?: number; encoding?: string; diff --git a/request/request.d.ts b/request/request.d.ts index b204920a8..fc03a7e19 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -91,7 +91,10 @@ declare module 'request' { body: any; } - export interface Request extends stream.Writable { + export interface Request extends stream.Stream { + readable: boolean; + writable: boolean; + getAgent(): http.Agent; //start(): void; //abort(): void; @@ -107,7 +110,14 @@ declare module 'request' { oauth(oauth: OAuthOptions): Request; jar(jar: CookieJar): Request; - pipe(dest: stream.Writable, opts?: any): stream.Writable; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + end(): void; + end(chunk: Buffer, cb?: Function): void; + end(chunk: string, cb?: Function): void; + end(chunk: string, encoding: string, cb?: Function): void; pause(): void; resume(): void; abort(): void; From ee3b10e2b0ee836bd5679d1ffa5e86dc237067df Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Fri, 22 Aug 2014 06:11:30 -0300 Subject: [PATCH 268/277] $id is a number on 1.3 --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 34e2fe8bf..2f2c68bec 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -376,7 +376,7 @@ declare module ng { $root: IRootScopeService; this: IRootScopeService; - $id: string; + $id: number; // Hidden members $$isolateBindings: any; From de1c0be350cb8756df38cdfb39e746b0c3c67dea Mon Sep 17 00:00:00 2001 From: chriscamicas Date: Fri, 22 Aug 2014 11:36:02 +0200 Subject: [PATCH 269/277] Knockout 3.2 fix for ko.components According to the documentation ko.components is missing http://knockoutjs.com/documentation/component-registration.html --- knockout/knockout.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index b8db00e3c..a400ad0bf 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -544,6 +544,8 @@ interface KnockoutStatic { writeValue(element: HTMLElement, value: any): void; }; + + components: KnockoutComponents ; } interface KnockoutBindingProvider { From 6b2b14b81d71dea440a6b36ecf1ad2e69897c416 Mon Sep 17 00:00:00 2001 From: chriscamicas Date: Fri, 22 Aug 2014 11:37:42 +0200 Subject: [PATCH 270/277] remove trailing space --- knockout/knockout.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index a400ad0bf..d9e8cdac7 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -545,7 +545,7 @@ interface KnockoutStatic { writeValue(element: HTMLElement, value: any): void; }; - components: KnockoutComponents ; + components: KnockoutComponents; } interface KnockoutBindingProvider { From 1b247dd0c7223dbaa70d0f1cdacab0286d0481ec Mon Sep 17 00:00:00 2001 From: John Reilly Date: Fri, 22 Aug 2014 12:09:25 +0100 Subject: [PATCH 271/277] AngularJS: Genericised angular.copy and added JSDoc --- angularjs/angular-tests.ts | 31 +++++++++++++++++++++++++++++++ angularjs/angular.d.ts | 15 ++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 220a63dec..2e19760e8 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -569,3 +569,34 @@ angular.module('docsTabsExample', []) templateUrl: 'my-pane.html' }; }); + +interface copyExampleUser { + name?: string; + email?: string; + gender?: string; +} + +interface copyExampleScope { + + user: copyExampleUser; + master: copyExampleUser; + update: (copyExampleUser) => any; + reset: () => any; +} + +angular.module('copyExample', []) + .controller('ExampleController', ['$scope', function ($scope: copyExampleScope) { + $scope.master = { }; + + $scope.update = function (user) { + // Example with 1 argument + $scope.master = angular.copy(user); + }; + + $scope.reset = function () { + // Example with 2 arguments + angular.copy($scope.master, $scope.user); + }; + + $scope.reset(); + }]); \ No newline at end of file diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 2f2c68bec..0fc44d976 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -42,7 +42,20 @@ declare module ng { bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; bootstrap(element: Element, modules?: any[]): auto.IInjectorService; bootstrap(element: Document, modules?: any[]): auto.IInjectorService; - copy(source: any, destination?: any): any; + + /** + * Creates a deep copy of source, which should be an object or an array. + * + * - If no destination is supplied, a copy of the object or array is created. + * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. + * - If source is not an object or array (inc. null and undefined), source is returned. + * - If source is identical to 'destination' an exception will be thrown. + * + * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. + * @param destination Destination into which the source is copied. If provided, must be of the same type as source. + */ + copy(source: T, destination?: T): T; + element: IAugmentedJQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; From 639aa3c14d909e80315840b2015ce8eff341290a Mon Sep 17 00:00:00 2001 From: John Reilly Date: Fri, 22 Aug 2014 12:14:55 +0100 Subject: [PATCH 272/277] Made tests noImplicitAny compliant --- 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 2e19760e8..0627f80be 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -580,7 +580,7 @@ interface copyExampleScope { user: copyExampleUser; master: copyExampleUser; - update: (copyExampleUser) => any; + update: (copyExampleUser: copyExampleUser) => any; reset: () => any; } From 039152e617b8b254dbc151f76a584e871caad90c Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Fri, 22 Aug 2014 21:16:48 -0700 Subject: [PATCH 273/277] Implement generic typing for D3.Map and D3.Set --- d3/d3.d.ts | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 26577be0e..f4ef9f3ba 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -538,8 +538,10 @@ declare module D3 { functor(value: (p : R) => T): (p : R) => T; functor(value: T): (p : any) => T; - map(object?: any): Map; - set(array?: Array): Set; + map(): Map; + set(): Set; + map(object: {[key: string]: T; }): Map; + set(array: T[]): Set; dispatch(...types: Array): Dispatch; rebind(target: any, source: any, ...names: Array): any; requote(str: string): string; @@ -839,25 +841,25 @@ declare module D3 { entries(values: any[]): NestKeyValue[]; } - export interface Map { + export interface Map { has(key: string): boolean; - get(key: string): any; - set(key: string, value: T): T; + get(key: string): T; + set(key: string, value: T): T; remove(key: string): boolean; - keys(): Array; - values(): Array; - entries(): Array; - forEach(func: (key: string, value: any) => void ): void; + keys(): string[]; + values(): T[]; + entries(): any[][]; // Actually of form [key: string, val: T][], but this is inexpressible in Typescript + forEach(func: (key: string, value: T) => void ): void; empty(): boolean; size(): number; } - export interface Set { - has(value: any): boolean; - add(value: T): T; - remove(value: any): boolean; - values(): Array; - forEach(func: (value: any) => void ): void; + export interface Set { + has(value: T): boolean; + add(value: T): T; + remove(value: T): boolean; + values(): string[]; + forEach(func: (value: string) => void ): void; empty(): boolean; size(): number; } @@ -1237,7 +1239,7 @@ declare module D3 { source: GraphNode; target: GraphNode; } - + export interface GraphNodeForce { index?: number; x?: number; @@ -3370,5 +3372,5 @@ declare module D3 { declare var d3: D3.Base; declare module "d3" { - export = d3; + export = d3; } From aa05ededeeaf5595f7fa050f0cc76fedba9226e9 Mon Sep 17 00:00:00 2001 From: jonathantyates Date: Sat, 23 Aug 2014 00:42:29 -0400 Subject: [PATCH 274/277] Update restangular.d.ts Added service method from https://github.com/mgonto/restangular#decoupled-restangular-service --- restangular/restangular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 9fd397bf5..a1a7e8a5e 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -93,6 +93,7 @@ declare module restangular { withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; restangularizeCollection(parent: any, element: any, route: string): ICollection; + service(route: string, parent: any): IService; stripRestangular(element: any): any; } From bb52146cfb2f0d7375b6c0ab1bcbea838d897863 Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Fri, 22 Aug 2014 22:29:16 -0700 Subject: [PATCH 275/277] [refactor] Switch from Array notation to type[] syntactic sugar. This is more idiomatic. Exactly the same semantics as before, per section 3.6.4 of the Typescript Lang Specification --- d3/d3.d.ts | 230 ++++++++++++++++++++++++++--------------------------- 1 file changed, 115 insertions(+), 115 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index f4ef9f3ba..a451a0de5 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -417,7 +417,7 @@ declare module D3 { /* * The array of built-in interpolator factories */ - interpolators: Array; + interpolators: Transition.InterpolateFactory[]; /** * Layouts */ @@ -525,11 +525,11 @@ declare module D3 { /** * gets the mouse position relative to a specified container. */ - mouse(container: any): Array; + mouse(container: any): number[]; /** * gets the touch positions relative to a specified container. */ - touches(container: any): Array>; + touches(container: any): number[][]; /** * If the specified value is a function, returns the specified value. @@ -542,8 +542,8 @@ declare module D3 { set(): Set; map(object: {[key: string]: T; }): Map; set(array: T[]): Set; - dispatch(...types: Array): Dispatch; - rebind(target: any, source: any, ...names: Array): any; + dispatch(...types: string[]): Dispatch; + rebind(target: any, source: any, ...names: any[]): any; requote(str: string): string; timer: { (funct: () => boolean, delay?: number, mark?: number): void; @@ -1134,11 +1134,11 @@ declare module D3 { /** * Runs the tree layout */ - nodes(root: GraphNode): Array; + nodes(root: GraphNode): GraphNode[]; /** * Given the specified array of nodes, such as those returned by nodes, returns an array of objects representing the links from parent to child for each node */ - links(nodes: Array): Array; + links(nodes: GraphNode[]): GraphLink[]; /** * If separation is specified, uses the specified function to compute separation between neighboring nodes. If separation is not specified, returns the current separation function */ @@ -1159,11 +1159,11 @@ declare module D3 { /** * Gets the available layout size */ - (): Array; + (): number[]; /** * Sets the available layout size */ - (size: Array): TreeLayout; + (size: number[]): TreeLayout; }; /** * Gets or sets the available node size @@ -1172,11 +1172,11 @@ declare module D3 { /** * Gets the available node size */ - (): Array; + (): number[]; /** * Sets the available node size */ - (size: Array): TreeLayout; + (size: number[]): TreeLayout; }; } @@ -1323,13 +1323,13 @@ declare module D3 { } export interface BundleLayout{ - (links: Array): Array>; + (links: GraphLink[]): GraphNode[][]; } export interface ChordLayout { matrix: { - (): Array>; - (matrix: Array>): ChordLayout; + (): number[][]; + (matrix: number[][]): ChordLayout; } padding: { (): number; @@ -1347,8 +1347,8 @@ declare module D3 { (): (a: number, b: number) => number; (comparator: (a: number, b: number) => number): ChordLayout; } - chords(): Array; - groups(): Array; + chords(): GraphLink[]; + groups(): ArcDescriptor[]; } export interface ClusterLayout{ @@ -1357,18 +1357,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): ClusterLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): ClusterLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): ClusterLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; seperation: { (): (a: GraphNode, b: GraphNode) => number; (seperation: (a: GraphNode, b: GraphNode) => number): ClusterLayout; } size: { - (): Array; - (size: Array): ClusterLayout; + (): number[]; + (size: number[]): ClusterLayout; } value: { (): (node: GraphNode) => number; @@ -1382,11 +1382,11 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): HierarchyLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): HierarchyLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): HierarchyLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): HierarchyLayout; @@ -1401,21 +1401,21 @@ declare module D3 { } export interface HistogramLayout { - (values: Array, index?: number): Array; + (values: any[], index?: number): Bin[]; value: { (): (value: any) => any; (accessor: (value: any) => any): HistogramLayout } range: { - (): (value: any, index: number) => Array; - (range: (value: any, index: number) => Array): HistogramLayout; - (range: Array): HistogramLayout; + (): (value: any, index: number) => number[]; + (range: (value: any, index: number) => number[]): HistogramLayout; + (range: number[]): HistogramLayout; } bins: { - (): (range: Array, index: number) => Array; - (bins: (range: Array, index: number) => Array): HistogramLayout; + (): (range: any[], index: number) => number[]; + (bins: (range: any[], index: number) => number[]): HistogramLayout; (bins: number): HistogramLayout; - (bins: Array): HistogramLayout; + (bins: number[]): HistogramLayout; } frequency: { (): boolean; @@ -1429,18 +1429,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): PackLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): PackLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): PackLayout; } size: { - (): Array; - (size: Array): PackLayout; + (): number[]; + (size: number[]): PackLayout; } padding: { (): number; @@ -1454,18 +1454,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): PackLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): PackLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): PackLayout; } size: { - (): Array; - (size: Array): PackLayout; + (): number[]; + (size: number[]): PackLayout; } } @@ -1475,18 +1475,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): TreeMapLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): TreeMapLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): TreeMapLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): TreeMapLayout; } size: { - (): Array; - (size: Array): TreeMapLayout; + (): number[]; + (size: number[]): TreeMapLayout; } padding: { (): number; @@ -1648,7 +1648,7 @@ declare module D3 { /** * The array of supported symbol types. */ - symbolTypes: Array; + symbolTypes: string[]; } export interface Symbol { @@ -2463,9 +2463,9 @@ declare module D3 { export interface Diagonal { (datum: any, index?: number): string; projection: { - (): (datum: any, index?: number) => Array; - (proj: (datum: any) => Array): Diagonal; - (proj: (datum: any, index: number) => Array): Diagonal; + (): (datum: any, index?: number) => number[]; + (proj: (datum: any) => number[]): Diagonal; + (proj: (datum: any, index: number) => number[]): Diagonal; }; source: { (): (datum: any, index?: number) => any; @@ -2842,19 +2842,19 @@ declare module D3 { /** * compute the latitude-longitude bounding box for a given feature. */ - bounds(feature: any): Array>; + bounds(feature: any): number[][]; /** * compute the spherical centroid of a given feature. */ - centroid(feature: any): Array; + centroid(feature: any): number[]; /** * compute the great-arc distance between two points. */ - distance(a: Array, b: Array): number; + distance(a: number[], b: number[]): number; /** * interpolate between two points along a great arc. */ - interpolate(a: Array, b: Array): (t: number) => Array; + interpolate(a: number[], b: number[]): (t: number) => number[]; /** * compute the length of a line string or the circumference of a polygon. */ @@ -2967,7 +2967,7 @@ declare module D3 { /** * */ - rotation(rotation: Array): Rotation; + rotation(rotation: number[]): Rotation; } export interface Path { @@ -3041,11 +3041,11 @@ declare module D3 { } export interface Circle { - (...args: Array): GeoJSON; + (...args: any[]): GeoJSON; origin: { - (): Array; - (origin: Array): Circle; - (origin: (...args: Array) => Array): Circle; + (): number[]; + (origin: number[]): Circle; + (origin: (...args: any[]) => number[]): Circle; } angle: { (): number; @@ -3059,31 +3059,31 @@ declare module D3 { export interface Graticule{ (): GeoJSON; - lines(): Array; + lines(): GeoJSON[]; outline(): GeoJSON; extent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } minorExtent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } majorExtent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } step: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } minorStep: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } majorStep: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } precision: { (): number; @@ -3109,33 +3109,33 @@ declare module D3 { } export interface GeoJSON { - coordinates: Array>; + coordinates: number[][]; type: string; } export interface RawProjection { - (lambda: number, phi: number): Array; - invert?(x: number, y: number): Array; + (lambda: number, phi: number): number[]; + invert?(x: number, y: number): number[]; } export interface Projection { - (coordinates: Array): Array; - invert?(point: Array): Array; + (coordinates: number[]): number[]; + invert?(point: number[]): number[]; rotate: { - (): Array; - (rotation: Array): Projection; + (): number[]; + (rotation: number[]): Projection; }; center: { - (): Array; - (location: Array): Projection; + (): number[]; + (location: number[]): Projection; }; parallels: { - (): Array; - (location: Array): Projection; + (): number[]; + (location: number[]): Projection; }; translate: { - (): Array; - (point: Array): Projection; + (): number[]; + (point: number[]): Projection; }; scale: { (): number; @@ -3146,8 +3146,8 @@ declare module D3 { (angle: number): Projection; }; clipExtent: { - (): Array>; - (extent: Array>): Projection; + (): number[][]; + (extent: number[][]): Projection; }; precision: { (): number; @@ -3166,8 +3166,8 @@ declare module D3 { } export interface Rotation extends Array { - (location: Array): Rotation; - invert(location: Array): Rotation; + (location: number[]): Rotation; + invert(location: number[]): Rotation; } export interface ProjectionMutator { @@ -3182,11 +3182,11 @@ declare module D3 { /** * compute the Voronoi diagram for the specified points. */ - voronoi(vertices: Array): Array; + voronoi(vertices: Vertice[]): Polygon[]; /** * compute the Delaunay triangulation for the specified points. */ - delaunay(vertices?: Array): Array; + delaunay(vertices?: Vertice[]): Polygon[]; /** * constructs a quadtree for an array of points. */ @@ -3194,21 +3194,21 @@ declare module D3 { /** * Constructs a new quadtree for the specified array of points. */ - quadtree(points: Array, x1: number, y1: number, x2: number, y2: number): Quadtree; + quadtree(points: Point[], x1: number, y1: number, x2: number, y2: number): Quadtree; /** * Constructs a new quadtree for the specified array of points. */ - quadtree(points: Array, width: number, height: number): Quadtree; + quadtree(points: Point[], width: number, height: number): Quadtree; /** * Returns the input array of vertices with additional methods attached */ - polygon(vertices:Array): Polygon; + polygon(vertices:Vertice[]): Polygon; /** * creates a new hull layout with the default settings. */ hull(): Hull; - hull(vertices:Array): Array; + hull(vertices:Vertice[]): Vertice[]; } export interface Vertice extends Array { @@ -3226,7 +3226,7 @@ declare module D3 { /** * Returns a two-element array representing the centroid of this polygon. */ - centroid(): Array; + centroid(): number[]; /** * Clips the subject polygon against this polygon */ @@ -3241,11 +3241,11 @@ declare module D3 { /** * Constructs a new quadtree for the specified array of points. */ - (points: Array, x1: number, y1: number, x2: number, y2: number): Quadtree; + (points: Point[], x1: number, y1: number, x2: number, y2: number): Quadtree; /** * Constructs a new quadtree for the specified array of points. */ - (points: Array, width: number, height: number): Quadtree; + (points: Point[], width: number, height: number): Quadtree; x: { (): (d: any) => any; @@ -3257,10 +3257,10 @@ declare module D3 { (accesor: (d: any) => any): QuadtreeFactory; } - size(): Array; - size(size: Array): QuadtreeFactory; - extent(): Array>; - extent(points: Array>): QuadtreeFactory; + size(): number[]; + size(size: number[]): QuadtreeFactory; + extent(): number[][]; + extent(points: number[][]): QuadtreeFactory; } export interface Quadtree { @@ -3280,15 +3280,15 @@ declare module D3 { /** * Compute the Voronoi diagram for the specified data. */ - (data: Array): Array; + (data: T[]): Polygon[]; /** * Compute the graph links for the Voronoi diagram for the specified data. */ - links(data: Array): Array; + links(data: T[]): Layout.GraphLink[]; /** * Compute the triangles for the Voronoi diagram for the specified data. */ - triangles(data: Array): Array>; + triangles(data: T[]): number[][]; x: { /** * Get the x-coordinate accessor. @@ -3333,30 +3333,30 @@ declare module D3 { /** * Get the clip extent. */ - (): Array>; + (): number[][]; /** * Set the clip extent. * * @param extent The new clip extent. */ - (extent: Array>): Voronoi; + (extent: number[][]): Voronoi; } size: { /** * Get the size. */ - (): Array; + (): number[]; /** * Set the size, equivalent to a clip extent starting from (0,0). * * @param size The new size. */ - (size: Array): Voronoi; + (size: number[]): Voronoi; } } export interface Hull { - (vertices: Array): Array; + (vertices: Vertice[]): Vertice[]; x: { (): (d: any) => any; (accesor: (d: any) => any): any; From d9aaf6bd95900a6e1083190cdab3f2e2ef069df6 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sat, 23 Aug 2014 15:05:38 +0900 Subject: [PATCH 276/277] resolve duplicate for #2676 --- express/express.d.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 7f12a9f81..d5d48308f 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -3,7 +3,7 @@ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped -/* =================== USAGE =================== +/* =================== USAGE =================== import express = require('express'); var app = express(); @@ -522,11 +522,6 @@ declare module "express" { /** * deprecated, use sendFile instead. */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - sendfile(path: string): void; /** * deprecated, use sendFile instead. @@ -1073,4 +1068,3 @@ declare module "express" { export = e; } - From 21a0b97dd79c83f8797895f3bf26bfafed76a5bc Mon Sep 17 00:00:00 2001 From: Adrien Bustany Date: Sat, 23 Aug 2014 22:56:47 +0200 Subject: [PATCH 277/277] Leaflet: Allow using as an AMD module --- leaflet/leaflet.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index a1276cbe9..f094f4734 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -4173,3 +4173,6 @@ declare var L_NO_TOUCH: boolean; */ declare var L_DISABLE_3D: boolean; +declare module "leaflet" { + export = L; +}