This commit is contained in:
EWOUT-QMINO\Ewout
2015-02-05 10:16:44 +01:00
22 changed files with 1296 additions and 59 deletions
+5 -3
View File
@@ -230,8 +230,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](google.analytics/ga.d.ts) [Google Analytics (Classic and Universal)](https://developers.google.com/analytics/devguides/collection/gajs) by [Ronnie Haakon Hegelund](http://ronniehegelund.blogspot.dk), [Pat Kujawa](http://patkujawa.com)
* [:link:](gapi/gapi.d.ts) [Google API Client](https://code.google.com/p/google-api-javascript-client) by [Frank M](https://github.com/sgtfrankieboy)
* [:link:](google.feeds/google.feed.api.d.ts) [Google Feed Apis](https://developers.google.com/feed) by [RodneyJT](https://github.com/RodneyJT)
* [:link:](google.geolocation/google.geolocation.d.ts) [Google Geolocation](https://code.google.com/p/geo-location-javascript) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](googlemaps/google.maps.d.ts) [Google Geolocation](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk)
* [:link:](google.geolocation/google.geolocation.d.ts) [Google Geolocation](https://code.google.com/p/geo-location-javascript) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](gapi.pagespeedonline/gapi.pagespeedonline.d.ts) [Google Page Speed Online Api](https://developers.google.com/speed/pagespeed) by [Frank M](https://github.com/sgtfrankieboy)
* [:link:](recaptcha/recaptcha.d.ts) [Google Recaptcha](https://www.google.com/recaptcha) by [Brent Jenkins](https://github.com/brentj73)
* [:link:](gapi.translate/gapi.translate.d.ts) [Google Translate API](https://developers.google.com/translate) by [Frank M](https://github.com/sgtfrankieboy)
@@ -293,7 +293,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](ix.js/ix.d.ts) [IxJS 1.0.6 / ix.js](https://github.com/Reactive-Extensions/IxJS) by [Igor Oleinikov](https://github.com/Igorbek)
* [:link:](ix.js/l2o.d.ts) [IxJS 1.0.6 / l2o.js](https://github.com/Reactive-Extensions/IxJS) by [Igor Oleinikov](https://github.com/Igorbek)
* [:link:](jake/jake.d.ts) [jake](https://github.com/mde/jake) by [Kon](http://phyzkit.net)
* [:link:](jasmine/jasmine.d.ts) [Jasmine](http://pivotal.github.com/jasmine) by [Boris Yankov](https://github.com/borisyankov), [Theodore Brown](https://github.com/theodorejb)
* [:link:](jasmine/jasmine.d.ts) [Jasmine](http://pivotal.github.com/jasmine) by [Boris Yankov](https://github.com/borisyankov), [Theodore Brown](https://github.com/theodorejb), [David Pärsson](https://github.com/davidparsson)
* [:link:](jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts) [Jasmine Data Driven Tests](https://github.com/gburghardt/jasmine-data_driven_tests) by [Anthony MacKinnon](https://github.com/AnthonyMacKinnon)
* [:link:](jasmine-fixture/jasmine-fixture.d.ts) [Jasmine-fixture](https://github.com/searls/jasmine-fixture) by [Craig Brett](https://github.com/craigbrett17)
* [:link:](jasmine-jquery/jasmine-jquery.d.ts) [Jasmine-JQuery](https://github.com/velesin/jasmine-jquery) by [Gregor Stamac](https://github.com/gstamac)
@@ -489,6 +489,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](mustache/mustache.d.ts) [Mustache](https://github.com/janl/mustache.js) by [Mark Ashley Bell](https://github.com/markashleybell)
* [:link:](nconf/nconf.d.ts) [nconf](https://github.com/flatiron/nconf) by [Jeff Goddard](https://github.com/jedigo), [Jean-Martin Thibault](https://github.com/jmthibault)
* [:link:](ncp/ncp.d.ts) [ncp](https://github.com/AvianFlu/ncp) by [Bart van der Schoor](https://github.com/bartvds)
* [:link:](nedb/nedb.d.ts) [NeDB](https://github.com/louischatriot/nedb) by [Stefan Steinhart](https://github.com/reppners)
* [:link:](needle/needle.d.ts) [needle](https://github.com/tomas/needle) by [San Chen](https://github.com/bigsan)
* [:link:](nexpect/nexpect.d.ts) [nexpect](https://github.com/nodejitsu/nexpect) by [vvakame](http://github.com/vvakame)
* [:link:](ng-grid/ng-grid.d.ts) [ng-grid](http://angular-ui.github.io/ng-grid) by [Ken Smith](https://github.com/smithkl42), [Roland Zwaga](https://github.com/rolandzwaga), [Kent Cooper](https://github.com/kentcooper)
@@ -524,7 +525,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](notifyjs/notifyjs.d.ts) [notify.js](https://github.com/alexgibson/notify.js) by [soundTricker](https://github.com/soundTricker)
* [:link:](noVNC/noVNC.d.ts) [noVNC](https://github.com/kanaka/noVNC) by [Ken Smith](https://github.com/smithkl42)
* [:link:](npm/npm.d.ts) [npm](https://github.com/npm/npm) by [Maxime LUCE](https://github.com/SomaticIT)
* [:link:](nprogress/NProgress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com)
* [:link:](nprogress/nprogress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com)
* [:link:](numeraljs/numeraljs.d.ts) [Numeral.js](https://github.com/adamwdraper/Numeral-js) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](object-path/object-path.d.ts) [objectPath](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar)
* [:link:](oboe/oboe.d.ts) [oboe](https://github.com/jimhigson/oboe.js) by [Jared Klopper](https://github.com/optical)
@@ -739,6 +740,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](webaudioapi/waa.d.ts) [Web Audio API](http://www.w3.org/TR/webaudio) by [Baruch Berger](https://github.com/bbss), [Kon](http://phyzkit.net), [kubosho](https://github.com/kubosho)
* [:link:](webaudioapi/waa-nightly.d.ts) [Web Audio API (nightly)](http://www.w3.org/TR/2012/WD-webaudio-20120802) by [Baruch Berger](https://github.com/bbss)
* [:link:](webmidi/webmidi.d.ts) [Web MIDI API](http://www.w3.org/TR/webmidi) by [Toshiya Nakakura](https://github.com/nakakura)
* [:link:](webspeechapi/webspeechapi.d.ts) [Web Speech API](https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html) by [SaschaNaz](https://github.com/saschanaz)
* [:link:](webcola/webcola.d.ts) [webcola](https://github.com/tgdwyer/WebCola) by [Qinfeng Chen](https://github.com/qinfchen)
* [:link:](webcrypto/WebCrypto.d.ts) [WebCrypto](http://www.w3.org/TR/WebCryptoAPI) by [Lucas Dixon](https://github.com/iislucas)
* [:link:](webrtc/MediaStream.d.ts) [WebRTC](http://dev.w3.org/2011/webrtc) by [Ken Smith](https://github.com/smithkl42)
@@ -19,8 +19,17 @@ declare module Microsoft.WindowsAzure {
logout(): void;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient;
invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise;
}
interface InvokeApiOptions
{
method?: string;
body?: any;
headers?: Object;
parameters?: Object;
}
// User object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554220.aspx
interface User {
getIdentities(): any;// { [providerName: string]: { userId: string, accessToken: string, accessTokenSecret?: string }; };
+1 -1
View File
@@ -2364,7 +2364,7 @@ declare module chrome.webRequest {
}
interface WebRequestAuthRequiredEvent extends chrome.events.Event {
addListener(callback: (details: OnAuthRequiredDetails, callback?: (response: BlockingResponse) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]) => void): void;
addListener(callback: (details: OnAuthRequiredDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
removeListener(callback: (details: OnAuthRequiredDetails, callback?: (response: BlockingResponse) => void) => void): void;
}
+23 -15
View File
@@ -173,6 +173,11 @@ declare module jquery.flot {
y: number;
}
interface offset {
left: number;
top: number;
}
interface canvasPoint {
top: number;
left: number;
@@ -188,26 +193,29 @@ declare module jquery.flot {
}
interface axis extends axisOptions {
p2c(point):canvasPoint;
c2p(canvasPoint):point;
options: axisOptions;
p2c(point: point):canvasPoint;
c2p(canvasPoint: canvasPoint):point;
}
interface plot {
highlight(series: dataSeries, datapoint: item);
unhightlight();
unhighlight(series: dataSeries, datapoint: item);
setData(data: any);
setupGrid();
draw();
triggerRedrawOverlay();
width();
height();
offset();
pointOffset(point: point);
resize();
shutdown();
highlight(series: dataSeries, datapoint: item): void;
unhightlight(): void;
unhighlight(series: dataSeries, datapoint: item): void;
setData(data: any): void;
setupGrid(): void;
draw(): void;
triggerRedrawOverlay(): void;
width(): number;
height(): number;
offset(): JQueryCoordinates;
pointOffset(point: point): offset;
resize(): void;
shutdown(): void;
getData(): dataSeries[];
getAxes(): axes;
getXAxes(): axis[];
getYAxes(): axis[];
getPlaceholder(): JQuery;
getCanvas(): HTMLCanvasElement;
getPlotOffset(): canvasPoint;
+1
View File
@@ -164,6 +164,7 @@ declare module "fs-extra" {
export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
export function exists(path: string, callback?: (exists: boolean) => void ): void;
export function existsSync(path: string): boolean;
export function ensureDir(path: string, cb: (err: Error) => void): void;
export interface OpenOptions {
encoding?: string;
+3 -1
View File
@@ -3,6 +3,8 @@
// Definitions by: Philip Bulley <https://github.com/milkisevil/>, Han Lin Yap <https://github.com/codler>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../touch-events/touch-events.d.ts" />
declare var Hammer:HammerStatic;
declare module "Hammer" {
@@ -167,7 +169,7 @@ declare class HammerInput
center:HammerPoint;
/** Source event object, type TouchEvent, MouseEvent or PointerEvent. */
srcEvent:Event; // TODO: Update to Union Type (TouchEvent | MouseEvent | PointerEvent) if it lands in TS1.4
srcEvent:TouchEvent | MouseEvent | PointerEvent;
/** Target that received the event. */
target:HTMLElement;
+9 -9
View File
@@ -136,7 +136,7 @@ interface HighchartsAxisOptions {
tickWidth?: number;
tickmarkPlacement?: string; // "between" or "on"
title?: HighchartsAxisTitle;
type?: string; // "linear", "logarithmic" or "datetime"
type?: string; // "linear", "logarithmic" or "datetime"
}
interface HighchartsExtremes {
@@ -175,7 +175,7 @@ interface HighchartsColorOrGradient {
cx: number; cy: number; r: number;
};
stops?: any[][];
brighten?(amount: number): HighchartsColorOrGradient;
get?(type: string): string;
}
@@ -986,10 +986,10 @@ interface HighchartsAxisObject {
}
interface HighchartsChartObject {
addSeries(options: HighchartsSeriesOptions): HighchartsSeriesOptions;
addSeries(options: HighchartsSeriesOptions, redraw: boolean): HighchartsSeriesOptions;
addSeries(options: HighchartsSeriesOptions, redraw: boolean, animation: boolean): HighchartsSeriesOptions;
addSeries(options: HighchartsSeriesOptions, redraw: boolean, animation: HighchartsAnimation): HighchartsSeriesOptions;
addSeries(options: HighchartsSeriesOptions, redraw?: boolean, animation?: boolean): HighchartsSeriesOptions;
addSeries(options: HighchartsSeriesOptions, redraw?: boolean, animation?: HighchartsAnimation): HighchartsSeriesOptions;
addAxis(options: HighchartsAxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean): HighchartsAxisObject;
addAxis(options: HighchartsAxisOptions, isX?: boolean, redraw?: boolean, animation?: HighchartsAnimation): HighchartsAxisObject;
container: HTMLElement;
destroy(): void;
exportChart(): void;
@@ -1057,7 +1057,7 @@ interface HighchartsStatic {
numberFormat(value: number, decimals?: number, decimalPoint?: string, thousandsSep?: string): string;
setOptions(options: HighchartsOptions): HighchartsOptions;
getOptions(): HighchartsOptions;
map(array: any[], fn: Function): any[];
}
declare var Highcharts: HighchartsStatic;
@@ -1103,9 +1103,9 @@ interface HighchartsSeriesObject {
select(): void;
select(selected?: boolean): void;
selected: boolean;
setData(data: number[]): void; // [value1,value2, ... ]
setData(data: number[]): void; // [value1,value2, ... ]
setData(data: number[], redraw: boolean): void;
setData(data: number[][]): void; // [[x1,y1],[x2,y2],... ]
setData(data: number[][]): void; // [[x1,y1],[x2,y2],... ]
setData(data: number[][], redraw: boolean): void;
setData(data: HighchartsDataPoint[]): void; // HighchartsDataPoint[]
setData(data: HighchartsDataPoint[], redraw: boolean): void;
+54
View File
@@ -400,6 +400,44 @@ describe("A spy, when configured to throw a value", function () {
});
});
describe("A spy, when configured with multiple actions", function () {
var foo: any, bar: any, fetchedBar: any;
beforeEach(function () {
foo = {
setBar: function (value: any) {
bar = value;
},
getBar: function () {
return bar;
}
};
spyOn(foo, 'getBar').and.callThrough().and.callFake(() => {
this.fakeCalled = true;
});
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function () {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function () {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function () {
expect(fetchedBar).toEqual(123);
});
it("should have called the fake implementation", function () {
expect(this.fakeCalled).toEqual(true);
});
});
describe("A spy", function () {
var foo: any, bar: any = null;
@@ -676,6 +714,22 @@ describe("Asynchronous specs", function () {
});
});
describe("Fail", function () {
it("should fail test when called without arguments", function () {
fail();
});
it("should fail test when called with a fail message", function () {
fail("The test failed");
});
it("should fail test when called an error", function () {
fail(new Error("The test failed with this error"));
});
});
(() => {
// from boot.js
var env = jasmine.getEnv();
+7 -5
View File
@@ -1,6 +1,6 @@
// Type definitions for Jasmine 2.1
// Project: http://pivotal.github.com/jasmine/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Theodore Brown <https://github.com/theodorejb>
// Project: http://jasmine.github.io/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Theodore Brown <https://github.com/theodorejb>, David Pärsson <https://github.com/davidparsson/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -33,6 +33,8 @@ declare function afterAll(action: (done: () => void) => void): void;
declare function expect(spy: Function): jasmine.Matchers;
declare function expect(actual: any): jasmine.Matchers;
declare function fail(e?: any): void;
declare function spyOn(object: any, method: string): jasmine.Spy;
declare function runs(asyncMethod: Function): void;
@@ -372,15 +374,15 @@ declare module jasmine {
interface SpyAnd {
/** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */
callThrough(): void;
callThrough(): Spy;
/** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */
returnValue(val: any): void;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */
callFake(fn: Function): void;
callFake(fn: Function): Spy;
/** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */
throwError(msg: string): void;
/** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */
stub(): void;
stub(): Spy;
}
interface Calls {
+2
View File
@@ -231,6 +231,8 @@ declare module Marionette {
* @param optionName the name of the option to retrieve.
*/
getOption(optionName: string): any;
triggerMethod(name: string, ...args: any[]): any;
}
interface RegionConstructionOptions {
+553
View File
@@ -0,0 +1,553 @@
/**
* Created by stefansteinhart on 31.01.15.
*/
/// <reference path="../q/Q.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="nedb.d.ts" />
import Q = require('q');
import nedb = require('nedb');
class BaseCollection<T> {
private dataStore:nedb;
constructor(dataStore:nedb) {
this.dataStore = dataStore;
}
public insert(document:T):Q.Promise<T> {
var deferred = Q.defer<T>();
this.dataStore.insert<T>(document, function (err:Error, newDoc:T) { // Callback is optional
// newDoc is the newly inserted document, including its _id
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(newDoc);
}
});
return deferred.promise;
}
public count():Q.Promise<number> {
var deferred = Q.defer<number>();
this.dataStore.count({}, function (err:Error, count:number) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(count);
}
});
return deferred.promise;
}
public countBy(criteria:any):Q.Promise<number> {
var deferred = Q.defer<number>();
this.dataStore.count(criteria, function (err:Error, count:number) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(count);
}
});
return deferred.promise;
}
public findByID(id:string):Q.Promise<T> {
var deferred = Q.defer<T>();
this.dataStore.findOne<T>({_id: id}, function (err:Error, doc:T) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(doc);
}
});
return deferred.promise;
}
public findOne(criteria:any):Q.Promise<T> {
var deferred = Q.defer<T>();
this.dataStore.findOne<T>(criteria, function (err:Error, doc:T) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(doc);
}
});
return deferred.promise;
}
public find(criteria:any):Q.Promise<Array<T>> {
var deferred = Q.defer<Array<T>>();
this.dataStore.find(criteria, function (err:Error, docs:Array<T>) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(docs);
}
});
return deferred.promise;
}
public all():Q.Promise<Array<T>> {
var deferred = Q.defer<Array<T>>();
this.dataStore.find({}, function (err:Error, docs:Array<T>) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(docs);
}
});
return deferred.promise;
}
public upsert(query:any, updateQuery:any):Q.Promise<T> {
var deferred = Q.defer<T>();
this.dataStore.update(query, updateQuery, {upsert: true}, function (err:Error, numberOfUpdated:number, upsert:boolean) {
if (err) {
deferred.reject(err);
}
else {
//deferred.resolve(newDoc);
}
});
return deferred.promise;
}
public update(query:Object, updateQuery:Object, options?:NeDB.UpdateOptions):Q.Promise<number> {
var deferred = Q.defer<number>();
this.dataStore.update(query, updateQuery, options, function (err:Error, numberOfUpdated:number) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(numberOfUpdated);
}
});
return deferred.promise;
}
public remove(criteria:any):Q.Promise<number> {
var deferred = Q.defer<number>();
this.dataStore.remove(criteria, function (err:Error, numberOfDeletedEntrys:number) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(numberOfDeletedEntrys);
}
});
return deferred.promise;
}
}
// Type 1: In-memory only datastore (no need to load the database)
import Datastore = require('nedb');
var db = new Datastore();
// Type 2: Persistent datastore with manual loading
db = new Datastore({filename: 'path/to/datafile'});
db.loadDatabase(function (err) { // Callback is optional
// Now commands will be executed
});
// Type 3: Persistent datastore with automatic loading
db = new Datastore({filename: 'path/to/datafile', autoload: true});
// You can issue commands right away
// Type 4: Persistent datastore for a Node Webkit app called 'nwtest'
// For example on Linux, the datafile will be ~/.config/nwtest/nedb-data/something.db
import path = require('path');
db = new Datastore({filename: path.join(require('nw.gui').App.dataPath, 'something.db')});
// Of course you can create multiple datastores if you need several
// collections. In this case it's usually a good idea to use autoload for all collections.
var dbContainer:any = {};
dbContainer.users = new Datastore('path/to/users.db');
dbContainer.robots = new Datastore('path/to/robots.db');
// You need to load each database (here we do it asynchronously)
dbContainer.users.loadDatabase();
dbContainer.robots.loadDatabase();
var doc:any = {
hello: 'world'
, n: 5
, today: new Date()
, nedbIsAwesome: true
, notthere: null
, notToBeSaved: undefined // Will not be saved
, fruits: ['apple', 'orange', 'pear']
, infos: {name: 'nedb'}
};
db.insert(doc, function (err:Error, newDoc:any) { // Callback is optional
// newDoc is the newly inserted document, including its _id
// newDoc has no key called notToBeSaved since its value was undefined
});
db.insert([{a: 5}, {a: 42}], function (err:Error, newdocs:Array<any>) {
// Two documents were inserted in the database
// newDocs is an array with these documents, augmented with their _id
});
// If there is a unique constraint on field 'a', this will fail
db.insert([{a: 5}, {a: 42}, {a: 5}], function (err:Error) {
// err is a 'uniqueViolated' error
// The database was not modified
});
// Finding all planets in the solar system
db.find({system: 'solar'}, function (err:Error, docs:Array<any>) {
// docs is an array containing documents Mars, Earth, Jupiter
// If no document is found, docs is equal to []
});
// Finding all planets whose name contain the substring 'ar' using a regular expression
db.find({planet: /ar/}, function (err:Error, docs:Array<any>) {
// docs contains Mars and Earth
});
// Finding all inhabited planets in the solar system
db.find({system: 'solar', inhabited: true}, function (err:Error, docs:Array<any>) {
// docs is an array containing document Earth only
});
// Use the dot-notation to match fields in subdocuments
db.find({"humans.genders": 2}, function (err:Error, docs:Array<any>) {
// docs contains Earth
});
// Use the dot-notation to navigate arrays of subdocuments
db.find({"completeData.planets.name": "Mars"}, function (err:Error, docs:Array<any>) {
// docs contains document 5
});
db.find({"completeData.planets.name": "Jupiter"}, function (err:Error, docs:Array<any>) {
// docs is empty
});
db.find({"completeData.planets.0.name": "Earth"}, function (err:Error, docs:Array<any>) {
// docs contains document 5
// If we had tested against "Mars" docs would be empty because we are matching against a specific array element
});
// You can also deep-compare objects. Don't confuse this with dot-notation!
db.find({humans: {genders: 2}}, function (err:Error, docs:Array<any>) {
// docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true }
});
// Find all documents in the collection
db.find({}, function (err:Error, docs:Array<any>) {
});
// The same rules apply when you want to only find one document
db.findOne({_id: 'id1'}, function (err:Error, doc:any) {
// doc is the document Mars
// If no document is found, doc is null
});
// $lt, $lte, $gt and $gte work on numbers and strings
db.find({"humans.genders": {$gt: 5}}, function (err:Error, docs:Array<any>) {
// docs contains Omicron Persei 8, whose humans have more than 5 genders (7).
});
// When used with strings, lexicographical order is used
db.find({planet: {$gt: 'Mercury'}}, function (err:Error, docs:Array<any>) {
// docs contains Omicron Persei 8
})
// Using $in. $nin is used in the same way
db.find({planet: {$in: ['Earth', 'Jupiter']}}, function (err:Error, docs:Array<any>) {
// docs contains Earth and Jupiter
});
// Using $exists
db.find({satellites: {$exists: true}}, function (err:Error, docs:Array<any>) {
// docs contains only Mars
});
// Using $regex with another operator
db.find({planet: {$regex: /ar/, $nin: ['Jupiter', 'Earth']}}, function (err:Error, docs:Array<any>) {
// docs only contains Mars because Earth was excluded from the match by $nin
});
// Using an array-specific comparison function
// Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error
db.find({satellites: {$size: 2}}, function (err:Error, docs:Array<any>) {
// docs contains Mars
});
db.find({satellites: {$size: 1}}, function (err:Error, docs:Array<any>) {
// docs is empty
});
// If a document's field is an array, matching it means matching any element of the array
db.find({satellites: 'Phobos'}, function (err:Error, docs:Array<any>) {
// docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' }
});
// This also works for queries that use comparison operators
db.find({satellites: {$lt: 'Amos'}}, function (err:Error, docs:Array<any>) {
// docs is empty since Phobos and Deimos are after Amos in lexicographical order
});
// This also works with the $in and $nin operator
db.find({satellites: {$in: ['Moon', 'Deimos']}}, function (err:Error, docs:Array<any>) {
// docs contains Mars (the Earth document is not complete!)
});
db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}]}, function (err:Error, docs:Array<any>) {
// docs contains Earth and Mars
});
db.find({$not: {planet: 'Earth'}}, function (err:Error, docs:Array<any>) {
// docs contains Mars, Jupiter, Omicron Persei 8
});
db.find({
$where: function () {
return parseInt(Object.keys(this)[0]) > 6;
}
}, function (err:Error, docs:Array<any>) {
// docs with more than 6 properties
});
// You can mix normal queries, comparison queries and logical operators
db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}], inhabited: true}, function (err:Error, docs:Array<any>) {
// docs contains Earth
});
// No query used means all results are returned (before the Cursor modifiers)
db.find({}).sort({planet: 1}).skip(1).limit(2).exec(function (err:Error, docs:Array<any>) {
// docs is [doc3, doc1]
});
// You can sort in reverse order like this
db.find({system: 'solar'}).sort({planet: -1}).exec(function (err:Error, docs:Array<any>) {
// docs is [doc1, doc3, doc2]
});
// You can sort on one field, then another, and so on like this:
db.find({}).sort({firstField: 1, secondField: -1});
// Same database as above
// Keeping only the given fields
db.find({planet: 'Mars'}, {planet: 1, system: 1}, function (err:Error, docs:Array<any>) {
// docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
});
// Keeping only the given fields but removing _id
db.find({planet: 'Mars'}, {planet: 1, system: 1, _id: 0}, function (err:Error, docs:Array<any>) {
// docs is [{ planet: 'Mars', system: 'solar' }]
});
// Omitting only the given fields and removing _id
db.find({planet: 'Mars'}, {planet: 0, system: 0, _id: 0}, function (err:Error, docs:Array<any>) {
// docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }]
});
// Failure: using both modes at the same time
db.find({planet: 'Mars'}, {planet: 0, system: 1}, function (err:Error, docs:Array<any>) {
// err is the error message, docs is undefined
});
// You can also use it in a Cursor way but this syntax is not compatible with MongoDB
// If upstream compatibility is important don't use this method
db.find({planet: 'Mars'}).projection({planet: 1, system: 1}).exec(function (err:Error, docs:Array<any>) {
// docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
});
// Count all planets in the solar system
db.count({system: 'solar'}, function (err:Error, count:number) {
// count equals to 3
});
// Count all documents in the datastore
db.count({}, function (err:Error, count:number) {
// count equals to 4
});
// Let's use the same example collection as in the "finding document" part
// { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }
// { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }
// { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }
// Replace a document by another
db.update({planet: 'Jupiter'}, {planet: 'Pluton'}, {}, function (err:Error, numReplaced:number) {
// numReplaced = 1
// The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' }
// Note that the _id is kept unchanged, and the document has been replaced
// (the 'system' and inhabited fields are not here anymore)
});
// Set an existing field's value
db.update({system: 'solar'}, {$set: {system: 'solar system'}}, {multi: true}, function (err:Error, numReplaced:number) {
// numReplaced = 3
// Field 'system' on Mars, Earth, Jupiter now has value 'solar system'
});
// Setting the value of a non-existing field in a subdocument by using the dot-notation
db.update({planet: 'Mars'}, {$set: {"data.satellites": 2, "data.red": true}}, {}, function () {
// Mars document now is { _id: 'id1', system: 'solar', inhabited: false
// , data: { satellites: 2, red: true }
// }
// Not that to set fields in subdocuments, you HAVE to use dot-notation
// Using object-notation will just replace the top-level field
db.update({planet: 'Mars'}, {$set: {data: {satellites: 3}}}, {}, function () {
// Mars document now is { _id: 'id1', system: 'solar', inhabited: false
// , data: { satellites: 3 }
// }
// You lost the "data.red" field which is probably not the intended behavior
});
});
// Deleting a field
db.update({planet: 'Mars'}, {$unset: {planet: true}}, {}, function () {
// Now the document for Mars doesn't contain the planet field
// You can unset nested fields with the dot notation of course
});
// Upserting a document
db.update({planet: 'Pluton'}, {
planet: 'Pluton',
inhabited: false
}, {upsert: true}, function (err:Error, numReplaced:number, upsert:boolean) {
// numReplaced = 1, upsert = { _id: 'id5', planet: 'Pluton', inhabited: false }
// A new document { _id: 'id5', planet: 'Pluton', inhabited: false } has been added to the collection
});
// If you upsert with a modifier, the upserted doc is the query modified by the modifier
// This is simpler than it sounds :)
db.update({planet: 'Pluton'}, {$inc: {distance: 38}}, {upsert: true}, function () {
// A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection
});
// If we insert a new document { _id: 'id6', fruits: ['apple', 'orange', 'pear'] } in the collection,
// let's see how we can modify the array field atomically
// $push inserts new elements at the end of the array
db.update({_id: 'id6'}, {$push: {fruits: 'banana'}}, {}, function () {
// Now the fruits array is ['apple', 'orange', 'pear', 'banana']
});
// $pop removes an element from the end (if used with 1) or the front (if used with -1) of the array
db.update({_id: 'id6'}, {$pop: {fruits: 1}}, {}, function () {
// Now the fruits array is ['apple', 'orange']
// With { $pop: { fruits: -1 } }, it would have been ['orange', 'pear']
});
// $addToSet adds an element to an array only if it isn't already in it
// Equality is deep-checked (i.e. $addToSet will not insert an object in an array already containing the same object)
// Note that it doesn't check whether the array contained duplicates before or not
db.update({_id: 'id6'}, {$addToSet: {fruits: 'apple'}}, {}, function () {
// The fruits array didn't change
// If we had used a fruit not in the array, e.g. 'banana', it would have been added to the array
});
// $pull removes all values matching a value or even any NeDB query from the array
db.update({_id: 'id6'}, {$pull: {fruits: 'apple'}}, {}, function () {
// Now the fruits array is ['orange', 'pear']
});
db.update({_id: 'id6'}, {$pull: {fruits: {$in: ['apple', 'pear']}}}, {}, function () {
// Now the fruits array is ['orange']
});
// $each can be used to $push or $addToSet multiple values at once
// This example works the same way with $addToSet
db.update({_id: 'id6'}, {$push: {fruits: {$each: ['banana', 'orange']}}}, {}, function () {
// Now the fruits array is ['apple', 'orange', 'pear', 'banana', 'orange']
});
// Let's use the same example collection as in the "finding document" part
// { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }
// { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }
// { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }
// Remove one document from the collection
// options set to {} since the default for multi is false
db.remove({_id: 'id2'}, {}, function (err:Error, numRemoved:number) {
// numRemoved = 1
});
// Remove multiple documents
db.remove({system: 'solar'}, {multi: true}, function (err:Error, numRemoved:number) {
// numRemoved = 3
// All planets from the solar system were removed
});
db.ensureIndex({fieldName: 'somefield'}, function (err:Error) {
// If there was an error, err is not null
});
// Using a unique constraint with the index
db.ensureIndex({fieldName: 'somefield', unique: true}, function (err:Error) {
});
// Using a sparse unique index
db.ensureIndex({fieldName: 'somefield', unique: true, sparse: true}, function (err:Error) {
});
// Format of the error message when the unique constraint is not met
db.insert({somefield: 'nedb'}, function (err:Error) {
// err is null
db.insert({somefield: 'nedb'}, function (err:Error) {
// err is { errorType: 'uniqueViolated'
// , key: 'name'
// , message: 'Unique constraint violated for key name' }
});
});
// Remove index on field somefield
db.removeIndex('somefield', function (err:Error) {
});
+207
View File
@@ -0,0 +1,207 @@
// Type definitions for NeDB
// Project: https://github.com/louischatriot/nedb
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "nedb" {
class NeDBDataStore {
constructor();
constructor(path:string);
constructor(options:NeDB.DataStoreOptions);
persistence:NeDB.Persistence;
/**
* Load the database from the datafile, and trigger the execution of buffered commands if any
*/
loadDatabase(cb?:(err:Error)=>void):void;
/**
* Get an array of all the data in the database
*/
getAllData():Array<any>;
/**
* Reset all currently defined indexes
*/
resetIndexes(newData:any):void;
/**
* Ensure an index is kept for this field. Same parameters as lib/indexes
* For now this function is synchronous, we need to test how much time it takes
* We use an async API for consistency with the rest of the code
* @param {String} options.fieldName
* @param {Boolean} options.unique
* @param {Boolean} options.sparse
* @param {Function} cb Optional callback, signature: err
*/
ensureIndex(options:NeDB.EnsureIndexOptions, cb?:(err:Error)=>void):void;
/**
* Remove an index
* @param {String} fieldName
* @param {Function} cb Optional callback, signature: err
*/
removeIndex(fieldName:string, cb?:(err:Error)=>void):void;
/**
* Add one or several document(s) to all indexes
*/
addToIndexes<T>(doc:T):void;
addToIndexes<T>(doc:Array<T>):void;
/**
* Remove one or several document(s) from all indexes
*/
removeFromIndexes<T>(doc:T):void;
removeFromIndexes<T>(doc:Array<T>):void;
/**
* Update one or several documents in all indexes
* To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
* If one update violates a constraint, all changes are rolled back
*/
updateIndexes<T>(oldDoc:T, newDoc:T):void;
updateIndexes<T>(updates:Array<{oldDoc:T; newDoc:T;}>):void;
/**
* Return the list of candidates for a given query
* Crude implementation for now, we return the candidates given by the first usable index if any
* We try the following query types, in this order: basic match, $in match, comparison match
* One way to make it better would be to enable the use of multiple indexes if the first usable index
* returns too much data. I may do it in the future.
*
* TODO: needs to be moved to the Cursor module
*/
getCandidates(query:any):void;
/**
* Insert a new document
* @param {Function} cb Optional callback, signature: err, insertedDoc
*/
insert<T>(newDoc:T, cb?:(err:Error, document:T)=>void):void;
/**
* Count all documents matching the query
* @param {any} query MongoDB-style query
*/
count(query:any, callback:(err:Error, n:number)=>void):void;
count(query:any):NeDB.CursorCount;
/**
* Find all documents matching the query
* If no callback is passed, we return the cursor so that user can limit, skip and finally exec
* @param {any} query MongoDB-style query
* @param {any} projection MongoDB-style projection
*/
find<T>(query:any, projection:T, callback:(err:Error, documents:Array<T>)=>void):void;
find<T>(query:any, projection:T):NeDB.Cursor<T>;
/**
* Find all documents matching the query
* If no callback is passed, we return the cursor so that user can limit, skip and finally exec
* * @param {any} query MongoDB-style query
*/
find<T>(query:any, callback:(err:Error, documents:Array<T>)=>void):void;
find<T>(query:any):NeDB.Cursor<T>;
/**
* Find one document matching the query
* @param {any} query MongoDB-style query
* @param {any} projection MongoDB-style projection
*/
findOne<T>(query:any, projection:T, callback:(err:Error, document:T)=>void):void;
/**
* Find one document matching the query
* @param {any} query MongoDB-style query
*/
findOne<T>(query:any, callback:(err:Error, document:T)=>void):void;
/**
* Update all docs matching query
* For now, very naive implementation (recalculating the whole database)
* @param {any} query
* @param {any} updateQuery
* @param {Object} options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* options.upsert If true, document is inserted if the query doesn't match anything
* @param {Function} cb Optional callback, signature: err, numReplaced, upsert (set to true if the update was in fact an upsert)
*
* @api private Use Datastore.update which has the same signature
*/
update(query:any, updateQuery:any, options?:NeDB.UpdateOptions, cb?:(err:Error, numberOfUpdated:number, upsert:boolean)=>void):void;
/**
* Remove all docs matching the query
* For now very naive implementation (similar to update)
* @param {Object} query
* @param {Object} options Optional options
* options.multi If true, can update multiple documents (defaults to false)
* @param {Function} cb Optional callback, signature: err, numRemoved
*
* @api private Use Datastore.remove which has the same signature
*/
remove(query:any, options:NeDB.RemoveOptions, cb?:(err:Error, n:number)=>void):void;
remove(query:any, cb?:(err:Error, n:number)=>void):void;
}
export = NeDBDataStore;
}
declare module NeDB {
interface Cursor<T> {
sort(query:any):Cursor<T>;
skip(n:number):Cursor<T>;
limit(n:number):Cursor<T>;
projection(query:any):Cursor<T>;
exec(callback:(err:Error, documents:Array<T>)=>void):void;
}
interface CursorCount {
exec(callback:(err:Error, count:number)=>void):void;
}
interface DataStoreOptions {
filename?:string // Optional, datastore will be in-memory only if not provided
inMemoryOnly?:boolean // Optional, default to false
nodeWebkitAppName?:boolean // Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
autoload?:boolean // Optional, defaults to false
onload?:(error:Error)=>any // Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown
afterSerialization?:(line:string)=>string; // (optional): hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost)
beforeDeserialization?:(line:string)=>string; // (optional): reverse of afterSerialization. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below)
corruptAlertThreshold?:number; // (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care
}
/**
* multi (defaults to false) which allows the modification of several documents if set to true
* upsert (defaults to false) if you want to insert a new document corresponding to the update rules if your query doesn't match anything
*/
interface UpdateOptions {
multi?: boolean;
upsert?: boolean;
}
/**
* options only one option for now: multi which allows the removal of multiple documents if set to true. Default is false
*/
interface RemoveOptions {
multi?:boolean
}
interface EnsureIndexOptions {
fieldName:string;
unique?:boolean;
sparse?:boolean;
}
interface Persistence {
compactDatafile():void;
setAutocompactionInterval(interval:number):void;
stopAutocompaction():void;
}
}
+4
View File
@@ -5,6 +5,7 @@ import zmq = require('zmq');
function test1() {
var sock = zmq.socket('push');
sock.bindSync('tcp://127.0.0.1:3000');
sock.unbindSync('tcp://127.0.0.1:3000');
sock.send("some work");
}
@@ -28,6 +29,9 @@ function test4() {
sock.bind('tcp://127.0.0.1', err => {
sock.send("some work");
});
sock.unbind('tcp://127.0.0.1', err => {
//
});
}
function test5() {
+18 -1
View File
@@ -85,7 +85,7 @@ declare module 'zmq' {
* @param addr Socket address
* @param cb Bind callback
*/
bind(addr: string, callback: (error: string) => void ): Socket;
bind(addr: string, callback?: (error: string) => void ): Socket;
/**
* Sync bind.
@@ -94,6 +94,23 @@ declare module 'zmq' {
*/
bindSync(addr: string): Socket;
/**
* Async unbind.
*
* Emits the "unbind" event.
*
* @param addr Socket address
* @param cb Unind callback
*/
unbind(addr: string, callback?: (error: string) => void ): Socket;
/**
* Sync unbind.
*
* @param addr Socket address
*/
unbindSync(addr: string): Socket;
/**
* Connect to `addr`.
*
+8 -3
View File
@@ -42,7 +42,7 @@ var INPUT_REF: string = "input";
// Top-Level API
// --------------------------------------------------------------------------
var reactClass: React.ComponentClass<Props, State, Context> = React.createClass<Props, State, Context>({
var reactClassicClass: React.ClassicComponentClass<Props, State, Context> = React.createClass<Props, State, Context>({
getDefaultProps: () => {
return <Props>{
hello: undefined,
@@ -69,6 +69,8 @@ var reactClass: React.ComponentClass<Props, State, Context> = React.createClass<
}
});
var reactClass: React.ComponentClass<Props, State, Context> = reactClassicClass;
class ModernComponent extends React.Component<Props, State, Context> implements React.ChildContextProvider<ChildContext> {
constructor(props: Props, context: Context) {
super(props, context);
@@ -149,6 +151,11 @@ var isValid = React.isValidElement(reactElement); // true
React.initializeTouchEvents(true);
var domNode: Element = React.findDOMNode(component);
var reactClassicElement: React.ReactClassicElement<Props>;
reactClassicElement = React.createElement<Props>(reactClassicClass, props);
var classicComponent: React.ClassicComponent<Props, State, Context>;
classicComponent = React.render<Props, State>(reactClassicElement, container);
//
// React Elements
// --------------------------------------------------------------------------
@@ -177,8 +184,6 @@ component.setState({ inputValue: "!!!" });
component.forceUpdate();
// classic
var classicComponent = <React.ClassicComponent<Props, State, Context>>component;
var htmlElement: Element = classicComponent.getDOMNode();
var divElement: HTMLDivElement = classicComponent.getDOMNode<HTMLDivElement>();
var isMounted: boolean = classicComponent.isMounted();
+5
View File
@@ -17,6 +17,9 @@ declare module React {
ref: string;
}
interface ReactClassicElement<P> extends ReactElement<P> {
}
interface ReactHTMLElement extends ReactElement<HTMLAttributes> {}
interface ReactSVGElement extends ReactElement<SVGAttributes> {}
@@ -112,8 +115,10 @@ declare module React {
interface TopLevelAPI {
createClass<P, S, C>(spec: ComponentSpec<P, S, C>): ClassicComponentClass<P, S, C>;
createElement<P>(type: ClassicComponentClass<P, any, any>, props: P, ...children: ReactNode[]): ReactClassicElement<P>;
createElement<P>(type: ComponentClass<P, any, any> | string, props: P, ...children: ReactNode[]): ReactElement<P>;
createFactory<P>(type: ComponentClass<P, any, any> | string): ComponentFactory<P>;
render<P, S>(element: ReactClassicElement<P>, container: Element, callback?: () => any): ClassicComponent<P, S, any>;
render<P, S>(element: ReactElement<P>, container: Element, callback?: () => any): Component<P, S, any>;
unmountComponentAtNode(container: Element): boolean;
renderToString(element: ReactElement<any>): string;
+1
View File
@@ -95,6 +95,7 @@ declare module "restify" {
listen(... args: any[]): any;
close(... args: any[]): any;
pre(routeCallBack: RequestHandler): any;
server: http.Server;
}
+26
View File
@@ -85,8 +85,34 @@ shell.ln("-sf", "file", "existing");
var testPath = shell.env["path"];
import child = require("child_process");
var version = shell.exec("node --version").output;
var version2 = <shell.ExecOutputReturnValue>shell.exec("node --version", { async: false });
var output = version2.output;
var asyncVersion3 = <child.ChildProcess>shell.exec("node --version", { async: true });
var pid = asyncVersion3.pid;
shell.exec("node --version", { silent: true }, function (code, output) {
var version = output;
});
shell.exec("node --version", { silent: true, async: true }, function (code, output) {
var version = output;
});
shell.exec("node --version", function (code, output) {
var version = output;
});
shell.exec("node --version", function (code: number) {
var num: number = code;
});
var childProc = shell.exec("node --version", function (code: number) {
var num: number = code;
});
var pid = childProc.pid;
shell.chmod(755, "/Users/brandon");
shell.chmod("755", "/Users/brandon"); // same as above
shell.chmod("u+x", "/Users/brandon");
+36 -21
View File
@@ -8,6 +8,8 @@
declare module "shelljs"
{
import child = require("child_process");
/**
* Changes to directory dir for the duration of the script
* @param {string} dir Directory to change in.
@@ -434,31 +436,44 @@ declare module "shelljs"
* 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.
* @param {string} command The command to execute.
* @return {ExecOutputReturnValue} Returns an object containing the return code and output as string.
*/
export function exec(command: string): ExecReturnValue;
export function exec(command: string): ExecOutputReturnValue;
/**
* Executes the given command synchronously.
* @param {string} command The command to execute.
* @param {ExecOptions} options Silence and synchronous options.
* @return {ExecOutputReturnValue | child.ChildProcess} Returns an object containing the return code and output as string, or if {async:true} was passed, a ChildProcess.
*/
export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildProcess;
/**
* Executes the given command synchronously.
* @param {string} command The command to execute.
* @param {ExecOptions} options Silence and synchronous options.
* @param {ExecCallback} callback Receives code and output asynchronously.
*/
export function exec(command: string, options: ExecOptions, callback: ExecCallback): child.ChildProcess;
/**
* Executes the given command synchronously.
* @param {string} command The command to execute.
* @param {ExecCallback} callback Receives code and output asynchronously.
*/
export function exec(command: string, callback: ExecCallback): child.ChildProcess;
interface ExecReturnValue
export interface ExecCallback {
(code: number, output: string): any;
}
export interface ExecOptions {
silent?: boolean;
async?: boolean;
}
export interface ExecOutputReturnValue
{
code: number;
output: string;
+7
View File
@@ -30,6 +30,13 @@ declare module WebCola{
stop(): void;
}
interface Constraint {
axis: string;
gap: number;
left: number;
right: number;
}
interface FlowLayout{
axis: string;
minSeparation?: number;
+153
View File
@@ -0,0 +1,153 @@
///<reference path="webspeechapi.d.ts" />
/*
Examples from the spec:
https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#examples-recognition
*/
// 6.1 Speech Recognition Examples
// Example 1
declare var q: HTMLInputElement;
() => {
var recognition = new SpeechRecognition();
recognition.onresult = function (event) {
if (event.results.length > 0) {
q.value = event.results[0][0].transcript;
q.form.submit();
}
}
}
// Example 2
declare var select: HTMLSelectElement;
() => {
var recognition = new SpeechRecognition();
recognition.maxAlternatives = 10;
recognition.onresult = function (event) {
if (event.results.length > 0) {
var result = event.results[0];
for (var i = 0; i < result.length; ++i) {
var text = result[i].transcript;
select.options[i] = new Option(text, text);
}
}
}
function start() {
select.options.length = 0;
recognition.start();
}
}
// Example 3
/*
This example has some changes from the one in spec.
`var i = resultIndex` -> `var i = event.resultIndex` (Recorded as Errata 16)
`event.results.final` -> `event.results[i].isFinal` (Recorded as Errata 02)
*/
declare var textarea: HTMLTextAreaElement;
declare var button: HTMLButtonElement;
() => {
var recognizing: boolean;
var recognition = new SpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset;
recognition.onresult = function (event) {
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
textarea.value += event.results[i][0].transcript;
}
}
}
function reset() {
recognizing = false;
button.innerHTML = "Click to Speak";
}
function toggleStartStop() {
if (recognizing) {
recognition.stop();
reset();
} else {
recognition.start();
recognizing = true;
button.innerHTML = "Click to Stop";
}
}
}
// Example 4
/*
This example has a change from the one in spec.
`recognition.interim = true;` -> `recognition.interimResults = true;` (Recorded as Errata 01)
`event.results[i].final` -> `event.results[i].isFinal` (Recorded as Errata 02)
*/
declare var button: HTMLButtonElement;
declare var final_span: HTMLSpanElement;
declare var interim_span: HTMLSpanElement;
() => {
var recognizing: boolean;
var recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
reset();
recognition.onend = reset;
recognition.onresult = function (event) {
var final = "";
var interim = "";
for (var i = 0; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final += event.results[i][0].transcript;
} else {
interim += event.results[i][0].transcript;
}
}
final_span.innerHTML = final;
interim_span.innerHTML = interim;
}
function reset() {
recognizing = false;
button.innerHTML = "Click to Speak";
}
function toggleStartStop() {
if (recognizing) {
recognition.stop();
reset();
} else {
recognition.start();
recognizing = true;
button.innerHTML = "Click to Stop";
final_span.innerHTML = "";
interim_span.innerHTML = "";
}
}
}
// 6.2 Speech Synthesis Examples
// Example 1
/*
This example has a change from the one in spec.
`SpeechSynthesisUtterance('Hello World')` -> `new SpeechSynthesisUtterance('Hello World')` (Recorded as Errata 09)
*/
() => {
speechSynthesis.speak(new SpeechSynthesisUtterance('Hello World'));
}
//Example 2
() => {
var u = new SpeechSynthesisUtterance();
u.text = 'Hello World';
u.lang = 'en-US';
u.rate = 1.2;
u.onend = function (event) { alert('Finished in ' + event.elapsedTime + ' seconds.'); }
speechSynthesis.speak(u);
}
+164
View File
@@ -0,0 +1,164 @@
// Type definitions for Web Speech API
// Project: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
// Definitions by: SaschaNaz <https://github.com/saschanaz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Spec version: 19 October 2012
// Errata version: 6 June 2014
// Corrected unofficial spec version: 6 June 2014
interface SpeechRecognition extends EventTarget {
grammars: SpeechGrammarList;
lang: string;
continuous: boolean;
interimResults: boolean;
maxAlternatives: number;
serviceURI: string;
start(): void;
stop(): void;
abort(): void;
onaudiostart: (ev: Event) => any;
onsoundstart: (ev: Event) => any;
onspeechstart: (ev: Event) => any;
onspeechend: (ev: Event) => any;
onsoundend: (ev: Event) => any;
onresult: (ev: SpeechRecognitionEvent) => any;
onnomatch: (ev: SpeechRecognitionEvent) => any;
onerror: (ev: SpeechRecognitionError) => any;
onstart: (ev: Event) => any;
onend: (ev: Event) => any;
}
interface SpeechRecognitionStatic {
prototype: SpeechRecognition;
new (): SpeechRecognition;
}
declare var SpeechRecognition: SpeechRecognitionStatic;
declare var webkitSpeechRecognition: SpeechRecognitionStatic;
interface SpeechRecognitionError extends Event {
error: string;
message: string;
}
interface SpeechRecognitionAlternative {
transcript: string;
confidence: number;
}
interface SpeechRecognitionResult {
length: number;
item(index: number): SpeechRecognitionAlternative;
[index: number]: SpeechRecognitionAlternative;
/* Errata 02 */
isFinal: boolean;
}
interface SpeechRecognitionResultList {
length: number;
item(index: number): SpeechRecognitionResult;
[index: number]: SpeechRecognitionResult;
}
interface SpeechRecognitionEvent extends Event {
resultIndex: number;
results: SpeechRecognitionResultList;
interpretation: any;
emma: Document;
}
interface SpeechGrammar {
src: string;
weight: number;
}
interface SpeechGrammarStatic {
prototype: SpeechGrammar;
new (): SpeechGrammar;
}
declare var SpeechGrammar: SpeechGrammarStatic;
declare var webkitSpeechGrammar: SpeechGrammarStatic;
interface SpeechGrammarList {
length: number;
item(index: number): SpeechGrammar;
[index: number]: SpeechGrammar;
addFromURI(src: string, weight: number): void;
addFromString(string: string, weight: number): void;
}
interface SpeechGrammarListStatic {
prototype: SpeechGrammarList;
new (): SpeechGrammarList;
}
declare var SpeechGrammarList: SpeechGrammarListStatic;
declare var webkitSpeechGrammarList: SpeechGrammarListStatic;
/* Errata 08 */
interface SpeechSynthesis extends EventTarget {
pending: boolean;
speaking: boolean;
paused: boolean;
/* Errata 11 */
onvoiceschanged: (ev: Event) => any;
speak(utterance: SpeechSynthesisUtterance): void;
cancel(): void;
pause(): void;
resume(): void;
/* Errata 05 */
getVoices(): SpeechSynthesisVoice[];
}
interface SpeechSynthesisGetter {
speechSynthesis: SpeechSynthesis;
}
interface Window extends SpeechSynthesisGetter {
}
declare var speechSynthesis: SpeechSynthesis;
interface SpeechSynthesisUtterance extends EventTarget {
text: string;
lang: string;
/* Errata 07 */
voice: SpeechSynthesisVoice;
volume: number;
rate: number;
pitch: number;
onstart: (ev: SpeechSynthesisEvent) => any;
onend: (ev: SpeechSynthesisEvent) => any;
/* Errata 12 */
onerror: (ev: SpeechSynthesisErrorEvent) => any;
onpause: (ev: SpeechSynthesisEvent) => any;
onresume: (ev: SpeechSynthesisEvent) => any;
onmark: (ev: SpeechSynthesisEvent) => any;
onboundary: (ev: SpeechSynthesisEvent) => any;
}
interface SpeechSynthesisUtteranceStatic {
prototype: SpeechSynthesisUtterance;
new (): SpeechSynthesisUtterance;
new (text: string): SpeechSynthesisUtterance;
}
declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic;
interface SpeechSynthesisEvent extends Event {
/* Errata 08 */
utterance: SpeechSynthesisUtterance;
charIndex: number;
elapsedTime: number;
name: string;
}
/* Errata 12 */
interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent {
error: string;
}
interface SpeechSynthesisVoice {
voiceURI: string;
name: string;
lang: string;
localService: boolean;
default: boolean;
}