diff --git a/.travis.yml b/.travis.yml index 0bad26ece..f99663162 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - "0.10" + - "iojs-v2" sudo: false diff --git a/acl/acl-mongodbBackend-tests.ts b/acl/acl-mongodbBackend-tests.ts index 31411b65c..01c9af908 100644 --- a/acl/acl-mongodbBackend-tests.ts +++ b/acl/acl-mongodbBackend-tests.ts @@ -1,4 +1,4 @@ -/// +/// // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); @@ -14,4 +14,3 @@ acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter acl.allow('member', 'blogs', ['edit','view', 'delete']); - diff --git a/acl/acl-mongodbBackend.d.ts b/acl/acl-mongodbBackend.d.ts deleted file mode 100644 index 8dbfb7e90..000000000 --- a/acl/acl-mongodbBackend.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Type definitions for node_acl 0.4.7 -// Project: https://github.com/optimalbits/node_acl -// Definitions by: Qubo -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "acl" { - import mongo = require('mongodb'); - - interface AclStatic { - mongodbBackend: MongodbBackendStatic; - } - - interface MongodbBackend extends Backend { } - interface MongodbBackendStatic { - new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new(db: mongo.Db, prefix: string): MongodbBackend; - new(db: mongo.Db): MongodbBackend; - } -} diff --git a/acl/acl-redisBackend-test.ts b/acl/acl-redisBackend-test.ts index e1bf29af4..273aeab3b 100644 --- a/acl/acl-redisBackend-test.ts +++ b/acl/acl-redisBackend-test.ts @@ -1,4 +1,4 @@ -/// +/// // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); diff --git a/acl/acl-redisBackend.d.ts b/acl/acl-redisBackend.d.ts deleted file mode 100644 index e199f8b81..000000000 --- a/acl/acl-redisBackend.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Type definitions for node_acl 0.4.7 -// Project: https://github.com/optimalbits/node_acl -// Definitions by: Qubo -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "acl" { - import redis = require('redis'); - - interface AclStatic { - redisBackend: RedisBackendStatic; - } - - interface RedisBackend extends Backend { } - interface RedisBackendStatic { - new(redis: redis.RedisClient, prefix: string): RedisBackend; - new(redis: redis.RedisClient): RedisBackend; - } -} diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 5d0498fed..57e85d9d5 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -6,6 +6,9 @@ /// /// +/// +/// + declare module "acl" { import http = require('http'); import Promise = require("bluebird"); @@ -115,6 +118,33 @@ declare module "acl" { end: () => void; } + // for redis backend + import redis = require('redis'); + + interface AclStatic { + redisBackend: RedisBackendStatic; + } + + interface RedisBackend extends Backend { } + interface RedisBackendStatic { + new(redis: redis.RedisClient, prefix: string): RedisBackend; + new(redis: redis.RedisClient): RedisBackend; + } + + // for mongodb backend + import mongo = require('mongodb'); + + interface AclStatic { + mongodbBackend: MongodbBackendStatic; + } + + interface MongodbBackend extends Backend { } + interface MongodbBackendStatic { + new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; + new(db: mongo.Db, prefix: string): MongodbBackend; + new(db: mongo.Db): MongodbBackend; + } + var _: AclStatic; export = _; } diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index cefc35b99..2b200bb37 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -9,10 +9,6 @@ interface Window { token: string; } -interface Location { - origin: string; -} - /** This is the interface for the main Auth0 client. */ interface Auth0Static { diff --git a/baconjs/baconjs-tests.ts b/baconjs/baconjs-tests.ts new file mode 100644 index 000000000..e542ef1c9 --- /dev/null +++ b/baconjs/baconjs-tests.ts @@ -0,0 +1,386 @@ +/// + +function CreatingStreams() { + $("#my-div").asEventStream("click"); + $("#my-div").asEventStream("click", ".more-specific-selector"); + $("#my-div").asEventStream("click", (event, args) => args[0]); + $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); + + Bacon.fromPromise($.ajax("https://baconjs.github.io/")); + Bacon.fromPromise(Promise.resolve(1)); + + Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); + Bacon.fromPromise(Promise.resolve(1), false); + + Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { + return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + }); + Bacon.fromPromise(Promise.resolve(1), false, n => { + return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + }); + + Bacon.fromEvent(document.body, "click").onValue(() => { + alert("Bacon!"); + }); + Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { + alert("Bacon!"); + }); + Bacon.fromEvent(process.stdin, "readable", () => { + alert("Bacon!"); + }); + + // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. + Bacon.fromCallback(callback => { + setTimeout(() => { + callback("Bacon!"); + }, 1000); + }); + + // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": + Bacon.fromCallback((a, b, callback) => { + callback(a + " " + b); + }, Bacon.constant("bacon"), "rules").log(); + + { + var fs = require("fs"), + read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); + read.onError(error => { + console.log("Reading failed: " + error); + }); + read.onValue(value => { + console.log("Read contents: " + value); + }); + } + + Bacon.once(new Bacon.Error("fail")); + + // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: + Bacon.fromArray([1, new Bacon.Error("")]); + + Bacon.repeatedly(10, [1, 2, 3]); + + // The following will produce values `0,1,2`. + Bacon.repeat(i => { + if (i < 3) { + return Bacon.once(i); + } else { + return false; + } + }).log(); + + { + var stream = Bacon.fromBinder(sink => { + sink("first value"); + sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); + sink(new Bacon.Next(() => { + return "This one will be evaluated lazily" + })); + sink(new Bacon.Error("oops, an error")); + sink(new Bacon.End()); + return () => { + // unsub functionality here, this one's a no-op + }; + }); + stream.log(); + } + + new Bacon.Next("value"); + new Bacon.Next(() => "value"); +} + +function CommonMethodsInEventStreamsAndProperties() { + // Converting strings to integers, skipping empty values: + Bacon.once("").flatMap(text => { + return text != "" ? parseInt(text) : Bacon.never(); + }); + + Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); + + Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); + + // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: + Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); + // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: + Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); + + { + var x = Bacon.fromArray([1, 2]), y = Bacon.fromArray([3, 4]); + x.zip(y, (x, y) => x + y); + } + + { + var stream = Bacon.fromArray([1, 2]); + stream.log("New event in myStream"); + stream.log(); + } + + Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { + if (event.hasValue()) { + // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> + return [sum + event.value(), []]; + } + else if (event.isEnd()) { + return [undefined, [new Bacon.Next(sum), event]]; + } + else { + return [sum, [event]]; + } + }); + + { + var property = Bacon.fromArray([1, 2, 3]).toProperty(), + who = Bacon.fromArray(["A", "B", "C"]).toProperty(); + property.decode({1: "mike", 2: who}); + + property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); + } + + { + // This is handy for keeping track whether we are currently awaiting an AJAX response: + var ajaxRequest = >{}, + ajaxResponse = >{}, + showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); + } + + Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + if (event.hasValue() && event.value() < 0) { + this.push(new Bacon.Error("Value below zero")); + return this.push(new Bacon.End()); + } else { + return this.push(event); + } + }); + + { + var src = Bacon.once(1), + obs = src.map(x => -x); + console.log(obs.toString()); // > "Bacon.once(1).map(function)" + + obs.withDescription(src, "times", -1); + console.log(obs.toString()); // > "Bacon.once(1).times(-1)" + } + + { + // Calculator for grouped consecutive values until group is cancelled: + var events = [ + {id: 1, type: "add", val: 3}, + {id: 2, type: "add", val: -1}, + {id: 1, type: "add", val: 2}, + {id: 2, type: "cancel"}, + {id: 3, type: "add", val: 2}, + {id: 3, type: "cancel"}, + {id: 1, type: "add", val: 1}, + {id: 1, type: "add", val: 2}, + {id: 1, type: "cancel"} + ], + keyF = (event:{id:number}) => event.id, + limitF = (groupedStream:Bacon.EventStream) => { + var cancel = groupedStream.filter(x => x.type === "cancel").take(1), + adds = groupedStream.filter(x => x.type === "add"); + return adds.takeUntil(cancel).map(x => x.val); + }; + + Bacon.sequentially(2, events) + .groupBy(keyF, limitF) + .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) + .onValue(sum => { + console.log(sum); // returns [-1, 2, 8] in an order + }); + } +} + +function EventStream() { + // This creates the stream which doesn't produce any events and never ends: + Bacon.interval(1e1, 0).last(); + + Bacon.fromArray([1, 2, 2, 1]) + .skipDuplicates().log(); // > returns [1, 2, 1] in an order + + // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: + Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); + + // Here's an equivalent to `stream.bufferWithTime(10)`: + { + var stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); + stream.bufferWithTime(f => { + setTimeout(f, 10); + }); + } + + // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. + Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); +} + +function Property() { + // This creates the property which doesn't produce any events and never ends: + Bacon.interval(1e1, 0).toProperty().last(); + + { + var property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); + // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: + property.assign($("#my-button"), "attr", "disabled"); + + // A simpler example would be to toggle the visibility of an element based on a Property: + property.assign($("#my-button"), "toggle"); + } + + Bacon.fromArray([1, 2, 2, 1]).toProperty() + .skipDuplicates().log(); // > returns [1, 2, 1] in an order +} + +function CombiningMultipleStreamsAndProperties() { + { + var property = Bacon.constant(1), + stream = Bacon.once(2), + constant = 3; + Bacon.combineAsArray(property, stream, constant) + .log(); // > returns [1, 2, 3] + } + + { + // To calculate the current sum of three numeric Properties, you can do: + var property = Bacon.constant(1), + stream = Bacon.once(2), + constant = 3; + // NOTE: had to explicitly specify the typing for `x:number, y:number, z:number` + Bacon.combineWith((x:number, y:number, z:number) => x + y + z, property, stream, constant); + } + + { + // Assuming you've got streams or properties named `password`, `username`, `firstname` and `lastname`, you can do: + var password = Bacon.constant("easy"), + username = Bacon.constant("juha"), + firstname = Bacon.constant("juha"), + lastname = Bacon.constant("paananen"), + // NOTE: you should provide `combineTemplate` typing explicitly! + loginInfo = Bacon.combineTemplate({ + magicNumber: 3, + userid: username, + passwd: password, + name: {first: firstname, last: lastname} + }).onValue(loginInfo => { + // and your new `loginInfo` property will combine values from all these streams using that template, whenever any of the streams/properties get a new value. It would yield a value: + console.log("`loginInfo` expected", { + magicNumber: 3, + userid: "juha", + passwd: "easy", + name: {first: "juha", last: "paananen"} + }); + console.log("`loginInfo` actual", loginInfo); + }); + + // Note that all Bacon.combine* methods produce a `Property` instead of an `EventStream`. If you need the result as an `EventStream` you might want to use `property.changes()`: + Bacon.combineWith((firstname, lastname) => `${firstname} ${lastname}`, firstname, lastname).changes(); + } + + { + var x = Bacon.fromArray([1, 2, 3]), + y = Bacon.fromArray([10, 20, 30]), + z = Bacon.fromArray([100, 200, 300]); + Bacon.zipAsArray(x, y, z) + .log(); // > returns values `[1, 10, 100]`, `[2, 20, 200]` and `[3, 30, 300]` + } + + // The following example would log the number 3. + // NOTE: had to explicitly specify the typing for `a:number, b:number` + Bacon.onValues(Bacon.constant(1), Bacon.constant(2), (a:number, b:number) => { + console.log(a + b); + }); +} + +function $Event() { + new Bacon.Next("value"); + new Bacon.Next(() => "value"); +} + +function Errors() { + // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: + // NOTE: had to explicitly specify the typing for `flatMap` + Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + return x > 2 ? new Bacon.Error("too big") : x; + }); + + // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: + Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { + var isNonCriticalError = (error:string) => Math.random() < .5, + handleNonCriticalError = (error:string) => 42; + return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); + }); + + // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: + Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + var dangerousFunction = (x:number) => { + throw new Error("dangerous function!"); + }; + try { + return dangerousFunction(x); + } catch (e) { + return new Bacon.Error(e); + } + }); + + Bacon.once("https://baconjs.github.io/").flatMap(url => { + // `ajaxCall` gives `Error`s on network or server `Error`s. + var ajaxCall = (url:string) => { + return Bacon.fromPromise($.ajax(url)); + }; + return Bacon.retry({ + source: () => ajaxCall(url), + retries: 5, + isRetryable: (error:JQueryXHR) => error.status !== 404, + delay: context => 100 // Just use the same delay always + }); + }); +} + +function JoinPatterns() { + { + // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + var tick = Bacon.interval(1e2, 0), + keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + handleTick = (_:number) => `timestamp: NONE`, + handleKeyEvent = (timestamp:number) => `timestamp: ${timestamp}`; + Bacon.when( + [tick, keyEvent], (_:number, timestamp:number) => handleKeyEvent(timestamp), + [tick], handleTick + ); + // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + } + + { + // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + var a = Bacon.once("a"), + b = Bacon.once("b"), + c = Bacon.once("c"), + f = (a:string, b:string, c:string) => `a = ${a}; b = ${b}; c = ${c}.`; + Bacon.zipWith(f, a, b, c); + Bacon.when([a, b, c], f); + } + { + // The inputs to `Bacon.update` are defined like this: + var initial = 0, + x = Bacon.interval(1e3, 1), + y = Bacon.interval(2e3, 1), + z = Bacon.interval(1.5e3, 1); + // NOTE: had to explicitly specify the typing for `previous:number` + Bacon.update(initial, + [x, y, z], (previous:number, x:number, y:number, z:number) => previous + x + y + z, + [x, y], (previous:number, x:number, y:number) => previous + x + y + ); + // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + } + { + // Here's a simple gaming example: + var scoreMultiplier = Bacon.constant(1), + hitUfo = new Bacon.Bus(), + hitMotherShip = new Bacon.Bus(), + score = Bacon.update(0, + [hitUfo, scoreMultiplier], (score:number, _:number, multiplier:number) => score + 100 * multiplier, + [hitMotherShip], (score:number, _:number) => score + 2000 + ); + // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + } +} diff --git a/baconjs/baconjs.d.ts b/baconjs/baconjs.d.ts new file mode 100644 index 000000000..0e3f77c12 --- /dev/null +++ b/baconjs/baconjs.d.ts @@ -0,0 +1,2746 @@ +// Type definitions for Bacon.js 0.7.0 +// Project: https://baconjs.github.io/ +// Definitions by: Alexander Matsievsky +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +interface JQuery { + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. + * @param {string} eventName + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click"); + */ + asEventStream(eventName:string):Bacon.EventStream; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector`. + * @param {string} eventName + * @param {string} selector + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector"); + */ + asEventStream(eventName:string, selector:string):Bacon.EventStream; + + /** + * @callback JQuery#asEventStream1~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {JQuery#asEventStream1~f} f + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", (event, args) => args[0]); + */ + asEventStream(eventName:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; + + /** + * @callback JQuery#asEventStream2~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector` and a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {string} selector + * @param {JQuery#asEventStream2~f} f + * @returns {Bacon.EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); + */ + asEventStream(eventName:string, selector:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; +} + +/** @module Bacon */ +declare module Bacon { + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. + * @param {Promise|JQueryXHR} promise + * @param {boolean} [abort] + * @returns {EventStream} + * @example + * Bacon.fromPromise($.ajax("https://baconjs.github.io/")); + * Bacon.fromPromise(Promise.resolve(1)); + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); + * Bacon.fromPromise(Promise.resolve(1), false); + */ + function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; + + /** + * @callback Bacon.fromPromise~eventTransformer + * @param {A} value + * @returns {(Initial|Next|End|Error)[]} + */ + /** + * @function Bacon.fromPromise + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. + * @param {Promise|JQueryXHR} promise + * @param {boolean} abort + * @param {Bacon.fromPromise~eventTransformer} eventTransformer + * @returns {EventStream} + * @example + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + * }); + * Bacon.fromPromise(Promise.resolve(1), false, n => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + * }); + */ + function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. + * @param {EventTarget|NodeJS.EventEmitter} target + * @param {string} eventName + * @returns {EventStream} + * @example + * Bacon.fromEvent(document.body, "click").onValue(() => { + * alert("Bacon!"); + * }); + * Bacon.fromEvent(process.stdin, "readable", () => { + * alert("Bacon!"); + * }); + */ + function fromEvent(target:EventTarget|NodeJS.EventEmitter, eventName:string):EventStream; + + /** + * @callback Bacon.fromEvent~eventTransformer + * @param {A} event + * @returns {B} + */ + /** + * @function Bacon.fromEvent + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. + * @param {EventTarget|NodeJS.EventEmitter} target + * @param {string} eventName + * @param {Bacon.fromEvent~eventTransformer} eventTransformer + * @returns {EventStream} + * @example + * Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { + * alert("Bacon!"); + * }); + */ + function fromEvent(target:EventTarget|NodeJS.EventEmitter, eventName:string, eventTransformer:(event:A) => B):EventStream; + + /** + * @callback Bacon.fromCallback1~f + * @param {Bacon.fromCallback1~callback} callback + * @returns {void} + */ + /** + * @callback Bacon.fromCallback1~callback + * @param {...*} args + * @returns {void} + */ + /** + * @function Bacon.fromCallback1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback1~f} f + * @returns {EventStream} + * @example + * // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. + * Bacon.fromCallback(callback => { + * setTimeout(() => { + * callback("Bacon!"); + * }, 1000); + * }); + */ + function fromCallback(f:(callback:(...args:any[]) => void) => void):EventStream; + + /** + * @callback Bacon.fromCallback2~f + * @param {...*} args + * @returns {void} + */ + /** + * @function Bacon.fromCallback2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback2~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": + * Bacon.fromCallback((a, b, callback) => { + * callback(a + " " + b); + * }, Bacon.constant("bacon"), "rules").log(); + */ + function fromCallback(f:(...args:any[]) => void, ...args:any[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. The function is supposed to call its callback just once. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromNodeCallback~f + * @param {Bacon.fromNodeCallback~callback} callback + * @returns {void} + */ + /** + * @callback Bacon.fromNodeCallback~callback + * @param {E} error + * @param {A} data + * @returns {void} + */ + /** + * @function Bacon.fromNodeCallback + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a Node.js `callback`: callback(error, data), where error is `null` if everything is fine. The function is supposed to call its callback just once. + * @param {Bacon.fromNodeCallback~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * { + * let fs = require("fs"), + * read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); + * read.onError(error => { + * console.log("Reading failed: " + error); + * }); + * read.onValue(value => { + * console.log("Read contents: " + value); + * }); + * } + */ + function fromNodeCallback(f:(callback:(error:E, data:A) => void) => void, ...args:any[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromNodeCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromPoll~f + * @returns {Next|End} + */ + /** + * @function Bacon.fromPoll + * @description Polls given function `f` with given `interval`. Function should return events: either [Next]{@link Bacon.Next} or [End]{@link Bacon.End}. Polling occurs only when there are subscribers to the stream. Polling ends permanently when `f` returns [End]{@link Bacon.End}. + * @param {number} interval + * @param {Bacon.fromPoll~f} f + * @returns {EventStream} + */ + function fromPoll(interval:number, f:() => Next|End):EventStream; + + /** + * @function Bacon.once + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given single `value` for the first subscriber. The stream will end immediately after this value. You can also send an [Error]{@link Bacon.Error} event instead of a `value`. + * @param {A|Error} value + * @returns {EventStream} + * @example + * Bacon.once(new Bacon.Error("fail")); + */ + function once(value:A|Error):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given series of `values` (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [Error]{@link Bacon.Error} events, or any combination of pure values and error events. + * @param {(A|Error)[]} values + * @returns {EventStream} + * @example + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function fromArray(values:(A|Error)[]):EventStream; + + /** + * @function + * @description Repeats the single `value` indefinitely with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A} value + * @returns {EventStream} + */ + function interval(interval:number, value:A):EventStream; + + /** + * @function + * @description Creates a [EventStream]{@link Bacon.EventStream} containing given `values` (given as array) with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + */ + function sequentially(interval:number, values:A[]):EventStream; + + /** + * @function + * @description Repeats given `values` indefinitely with then given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + * @example + * // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function repeatedly(interval:number, values:A[]):EventStream; + + /** + * @callback Bacon.repeat~f + * @param {number} iteration + * @returns {boolean|Observable} + */ + /** + * @function Bacon.repeat + * @description Calls generator function `f` which is expected to return an [Observable]{@link Bacon.Observable}. The returned [EventStream]{@link Bacon.EventStream} contains values and errors from the spawned observable. When the spawned Observable ends, the generator `f` is called again to spawn a new Observable. This is repeated until the generator `f` returns a falsy value (such as `undefined` or `false`). The generator `f` is called with one argument — `iteration` number starting from `0`. + * @param {Bacon.repeat~f} f + * @returns {EventStream} + * @example + * // The following will produce values `0,1,2`. + * Bacon.repeat(i => { + * if (i < 3) { + * return Bacon.once(i); + * } else { + * return false; + * } + * }).log(); + */ + function repeat(f:(iteration:number) => boolean|Observable):EventStream; + + /** + * @function Bacon.never + * @description Creates an [EventStream]{@link Bacon.EventStream} that immediately ends. + * @returns {EventStream} + */ + function never():EventStream; + + /** + * @function + * @description Creates a single-element [EventStream]{@link Bacon.EventStream} that produces given `value` after a given `delay` (in milliseconds). + * @param {number} delay + * @param {A} value + * @returns {EventStream} + */ + function later(delay:number, value:A):EventStream; + + /** + * @function + * @description Creates a constant [Property]{@link Bacon.Property} with value `x`. + * @param {A} x + * @returns {Property} + */ + function constant(x:A):Property; + + /** + * @callback Bacon.fromBinder~subscribe + * @param {Bacon.fromBinder~sink} sink + * @returns {Bacon.fromBinder~unsubscribe} + */ + /** + * @callback Bacon.fromBinder~sink + * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value + * @returns {void} + */ + /** + * @callback Bacon.fromBinder~unsubscribe + * @returns {void} + */ + /** + * @function Bacon.fromBinder + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given [subscribe]{@link Bacon.fromBinder~subscribe} function. The parameter `subscribe` is a function that accepts a [sink]{@link Bacon.fromBinder~sink} which is a function that your `subscribe` function can "push" events to. You can push: a plain value, like `"first value"`; an [Event]{@link Bacon.Event} object including [Error]{@link Bacon.Error} (wraps an error) and [End]{@link Bacon.End} (indicates stream end); an array of event objects at once. The `subscribe` function must return a function. Let's call that function [unsubscribe]{@link Bacon.fromBinder~unsubscribe}. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the `subscribe` function reserved. The `sink` function may return [noMore]{@link Bacon.noMore} (as well as [more]{@link Bacon.more} or any other value). If it returns `noMore`, no further events will be consumed by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g., by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored, but doing so can increase performance in rare cases. The EventStream will wrap your `subscribe` function so that it will only be called when the first stream listener is added, and the `unsubscribe` function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the `subscribe` function. + * @param {Bacon.fromBinder~subscribe} subscribe + * @returns {EventStream} + * @example + * let stream = Bacon.fromBinder(sink => { + * sink("first value"); + * sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); + * sink(new Bacon.Next(() => { + * return "This one will be evaluated lazily" + * })); + * sink(new Bacon.Error("oops, an error")); + * sink(new Bacon.End()); + * return () => { + * // unsub functionality here, this one's a no-op + * }; + * }); + * stream.log(); + */ + function fromBinder(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; + + /** + * @interface + * @see Bacon.more + */ + interface More { + } + /** + * @property more + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var more:More; + + /** + * @interface + * @see Bacon.noMore + */ + interface NoMore { + } + /** + * @property noMore + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var noMore:NoMore; + + /** + * @class Observable + * @description A superclass for [EventStream]{@link Bacon.EventStream} and [Property]{@link Bacon.Property}. + * */ + interface Observable { + /** + * @callback Observable#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Observable#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onValue + * @description Subscribes a given handler function `f` to the [Observable]{@link Bacon.Observable}. Function will be called for each new value. This is the simplest way to assign a side-effect to an Observable. The difference to the [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe} methods is that the actual stream `value`s are received, instead of [Event]{@link Bacon.Event} objects. [EventStream.onValue]{@link Bacon.EventStream#onValue} and [Property.onValue]{@link Bacon.Property#onValue} behave similarly, except that the latter also pushes the initial value of the Property, in case there is one. + * @param {Observable#onValue~f} f + * @returns {Observable#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Observable#onError~f + * @param {E} error + * @returns {void} + */ + /** + * @callback Observable#onError~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onError + * @description Subscribes a given handler function `f` to [Error]{@link Bacon.Error} events. The function `f` will be called for each error in the [Observable]{@link Bacon.Observable}. + * @param {Observable#onError~f} f + * @returns {Observable#onError~unsubscribe} + */ + onError(f:(error:E) => void):() => void; + + /** + * @callback Observable#onEnd~f + * @returns {void} + */ + /** + * @callback Observable#onEnd~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onEnd + * @description Subscribes a given handler function `f` to [End]{@link Bacon.End} event. The function `f` will be called when the [Observable]{@link Bacon.Observable} ends. Just like [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Observable#onEnd~f} f + * @returns {Observable#onEnd~unsubscribe} + */ + onEnd(f:() => void):() => void; + + /** + * @callback Observable#toPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#toPromise + * @description Returns a Promise which will be resolved with the last event coming from an [Observable]{@link Bacon.Observable}. The global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. Use a shim if you need to support legacy browsers or platforms. + * @param {Observable#toPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + toPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @callback Observable#firstToPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#firstToPromise + * @description Returns a Promise which will be resolved with the first event coming from an [Observable]{@link Bacon.Observable}. Like [Observable.toPromise]{@link Bacon.Observable#toPromise}, the global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. + * @param {Observable#firstToPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + firstToPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @method + * @description Throttles the [Observable]{@link Bacon.Observable} using a buffer so that at most one value event in `minimumInteval` is issued. Unlike [EventStream.throttle]{@link Bacon.EventStream#throttle} and [Property.throttle]{@link Bacon.Property#throttle}, it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per `minimumInterval`. + * @param {number} minimumInterval + * @returns {EventStream} + */ + bufferingThrottle(minimumInterval:number):EventStream; + + /** + * @callback Observable#flatMap~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMap + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMap]{@link Bacon.Observable#flatMap} is always an EventStream. The "Function Construction rules" apply here. `flatMap` can be used conveniently with [Bacon.once]{@link Bacon.once} and [Bacon.never]{@link Bacon.never} for converting and filtering at the same time, including only some of the results. + * @param {Observable#flatMap~f} f + * @returns {EventStream} + * @example + * // Converting strings to integers, skipping empty values: + * Bacon.once("").flatMap(text => { + * return text != "" ? parseInt(text) : Bacon.never(); + * }); + */ + flatMap(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapLatest~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapLatest + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, but instead of including events from all spawned streams, only includes them from the latest spawned stream into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapLatest]{@link Bacon.Observable#flatMapLatest} is always an EventStream. + * @param {Observable#flatMapLatest~f} f + * @returns {EventStream} + */ + flatMapLatest(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapFirst~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapFirst + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f` only if the previously spawned stream has ended, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapFirst]{@link Bacon.Observable#flatMapFirst} is always an EventStream. + * @param {Observable#flatMapFirst~f} f + * @returns {EventStream} + */ + flatMapFirst(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapError~f + * @param {E} error + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapError + * @description For each [Error]{@link Bacon.Error} event in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapError]{@link Bacon.Observable#flatMapError} is always an EventStream. + * @param {Observable#flatMapError~f} f + * @returns {EventStream} + */ + flatMapError(f:(error:E) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapWithConcurrencyLimit~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapWithConcurrencyLimit + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events by `limit` amount. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. [flatMapConcat]{@link Bacon.Observable#flatMapConcat} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(1) (only one input active), and [flatMap]{@link Bacon.Observable#flatMap} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(∞) (all inputs are piped to output). The result of `flatMapWithConcurrencyLimit` is always an EventStream. + * @param {number} limit + * @param {Observable#flatMapWithConcurrencyLimit~f} f + * @returns {EventStream} + */ + flatMapWithConcurrencyLimit(limit:number, f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapConcat~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapConcat + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events to 1. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of `flatMapConcat` is always an EventStream. + * @param {Observable#flatMapConcat~f} f + * @returns {EventStream} + */ + flatMapConcat(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#scan~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#scan + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, resulting to a [Property]{@link Bacon.Property}. For example, you might use zero as `seed` and a "plus" function as the accumulator to create an "integral" Property. When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch: the starting value for `r` depends on whether `p` has an initial value when `scan` is applied. If there's no initial value, this works identically to `[EventStream]{@link Bacon.EventStream}.scan`: the `seed` will be the initial value of `r`. However, if `r` already has a current/initial value `x`, the seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense, because there can only be 1 initial value for a Property at a time. + * @param {B} seed + * @param {Observable#scan~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); + */ + scan(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#fold~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#fold + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#fold~f} f + * @returns {Property} + */ + fold(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#reduce~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#reduce + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#reduce~f} f + * @returns {Property} + */ + reduce(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#diff~f + * @param {A} a + * @param {B} b + * @returns {B} + */ + /** + * @method Observable#diff + * @description Returns a [Property]{@link Bacon.Property} that represents the result of a comparison `f` between the previous and current value of the [Observable]{@link Bacon.Observable}. For the initial value of the Observable, the previous value will be the given `start`. + * @param {A} start + * @param {Observable#diff~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); + */ + diff(start:A, f:(a:A, b:A) => B):Property; + + /** + * @callback Observable#zip~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#zip + * @description Returns an [EventStream]{@link Bacon.EventStream} with elements pair-wise lined up with events from this and the `other` EventStream. A zipped EventStream will publish only when it has a value from each EventStream and will only produce values up to when any single EventStream ends. The given function `f` is used to create the result value from value in the two source EventStream. If no function `f` is given, the values are zipped into an array. Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable. + * @param {EventStream} other + * @param {Observable#zip~f} f + * @returns {EventStream} + * @example + * { + * let x = Bacon.fromArray([1, 2]), + * y = Bacon.fromArray([3, 4]); + * x.zip(y, (x, y) => x + y); + * } + */ + zip(other:EventStream, f:(a:A, b:B) => C):EventStream; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that represents a "sliding window" into the history of the values of the [Observable]{@link Bacon.Observable}. The resulting Property will have a value that is an array containing the last `n` values of the original Observable, where `n` is at most the value of the `max` argument, and at least the value of the `min` argument. If the `min` argument is omitted, there's no lower limit of values. + * @param {number} max + * @param {number} [min] + * @returns {Property} + * @example + * // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); + * // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); + */ + slidingWindow(max:number, min?:number):Property; + + /** + * @callback Observable#combine~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#combine + * @description Combines the latest values of the two [EventStream]{@link Bacon.EventStream}s or [Property]{@link Bacon.Property}s using a two-arg function `f`. The result is a Property. + * @param {Property} property2 + * @param {Observable#combine~f} f + * @returns {Property} + */ + combine(property2:Property, f:(a:A, b:B) => C):Property; + + /** + * @callback Observable#withStateMachine~f + * @param {B} state + * @param {Initial|Next|End|Error} event + * @returns {[B, (Initial|Next|End|Error)[]]} + */ + /** + * @method Observable#withStateMachine + * @description Lets you run a state machine on an [Observable]{@link Bacon.Observable}. Give it an initial state `initState` object and a state transformation function `f` that processes each incoming [Event]{@link Bacon.Event} and returns and array containing the next `state` and an array of output Event's. + * @param {B} initState + * @param {Observable#withStateMachine~f} f + * @returns {EventStream} + * @example + * // Calculate the total sum of all numbers in the stream and output the value on stream end: + * Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { + * if (event.hasValue()) { + * had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> + * return [sum + event.value(), []]; + * } else if (event.isEnd()) { + * return [undefined, [new Bacon.Next(sum), event]]; + * } else { + * return [sum, [event]]; + * } + * }); + */ + withStateMachine(initState:B, f:(state:B, event:Initial|Next|End|Error) => [B, (Initial|Next|End|Error)[]]):EventStream; + + /** + * @method + * @description Decodes input [Observable]{@link Bacon.Observable} using the given `mapping`. Is a bit like a switch-case or the decode function in Oracle SQL. The return value of `decode` is always a [Property]{@link Bacon.Property}. + * @param {Object} mapping + * @returns {Property} + * @example + * let property = Bacon.fromArray([1, 2, 3]).toProperty(), + * who = Bacon.fromArray(["A", "B", "C"]).toProperty(); + * // The following would map the value 1 into the string "mike" and the value 2 into the value of the `who` property: + * property.decode({1: "mike", 2: who}); + * + * // You can compose static and dynamic data quite freely, as in: + * property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); + */ + decode(mapping:Object):Property; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} that indicates whether Observable is awaiting `otherObservable`, i.e. has produced a value after the latest value from `otherObservable`. + * @param {Observable} otherObservable + * @returns {Property} + * @example + * // This is handy for keeping track whether we are currently awaiting an AJAX response: + * let ajaxRequest = >{}, + * ajaxResponse = >{}, + * showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); + */ + awaiting(otherObservable:Observable):Property; + } + + /** + * @class EventStream + * @augments Bacon.Observable + * @description A stream of events. + * */ + interface EventStream extends Observable { + /** + * @callback EventStream#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#map + * @description Maps [EventStream]{@link Bacon.EventStream} values using given function `f`, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {EventStream#map~f} f + * @returns {EventStream} + * */ + map(f:(value:A) => B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `constant` value, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {EventStream} + * */ + map(constant:B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `propertyExtractor` string like ".keyCode", returning a new EventStream. So, if `propertyExtractor` is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If `keyCode` was a function, the result EventStream would contain the values returned by the function. The "Function Construction rules" apply here. The `map` method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {EventStream} + * */ + map(propertyExtractor:string):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} events to the current value of the given [Property]{@link Bacon.Property} `property`. This is equivalent to [Property.sampledBy]{@link Bacon.Property#sampledBy}. + * @param {Property} property + * @returns {EventStream} + */ + map(property:Property):EventStream; + + /** + * @callback EventStream#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method EventStream#mapError + * @description Maps [EventStream]{@link Bacon.EventStream} [Error]{@link Bacon.Error}s using given function `f`. More specifically, feeds the "error" field of the Error event to the function and produces a [Next]{@link Bacon.Next} event based on the return value. The "Function Construction rules" apply here. + * @param {EventStream#mapError~f} f + * @returns {EventStream} + */ + mapError(f:(error:E) => B):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns `false`. + * @returns {EventStream} + */ + errors():EventStream; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {EventStream} + */ + skipErrors():EventStream; + + /** + * @callback EventStream#mapEnd~f + * @returns {A} + */ + /** + * @method EventStream#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. The value is created by calling the given function `f` when the source [EventStream]{@link Bacon.EventStream} ends. + * @param {EventStream#mapEnd~f} f + * @returns {EventStream} + */ + mapEnd(f:() => A):EventStream; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. A static `value` is used. + * @param {A} value + * @returns {EventStream} + */ + mapEnd(value:A):EventStream; + + /** + * @callback EventStream#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#filter + * @description Filters [EventStream]{@link Bacon.EventStream} `value`s using a given predicate function `f`. + * @param {EventStream#filter~f} f + * @returns {EventStream} + */ + filter(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `constant` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {EventStream} + */ + filter(bool:boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {EventStream} + */ + filter(propertyExtractor:string):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values based on the value of a [Property]{@link Bacon.Property} `property`. [Event]{@link Bacon.Event} will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {EventStream} + */ + filter(property:Property):EventStream; + + /** + * @callback EventStream#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#takeWhile + * @description Takes [EventStream]{@link Bacon.EventStream} values while given predicate function `f` holds `true`, and then ends. + * @param {EventStream#takeWhile} f + * @returns {EventStream} + */ + takeWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Takes [EventStream]{@link Bacon.EventStream} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {EventStream} + */ + takeWhile(property:Property):EventStream; + + /** + * @method + * @description Takes at most n elements from the [EventStream]{@link Bacon.EventStream}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {EventStream} + */ + take(n:number):EventStream; + + /** + * @method + * @description Takes elements from [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in the EventStream `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {EventStream} + */ + takeUntil(stream:EventStream):EventStream; + + /** + * @method + * @description Takes the first element from the [EventStream]{@link Bacon.EventStream}. Essentially [Observable.take]{@link Bacon.EventStream#take}(1). + * @returns {EventStream} + */ + first():EventStream; + + /** + * @method + * @description Takes the last element from the [EventStream]{@link Bacon.EventStream}. None, if EventStream is empty. + * @returns {EventStream} + * @example + * // This creates the stream which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).last(); + */ + last():EventStream; + + /** + * @method + * @description Skips the first `n` elements from the [EventStream]{@link Bacon.EventStream}. + * @param {number} n + * @returns {EventStream} + */ + skip(n:number):EventStream; + + /** + * @method + * @description Delays the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). + * @param {number} delay + * @returns {EventStream} + */ + delay(delay:number):EventStream; + + /** + * @method EventStream#throttle + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. + * @param {number} delay + * @returns {EventStream} + */ + throttle(delay:number):EventStream; + + /** + * @method EventStream#debounce + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". The difference of [throttle]{@link Bacon.EventStream#throttle} and [debounce]{@link Bacon.EventStream#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {EventStream} + */ + debounce(delay:number):EventStream; + + /** + * @method + * @description Passes the first event in the [EventStream]{@link Bacon.EventStream} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {EventStream} + */ + debounceImmediate(delay:number):EventStream; + + /** + * @callback EventStream#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method EventStream#doAction + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {EventStream#doAction~f} f + * @returns {EventStream} + */ + doAction(f:(value:A) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {EventStream} + */ + doAction(propertyExtractor:string):EventStream; + + /** + * @callback EventStream#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method EventStream#doError + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as `doAction` but for errors. + * @param {EventStream#doError~f} f + * @returns {EventStream} + */ + doError(f:(error:E) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} that inverts boolean values. + * @returns {EventStream} + */ + not():EventStream; + + /** + * @method EventStream#log + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original EventStream. Note that as a side-effect, the EventStream will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {EventStream} + */ + log(label?:string):EventStream; + + /** + * @method EventStream#doLog + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {EventStream} + */ + doLog():EventStream; + + /** + * @method + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned EventStream. + * @returns {EventStream} + */ + endOnError():EventStream; + + /** + * @callback EventStream#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method EventStream#endOnError + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned EventStream. + * @param {EventStream#endOnError} f + * @returns {EventStream} + */ + endOnError(f:(error:E) => boolean):EventStream; + + /** + * @callback EventStream#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method EventStream#withHandler + * @description Lets you do more custom event handling on [EventStream]{@link Bacon.EventStream}: you get all events to your function `f` and you can output any number of events and end the stream if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {EventStream#withHandler~f} f + * @returns {EventStream} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):EventStream; + + /** + * @method + * @description Sets the name of the [EventStream]{@link Bacon.EventStream}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {EventStream} + */ + name(newName:string):EventStream; + + /** + * @method + * @description Sets the structured description of the [EventStream]{@link Bacon.EventStream}. The `toString` and `inspect` methods use this data recursively to create a string representation for the `EventStream`. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {EventStream} + * @example + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):EventStream; + + /** + * @callback EventStream#groupBy1~keyF + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#groupBy1 + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. + * @param {EventStream#groupBy1~keyF} keyF + * @returns {EventStream>} + */ + groupBy(keyF:(value:A) => B):EventStream>; + + /** + * @callback keyF + * @param {A} value + * @returns {B} + */ + /** + * @callback limitF + * @param {EventStream} groupedStream + * @param {Initial|Next|End|Error} groupStartingEvent + * @returns {EventStream} + */ + /** + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. `limitF` is provided to limit grouped stream life. EventStream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream and the original [Event]{@link Bacon.Event} causing the EventStream to start as parameters. + * @param {keyF} keyF + * @param {limitF} limitF + * @returns {EventStream>} Grouped streams. + */ + groupBy(keyF:(value:A) => B, limitF:(groupedStream:EventStream, groupStartingEvent:Initial|Next|End|Error) => EventStream):EventStream>; + + /** + * @callback EventStream#subscribe~f + * @param {Event} event + * @returns {void|NoMore} + */ + /** + * @callback EventStream#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#subscribe + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will receive [Event]{@link Bacon.Event} objects. The [subscribe]{@link EventStream#subscribe} call returns an [unsubscribe function]{@link EventStream#subscribe~unsubscribe} that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore]{@link Bacon.noMore} from the handler function as a reply to an Event. + * @param {EventStream#subscribe~f} f + * @returns {EventStream#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void|NoMore):() => void; + + /** + * @callback EventStream#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback EventStream#onValue~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValue + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will be called for each new value in the EventStream. This is the simplest way to assign a side-effect to a EventStream. The difference to the [subscribe]{@link Bacon.EventStream#subscribe} method is that the actual EventStream values are received, instead of [Event]{@link Bacon.Event} objects. Just like `subscribe`, this method returns a function for `unsubscribe`ing. + * @param {EventStream#onValue~f} f + * @returns {EventStream#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback EventStream#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback EventStream#onValues~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValues + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Like [EventStream.onValue]{@link Bacon.EventStream#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {EventStream#onValues~f} f + * @returns {EventStream#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @callback EventStream#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method EventStream#skipDuplicates + * @description Drops consecutive equal elements of the [EventStream]{@link Bacon.EventStream}. Uses the === operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling [isEqual]{@link EventStream#skipDuplicates~isEqual}. For instance, to do a deep comparison, you can use the `isEqual` function from underscore.js like `stream.skipDuplicates(_.isEqual)`. + * @param {EventStream#skipDuplicates~isEqual} [isEqual] + * @returns {EventStream} + * @example + * Bacon.fromArray([1, 2, 2, 1]).skipDuplicates().log(); + * // > returns [1, 2, 1] in an order + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):EventStream; + + /** + * @method + * @description Concatenates two [EventStream]{@link Bacon.EventStream}s into one so that it will deliver events from EventStream until it ends and then deliver events from `otherStream`. This means too that events from `otherStream`, occurring before the end of EventStream will not be included in the result EventStream. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + concat(otherStream:EventStream):EventStream; + + /** + * @method + * @description Merges two [EventStream]{@link Bacon.EventStream}s into one that delivers events from both. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + merge(otherStream:EventStream):EventStream; + + /** + * @method + * @description Pauses and buffers the [EventStream]{@link Bacon.EventStream} if last event in `valve` is truthy. All buffered events are released when `valve` becomes falsy. + * @param {Observable} valve + * @returns {EventStream} + */ + holdWhen(valve:Observable):EventStream; + + /** + * @method + * @description Adds a starting `value` to the [EventStream]{@link Bacon.EventStream}, i.e. concats a EventStream containing a single `value` with this EventStream. + * @param {A} value + * @returns {EventStream} + */ + startWith(value:A):EventStream; + + /** + * @callback EventStream#skipWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#skipWhile + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the given predicate function `f` returns falsy once, and then lets all events pass through. + * @param {EventStream#skipWhile~f} f + * @returns {EventStream} + */ + skipWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the value of the given [Property]{@link Bacon.Property} `property` is falsy once, and then lets all events pass through. + * @param {Property} property + * @returns {EventStream} + */ + skipWhile(property:Property):EventStream; + + /** + * @method + * @description Skips elements from the [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in `stream2`. In other words, starts delivering values from `stream` after first event appears in `stream2`. + * @param {EventStream} stream2 + * @returns {EventStream} + */ + skipUntil(stream2:EventStream):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given `delay` (in milliseconds). The buffer is flushed at most once in the given `delay`. + * @param {number} delay + * @returns {EventStream} + * @example + * // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: + * Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); + */ + bufferWithTime(delay:number):EventStream; + + /** + * @callback EventStream#bufferWithTime~f + * @param {EventStream#bufferWithTime~defer} defer + * @returns {void} + */ + /** + * @callback EventStream#bufferWithTime~defer + * @param {...*} args + * @returns {void} + */ + /** + * @method EventStream#bufferWithTime + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given "defer-function" `f`. + * @param {EventStream#bufferWithTime~f} f + * @returns {EventStream} + * @example + * // Here's an equivalent to `stream.bufferWithTime(10)`: + * let stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); + * stream.bufferWithTime(f => { setTimeout(f, 10); }); } + */ + bufferWithTime(f:(defer:(...args:any[]) => void) => void):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events with given `count`. The buffer is flushed when it contains the given `count` of elements. + * @param {number} count + * @returns {EventStream} + * @example + * // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. + * Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); + */ + bufferWithCount(count:number):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events and flushes when either the buffer contains the given `count` of elements or the given `delay` (in milliseconds) has passed since last buffered event. + * @param {number} delay + * @param {number} count + * @returns {EventStream} + */ + bufferWithTimeOrCount(delay:number, count:number):EventStream; + + /** + * @method EventStream#toProperty + * @description Creates a [Property]{@link Bacon.Property} based on the [EventStream]{@link Bacon.EventStream}. Without arguments, you'll get a Property without an initial value and will get its first actual value from the EventStream, and after that it'll always have a current value. Given `initialValue` will be used as the current value until the first value comes from the EventStream. + * @param {A} [initialValue] + * @returns {Property} + */ + toProperty(initialValue?:A):Property; + } + + var EventStream:{ + /** + * @callback EventStream#new~subscribe + * @param {EventStream#new~sink} sink + * @returns {EventStream#new~unsubscribe} + */ + /** + * @callback EventStream#new~sink + * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value + * @returns {void} + */ + /** + * @callback EventStream#new~unsubscribe + * @returns {void} + */ + /** + * @constructor EventStream#new + * @constructs Bacon.EventStream + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given `subscribe` function. + * @param {EventStream#new~subscribe} subscribe + * @returns {EventStream} + */ + new(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; + }; + + /** + * @class Property + * @augments Bacon.Observable + * @description A reactive property. Has the concept of "current value". You can create a Property from an [EventStream]{@link Bacon.EventStream} by using either [EventStream.toProperty]{@link Bacon.EventStream#toProperty} or [Observable.scan]{@link Bacon.Observable#scan} method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the EventStream has ended. + * */ + interface Property extends Observable { + /** + * @callback Property#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method Property#map + * @description Maps the [Property]{@link Bacon.Property} values using given function `f`, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {Property#map~f} f + * @returns {Property} + * */ + map(f:(value:A) => B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `constant` value, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {Property} + * */ + map(constant:B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `propertyExtractor` string like ".keyCode", returning a new Property. So, if f is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If "keyCode" was a function, the resulting Property would contain the values returned by the function. This method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {Property} + * */ + map(propertyExtractor:string):Property; + + /** + * @callback Property#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method Property#mapError + * @description Maps the [Property]{@link Bacon.Property} errors using given function `f`. More specifically, feeds the "error" field of the [Error]{@link Bacon.Error} event to the function `f` and produces a [Next]{@link Bacon.Next} event based on the return value. + * @param {Property#mapError~f} f + * @returns {Property} + */ + mapError(f:(error:E) => B):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns false. + * @returns {Property} + */ + errors():Property; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {Property} + */ + skipErrors():Property; + + /** + * @callback Property#mapEnd~f + * @returns {A} + */ + /** + * @method Property#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. The value is created by calling the given function `f` when the source Property ends. + * @param {Property#mapEnd~f} f + * @returns {Property} + */ + mapEnd(f:() => A):Property; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. A static `value` is used. + * @param {A} value + * @returns {Property} + */ + mapEnd(value:A):Property; + + /** + * @callback Property#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#filter + * @description Filters the [Property]{@link Bacon.Property} values using a given predicate function `f`. + * @param {Property#filter~f} f + * @returns {Property} + */ + filter(f:(value:A) => boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given constant `bool` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {Property} + */ + filter(bool:boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {Property} + */ + filter(propertyExtractor:string):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values based on the value of the Property `property`. Event will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {Property} + */ + filter(property:Property):Property; + + /** + * @callback Property#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#takeWhile + * @description Takes the [Property]{@link Bacon.Property} values while given predicate function `f` holds `true`, and then ends. + * @param {Property#takeWhile~f} f + * @returns {Property} + */ + takeWhile(f:(value:A) => boolean):Property; + + /** + * @method + * @description Takes the [Property]{@link Bacon.Property} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {Property} + */ + takeWhile(property:Property):Property; + + /** + * @method Property#take + * @description Takes at most `n` elements from the [Property]{@link Bacon.Property}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {Property} + */ + take(n:number):Property; + + /** + * @method + * @description Takes elements from the [Property]{@link Bacon.Property} until a [Next]{@link Bacon.Next} event appears in the `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {Property} + */ + takeUntil(stream:EventStream):Property; + + /** + * @method + * @description Takes the first element from the [Property]{@link Bacon.Property}. Essentially [Property.take]{@link Bacon.Property#take}(1). + * @returns {Property} + */ + first():Property; + + /** + * @method + * @description Takes the last element from the [Property]{@link Bacon.Property}. None, if Property is empty. + * @returns {Property} + * @example + * // This creates the property which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).toProperty().last(); + */ + last():Property; + + /** + * @method + * @description Skips the first `n` elements from the [Property]{@link Bacon.Property}. + * @param {number} n + * @returns {Property} + */ + skip(n:number):Property; + + /** + * @method + * @description Delays the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Does not delay the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + delay(delay:number):Property; + + /** + * @method Property#throttle + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. Does not affect emitting the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + throttle(delay:number):Property; + + /** + * @method Property#debounce + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a Property. The difference of [throttle]{@link Bacon.Property#throttle} and [debounce]{@link Bacon.Property#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {Property} + */ + debounce(delay:number):Property; + + /** + * @method + * @description Passes the first event in the [Property]{@link Bacon.Property} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {Property} + */ + debounceImmediate(delay:number):Property; + + /** + * @callback Property#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method Property#doAction + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {Property#doAction~f} f + * @returns {Property} + */ + doAction(f:(value:A) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {Property} + */ + doAction(propertyExtractor:string):Property; + + /** + * @callback Property#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method Property#doError + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as [doAction]{@link Bacon.Property#doAction} but for [Error]{@link Bacon.Error}s. + * @param {Property#doError~f} f + * @returns {Property} + */ + doError(f:(error:E) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that inverts boolean values. + * @returns {Property} + */ + not():Property; + + /** + * @method Property#log + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original Property. Note that as a side-effect, the Property will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {Property} + */ + log(label?:string):Property; + + /** + * @method Property#doLog + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {Property} + */ + doLog():Property; + + /** + * @method + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned Property. + * @returns {Property} + */ + endOnError():Property; + + /** + * @callback Property#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method Property#endOnError + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned Property. + * @param {Property#endOnError~f} f + * @returns {Property} + */ + endOnError(f:(error:E) => boolean):Property; + + /** + * @callback Property#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method Property#withHandler + * @description Lets you do more custom event handling on the [Property]{@link Bacon.Property}: you get all events to your function `f` and you can output any number of [Event]{@link Bacon.Event}s and end the Property if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {Property#withHandler~f} f + * @returns {Property} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):Property; + + /** + * @method + * @description Sets the `newName` of the [Property]{@link Bacon.Property}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {Property} + */ + name(newName:string):Property; + + /** + * @method + * @description Sets the structured description of the [Property]{@link Bacon.Property}. The `toString` and `inspect` methods use this data recursively to create a string representation for the Property. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {Property} + * @example + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):Property; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} based on this [Property]{@link Bacon.Property}. The EventStream contains also an event for the current value of this Property at the time this method was called. + * @returns {EventStream} + */ + toEventStream():EventStream; + + /** + * @callback Property#subscribe~f + * @param {Event} event + * @returns {void} + */ + /** + * @callback Property#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method Property#subscribe + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. If there's a current value, an [Initial]{@link Bacon.Initial} event will be pushed immediately. [Next]{@link Bacon.Next} event will be pushed on updates and an [End]{@link Bacon.End} event in case the source Property ends. Returns a function that you call to `unsubscribe`. + * @param {Property#subscribe~f} f + * @returns {Property#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void):() => void; + + /** + * @callback Property#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Property#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValue + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Similar to [EventStream.onValue]{@link Bacon.EventStream#onValue}, except that also pushes the initial value of the Property, in case there is one. Just like [subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Property#onValue~f} f + * @returns {Property#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Property#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback Property#onValues~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValues + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Like [onValue]{@link Bacon.Property#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {Property#onValues~f} f + * @returns {Property#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @method Property#assign + * @description Calls the `method` of the given `object` with each value of this [Property]{@link Bacon.Property}. You can optionally supply `params` which will be used as the first arguments of the `method` call. Note that the [assign]{@link Bacon.Property#assign} method is actually just a synonym for [onValue]{@link Bacon.Property#onValue}. + * @param {Object} obj + * @param {string} method + * @param {...*} params + * @returns {void} + * @example + * let property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); + * // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: + * property.assign($("#my-button"), "attr", "disabled"); + * // A simpler example would be to toggle the visibility of an element based on a Property: + * property.assign($("#my-button"), "toggle"); + */ + assign(obj:Object, method:string, ...params:any[]):void; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at given `interval` (in milliseconds). + * @param {number} interval + * @returns {EventStream} + */ + sample(interval:number):EventStream; + + /** + * @method Property#sampledBy + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at each event from the given `stream`. The result EventStream will contain the value at each event in the source Property. + * @param {EventStream} stream + * @returns {EventStream} + */ + sampledBy(stream:EventStream):EventStream; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} by sampling the value at each event from the given [Property]{@link Bacon.Property} `property`. The result Property will contain the value at each event in the source Property. + * @param {Property} property + * @returns {Property} + */ + sampledBy(property:Property):Property; + + /** + * @callback Property#sampledBy~f + * @param {A} propertyValue + * @param {B} samplerValue + * @returns {C} + */ + /** + * @method Property#sampledBy + * @description Samples the [Property]{@link Bacon.Property} on `streamOrProperty` events. The result values will be formed using the given function `f`. + * @param {Observable} streamOrProperty + * @param {Property#sampledBy~f} f + * @returns {EventStream} + */ + sampledBy(streamOrProperty:Observable, f:(propertyValue:A, samplerValue:B) => C):EventStream; + + /** + * @callback Property#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method Property#skipDuplicates + * @description Drops consecutive equal elements. Uses the `===` operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling `isEqual(oldValue, newValue)`. The old name for this method was `distinctUntilChanged`. + * @param {Property#skipDuplicates~isEqual} [isEqual] + * @returns {Property} + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):Property; + + /** + * @method Property#changes + * @description Returns an [EventStream]{@link Bacon.EventStream} of [Property]{@link Bacon.Property} value changes. Returns exactly the same events as the Property itself, except any [Initial]{@link Bacon.Initial} events (the stream DOES NOT include an event for the current value of the Property at the time this method was called). Note that [Property.changes]{@link Bacon.Property#changes} DOES NOT skip duplicate values, use [Property.skipDuplicates]{@link Bacon.Property#skipDuplicates} for that. + * @returns {EventStream} + */ + changes():EventStream; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the && operator. + * @param {Property} other + * @returns {Property} + */ + and(other:Property):Property; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the || operator. + * @param {Property} other + * @returns {Property} + */ + or(other:Property):Property; + + /** + * @method + * @description Adds an initial "default" value for the [Property]{@link Bacon.Property}. If the Property doesn't have an initial value of it's own, the given `value` will be used as the initial value. If the property has an initial value of its own, the given `value` will be ignored. + * @param {A} value + * @returns {Property} + */ + startWith(value:A):Property; + } + + /** + * @function Bacon.combineAsArray + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. The input array may contain both Properties and EventStreams. In the latter case, the stream is first converted into a Property and then combined with the other Property's. + * @param {(A|Observable)[]} streams + * @returns {Property} + */ + function combineAsArray(streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. Like [Bacon.combineAsArray]{@link Bacon.combineAsArray}, but `streams` are provided as a list of arguments as opposed to a single array. + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineAsArray(...streams:(A|Observable)[]):Property; + + /** + * @callback Property#combineWith~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Property#combineWith + * @description Combines given n [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using the given n-ary function `f`. + * @param {Property#combineWith~f} f + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineWith(f:(...args:A[]) => B, ...streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using a `template` object. + * @param {{string:number|boolean|string|Object|Observable}} template + * @returns {Property} + */ + function combineTemplate(template:{[label:string]:number|boolean|string|Object|Observable}):Property; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function mergeAll(streams:EventStream[]):EventStream; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function mergeAll(...streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function zipAsArray(streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. EventStream's are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipAsArray(...streams:EventStream[]):EventStream; + + /** + * @callback Bacon.zipWith1~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith1 + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @param {Bacon.zipWith1~f} f + * @returns {EventStream} + */ + function zipWith(streams:EventStream[], f:(...args:A[]) => B):EventStream; + + /** + * @callback Bacon.zipWith2~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith2 + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Streams are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {Bacon.zipWith2~f} f + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipWith(f:(...args:A[]) => B, ...streams:EventStream[]):EventStream; + + /** + * @function + * @description Is a shorthand for combining multiple sources ([EventStream]{@link Bacon.EventStream}s, [Property]{@link Bacon.Property}s, constants) as array and assigning the side-effect function `f` for the values. + * @param {...*} args + * @returns {void} + */ + function onValues(...args:any[]):void; + + /** + * @class Bus + * @augments Bacon.EventStream + * @description An [EventStream]{@link Bacon.EventStream} that allows you to [push]{@link Bacon.Bus#push} values into the EventStream. It also allows [plug]{@link Bacon.Bus#plug}ging other EventStream's into the Bus. The Bus practically merges all plugged-in streams and the values pushed using the [push]{@link Bacon.Bus#push} method. + */ + interface Bus extends EventStream { + /** + * @method Bus#push + * @description Pushes the given `value` to the [Bus]{@link Bacon.Bus}. + * @param {A} value + * @returns {void} + */ + push(value:A):void; + + /** + * @method + * @description Ends the [Bus]{@link Bacon.Bus}. Sends an [End]{@link Bacon.End} event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [Bus.push]{@link Bacon.Bus#push} and [Bus.plug]{@link Bacon.Bus#plug} methods have no effect. + * @returns {void} + */ + end():void; + + /** + * @method + * @description Sends an [Error]{@link Bacon.Error} with given `error` message to all subscribers. + * @param {Error} error + * @returns {void} + */ + error(error:Error):void; + + /** + * @callback Bus#plug~unplug + * @returns {void} + */ + /** + * @method Bus#plug + * @description Plugs the given [EventStream]{@link Bacon.EventStream} to the [Bus]{@link Bacon.Bus}. All events from the given `stream` will be delivered to the subscribers of the Bus. Returns a function `unplug` that can be used to unplug the same stream. The [plug]{@link Bacon.Bus#plug} method practically allows you to merge in other EventStream's after the creation of the Bus. + * @param {EventStream} stream + * @returns {Bus#plug~unplug} + */ + plug(stream:EventStream):() => void; + } + + var Bus:{ + /** + * @constructor + * @constructs Bacon.Bus + * @description Returns a new [Bus]{@link Bacon.Bus}. + * @returns {Bus} + */ + new():Bus; + }; + + /** + * @class Event + * @description Has subclasses [Initial]{@link Bacon.Initial}, [Next]{@link Bacon.Next}, [End]{@link Bacon.End} and [Error]{@link Bacon.Error}. + * */ + class Event { + /** + * @method + * @description Returns the value associated with a [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next} event. + * @returns {A} + */ + value():A; + + /** + * @method + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + hasValue():boolean; + + /** + * @method Error#isInitial + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial}. + * @returns {boolean} + */ + isInitial():boolean; + + /** + * @method Error#isNext + * @description Returns `true` for events of type [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + isNext():boolean; + + /** + * @method Error#isError + * @description Returns `true` for events of type [Error]{@link Bacon.Error}. + * @returns {boolean} + */ + isError():boolean; + + /** + * @method Error#isEnd + * @description Returns `true` for events of type [End]{@link Bacon.End}. + * @returns {boolean} + */ + isEnd():boolean; + } + + /** + * @class Error + * @augments Bacon.Event + * @description An error event. Call [Event.isError]{@link Bacon.Event#isError} to distinguish these events in your subscriber, or use [onError]{@link Bacon.Observable#onError} to react to error events only. [Error.error]{@link Bacon.Error#error} returns the associated error object (usually string). [Error]{@link Bacon.Error} events are always passed through all stream combinators. So, even if you filter all values out, the error events will pass through. If you use [Observable.flatMap]{@link Bacon.Observable#flatMap}, the result stream will contain Error events from the source as well as all the spawned stream. You can take action on errors by using the [Observable.onError]{@link Bacon.Observable#onError}. See documentation on [Observable.onError]{@link Bacon.Observable#onError}, [EventStream.mapError]{@link Bacon.EventStream#mapError}, [Property.mapError]{@link Bacon.Property#mapError}, [EventStream.errors]{@link Bacon.EventStream#errors}, [Property.errors]{@link Bacon.Property#errors}, [EventStream.skipErrors]{@link Bacon.EventStream#skipErrors}, [Property.skipErrors]{@link Bacon.Property#skipErrors}, [Bacon.retry]{@link Bacon.retry} and [Observable.flatMapError]{@link Bacon.Observable#flatMapError}. An Error does not terminate the stream. The methods [EventStream.endOnError]{@link Bacon.EventStream#endOnError} and [EventStream.endOnError]{@link Bacon.EventStream#endOnError} returns a stream/property that ends immediately after first error. Bacon.js doesn't currently generate any Error events itself (except when converting errors using [Bacon.fromPromise]{@link Bacon.fromPromise}). Error events definitely would be generated by streams derived from IO sources such as AJAX calls. + * @example + * // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * NOTE: had to explicitly specify the `` typing for `flatMap`. + * return x > 2 ? new Bacon.Error("too big") : x; + * }); + * + * // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: + * Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { + * let isNonCriticalError = error => Math.random() < .5, + * handleNonCriticalError = error => 42; + * return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); + * }); + * + * // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * let dangerousFunction = x => { + * throw new Error("dangerous function!"); + * }; + * try { + * return dangerousFunction(x); + * } catch (e) { + * return new Bacon.Error(e); + * } + * }); + */ + class Error extends Event { + /** + * @constructor + * @constructs Error + * @param {E} error + * */ + constructor(error:E); + + /** + * @property Error#error + * @description Returns the `error` associated with an [Error]{@link Bacon.Error} event. + * @returns {E} + */ + error:E; + } + + /** + * @class End + * @augments Bacon.Event + * @description An end-of-stream event of [EventStream]{@link Bacon.EventStream} or [Property]{@link Bacon.Property}. Call [Event.isEnd]{@link Bacon.Event#isEnd} to distinguish an End from other events. + * */ + class End extends Event { + /** + * @constructor + * @constructs Bacon.End + * */ + constructor(); + } + + /** + * @class Initial + * @augments Bacon.Event + * @description The initial (current) value of a [Property]{@link Bacon.Property}. Call [Event.isInitial]{@link Bacon.Event#isInitial} to distinguish from other events. Only sent immediately after subscription to a Property. + * */ + class Initial extends Event { + /** + * @constructor + * @constructs Bacon.Initial + * @param {A} value + * */ + constructor(value:A); + } + + /** + * @class Next + * @augments Bacon.Event + * @description Next value in an [EventStream]{@link Bacon.EventStream} or a [Property]{@link Bacon.Property}. Call [Event.isNext]{@link Bacon.Event#isNext} to distinguish a Next event from other events. + * */ + class Next extends Event { + /** + * @constructor + * @constructs Bacon.Next + * @param {A} value + * @example + * new Bacon.Next("value"); + * */ + constructor(value:A); + + /** + * @callback Next#constructor + * @returns {A} + */ + /** + * @constructor Next#constructor + * @constructs Bacon.Next + * @description This version is safe only when you know that the actual value in the stream is not a function. The idea in using a function `f` instead of a plain value is that the internals on Bacon.js take advantage of lazy evaluation by deferring the evaluations of values created by `map`, `combine`. + * @param {Next#constructor} f + * @example + * new Bacon.Next(() => "value"); + * */ + constructor(f:() => A); + } + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [EventStream]{@link Bacon.EventStream}. + * @returns {EventStream} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. + * @param {E} error + * @returns {boolean} + */ + /** + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [EventStream]{@link Bacon.EventStream} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [EventStream]{@link Bacon.EventStream} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {EventStream} + */ + function retry(options:{ + source:() => EventStream; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):EventStream; + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [Property]{@link Bacon.Property}. + * @returns {Property} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. + * @param {E} error + * @returns {boolean} + */ + /** + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [Property]{@link Bacon.Property} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [Property]{@link Bacon.Property} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {Property} + */ + function retry(options:{ + source:() => Property; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):Property; + + /** + * @callback Bacon.when1~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.when1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when1~f1} f1 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B):EventStream; + + /** + * @callback Bacon.when2~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when2~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.when2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when2~f2} f2 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B):EventStream; + + /** + * @callback Bacon.when3~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.when3 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when3~f3} f3 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B):EventStream; + + /** + * @callback Bacon.when4~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.when4 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when4~f4} f4 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B):EventStream; + + /** + * @callback Bacon.when5~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f5 + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.when5 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.when5~f5} f5 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B, pattern5:Observable[], f5:(...args:A5[]) => B):EventStream; + + /** + * @callback Bacon.update1~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.update1 + * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update1~f1} f1 + * @returns {EventStream} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C):Property; + + /** + * @callback Bacon.update2~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update2~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.update2 + * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update2~f2} f2 + * @returns {EventStream} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C):Property; + + /** + * @callback Bacon.update3~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.update3 + * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update3~f3} f3 + * @returns {EventStream} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C):Property; + + /** + * @callback Bacon.update4~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.update4 + * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update4~f4} f4 + * @returns {EventStream} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => C):Property; + + /** + * @callback Bacon.update5~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f5 + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.update5 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.update5~f5} f5 + * @returns {EventStream} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => C, pattern5:Observable[], f5:(initial:B, ...args:A5[]) => C):Property; +} + +declare module "baconjs" { + export = Bacon; +} diff --git a/camel-case/camel-case-tests.ts b/camel-case/camel-case-tests.ts new file mode 100644 index 000000000..4f40e11fb --- /dev/null +++ b/camel-case/camel-case-tests.ts @@ -0,0 +1,10 @@ +/// + +import camelCase = require('camel-case'); + +console.log(camelCase('string')); // => "string" +console.log(camelCase('dot.case')); // => "dotCase" +console.log(camelCase('PascalCase')); // => "pascalCase" +console.log(camelCase('version 1.2.10')); // => "version1_2_10" + +console.log(camelCase('STRING 1.2', 'tr')); // => "strıng1_2" diff --git a/camel-case/camel-case.d.ts b/camel-case/camel-case.d.ts new file mode 100644 index 000000000..9b2ec3fec --- /dev/null +++ b/camel-case/camel-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for camel-case +// Project: https://github.com/blakeembrey/camel-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "camel-case" { + function camelCase(string: string, locale?: string): string; + export = camelCase; +} diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index cd0be3593..af708cf0a 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -44,6 +44,7 @@ interface Cheerio { // Traversing find(selector: string): Cheerio; + find(element: Cheerio): Cheerio; parent(selector?: string): Cheerio; parents(selector?: string): Cheerio; diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts index 523c2c515..aa052b8ee 100644 --- a/ckeditor/ckeditor-tests.ts +++ b/ckeditor/ckeditor-tests.ts @@ -161,7 +161,7 @@ function test_dom_element() { } function test_dom_event() { - var event = new CKEDITOR.dom.event(new Event()); + var event = new CKEDITOR.dom.event(new Event("")); alert(event.getKey()); alert(event.getKeystroke() == 65); alert(event.getKeystroke() == CKEDITOR.CTRL + 65); diff --git a/connect-modrewrite/connect-modrewrite-tests.ts b/connect-modrewrite/connect-modrewrite-tests.ts new file mode 100644 index 000000000..177cea497 --- /dev/null +++ b/connect-modrewrite/connect-modrewrite-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +import modRewrite = require('connect-modrewrite'); +import express = require('express'); + +var app = express(); + +app.use(modRewrite([ + '^/test$ /index.html', + '^/test/\\d*$ /index.html [L]', + '^/test/\\d*/\\d*$ /flag.html [L]', +])); \ No newline at end of file diff --git a/connect-modrewrite/connect-modrewrite.d.ts b/connect-modrewrite/connect-modrewrite.d.ts new file mode 100644 index 000000000..56011c6df --- /dev/null +++ b/connect-modrewrite/connect-modrewrite.d.ts @@ -0,0 +1,12 @@ +// Type definitions for connect-modrewrite +// Project: https://github.com/tinganho/connect-modrewrite +// Definitions by: Tingan Ho +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'connect-modrewrite' { + import express = require('express'); + function modrewrite(rewrites: string[]): express.RequestHandler; + export = modrewrite; +} \ No newline at end of file diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts new file mode 100644 index 000000000..8a4ec2c0b --- /dev/null +++ b/core-js/core-js-tests.ts @@ -0,0 +1,502 @@ +/// + +interface Point { x: number; y: number; } +interface Point3D extends Point { z: number; } + +let a: any; +let s: string; +let i: number; +let b: boolean; +let f: () => void; +let o: Object; +let r: RegExp; +let sym: symbol; +let e: Error; +let date: Date; +let key: PropertyKey; +let point: Point; +let point3d: Point3D; +let arrayOfPoint: Point[]; +let arrayOfPoint3D: Point3D[]; +let arrayOfSymbol: symbol[]; +let arrayOfPropertyKey: PropertyKey[]; +let arrayOfAny: any[]; +let arrayOfStringAny: [string, any][]; +let arrayLikeOfAny: ArrayLike; +let iterableOfPoint: Iterable; +let iterableOfStringPoint: Iterable<[string, Point]>; +let iterableOfPointPoint3D: Iterable<[Point, Point3D]>; +let iterableIteratorOfPoint: IterableIterator; +let iterableIteratorOfNumberPoint: IterableIterator<[number, Point]>; +let iterableIteratorOfNumber: IterableIterator; +let iterableIteratorOfString: IterableIterator; +let iterableIteratorOfPointPoint: IterableIterator<[Point, Point]>; +let iterableIteratorOfNode: IterableIterator; +let iterableIteratorOfStringPoint: IterableIterator<[string, Point]>; +let iterableIteratorOfAny: IterableIterator; +let iterableIteratorOfPropertyKey: IterableIterator; +let iterableIteratorOfPropertyKeyPoint: IterableIterator<[PropertyKey, Point]>; +let nodeList: NodeList; +let pd: PropertyDescriptor; +let pdm: PropertyDescriptorMap; +let map: Map; +let set: Set; +let weakMap: WeakMap; +let weakSet: WeakSet; +let $forOfPoint: $for; +let $forOfPoint3D: $for; +let promiseLikeOfPoint: PromiseLike; +let promiseLikeOfPoint3D: PromiseLike; +let promiseOfPoint: Promise; +let promiseOfPoint3D: Promise; +let promiseOfArrayOfPoint: Promise; +let promiseOfVoid: Promise; +let dictOfPoint: Dict; +let dictOfPoint3D: Dict; +let dictOfAny: Dict; + +// ############################################################################################# +// ECMAScript 6: Object & Function +// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, +// es6.object.to-string, es6.function.name and es6.function.has-instance. +// ############################################################################################# + +point = Object.assign(point, point); +b = Object.is(point, point); +Object.setPrototypeOf(point, point); +s = f.name; +b = f[Symbol.hasInstance](point); + +// ############################################################################################# +// ECMAScript 6: Array +// Modules: es6.array.from, es6.array.of, es6.array.copy-within, es6.array.fill, es6.array.find, +// and es6.array.find-index +// ############################################################################################# + +point = arrayOfPoint.find(p => b); +i = arrayOfPoint.findIndex(p => b); +arrayOfPoint = arrayOfPoint.fill(point, i, arrayOfPoint.length); +arrayOfPoint = arrayOfPoint.copyWithin(i, i, i); +a = arrayOfPoint[Symbol.unscopables]; +arrayOfPoint = Array.from(arrayOfPoint); +arrayOfPoint = Array.from(iterableOfPoint); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d, a); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d, a); +arrayOfPoint = Array.of(point, point); + +// ############################################################################################# +// ECMAScript 6: String & RegExp +// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, +// es6.string.ends-with, es6.string.includes, es6.string.repeat, +// es6.string.starts-with, and es6.regexp +// ############################################################################################# + +i = s.codePointAt(i); +b = s.includes(s, i); +b = s.endsWith(s, i); +s = s.repeat(i); +b = s.startsWith(s, i); +s = String.fromCodePoint(i, i); +s = String.raw`abc`; +s = r.flags; + +// ############################################################################################# +// ECMAScript 6: Number & Math +// Modules: es6.number.constructor, es6.number.statics, and es6.math +// ############################################################################################# + +i = Number.EPSILON; +b = Number.isFinite(i); +b = Number.isInteger(i); +b = Number.isNaN(i); +b = Number.isSafeInteger(i); +i = Number.MAX_SAFE_INTEGER; +i = Number.MIN_SAFE_INTEGER; +i = Number.parseFloat(s); +i = Number.parseInt(s); +i = Number.parseInt(s, i); +i = Math.clz32(i); +i = Math.imul(i, i); +i = Math.sign(i); +i = Math.log10(i); +i = Math.log2(i); +i = Math.log1p(i); +i = Math.expm1(i); +i = Math.cosh(i); +i = Math.sinh(i); +i = Math.tanh(i); +i = Math.acosh(i); +i = Math.asinh(i); +i = Math.atanh(i); +i = Math.hypot(i, i); +i = Math.trunc(i); +i = Math.fround(i); +i = Math.cbrt(i); + +// ############################################################################################# +// ECMAScript 6: Symbols +// Modules: es6.symbol +// ############################################################################################# + +sym = Symbol(); +sym = Symbol(s); +sym = Symbol.for(s); +s = Symbol.keyFor(sym); +sym = Symbol.hasInstance; +sym = Symbol.isConcatSpreadable; +sym = Symbol.iterator; +sym = Symbol.match; +sym = Symbol.replace; +sym = Symbol.search; +sym = Symbol.species; +sym = Symbol.split; +sym = Symbol.toPrimitive; +sym = Symbol.toStringTag; +sym = Symbol.unscopables; +b = o.hasOwnProperty(sym); +b = o.hasOwnProperty(i); +b = o.propertyIsEnumerable(sym); +b = o.propertyIsEnumerable(i); +arrayOfSymbol = Object.getOwnPropertySymbols(a); +pd = Object.getOwnPropertyDescriptor(a, sym); +pd = Object.getOwnPropertyDescriptor(a, i); +Object.defineProperty(a, sym, pd); +Object.defineProperty(a, i, pd); +s = Math[Symbol.toStringTag]; +s = JSON[Symbol.toStringTag]; + +// Non-standard +Symbol.useSimple(); +Symbol.userSetter(); + +// ############################################################################################# +// ECMAScript 6: Collections +// Modules: es6.map, es6.set, es6.weak-map, and es6.weak-set +// ############################################################################################# + +map.clear(); +map.delete(s); +map.forEach((value: Point, key: string) => { }); +point = map.get(s); +b = map.has(s); +map = map.set(s, point); +i = map.size; +map = new Map(); +map = new Map(iterableOfStringPoint); + +set.clear(); +set.delete(point); +set.forEach((value: Point, key: Point) => { }); +b = set.has(point); +set = set.add(point); +i = set.size; +set = new Set(); +set = new Set(iterableOfPoint); + +weakMap.delete(point); +point3d = weakMap.get(point); +b = weakMap.has(point); +weakMap = weakMap.set(point, point3d); +weakMap = new WeakMap(); +weakMap = new WeakMap(iterableOfPointPoint3D); + +weakSet.delete(point); +weakSet = weakSet.add(point); +b = weakSet.has(point); +weakSet = new WeakSet(); +weakSet = new WeakSet(iterableOfPoint); + +// ############################################################################################# +// ECMAScript 6: Iterators +// Modules: es6.string.iterator, es6.array.iterator, es6.map, es6.set, web.dom.iterable +// ############################################################################################# + +iterableIteratorOfPoint = arrayOfPoint[Symbol.iterator](); +iterableIteratorOfNumberPoint = arrayOfPoint.entries(); +iterableIteratorOfNumber = arrayOfPoint.keys(); +iterableIteratorOfPoint = arrayOfPoint.values(); +iterableIteratorOfStringPoint = map.entries(); +iterableIteratorOfString = map.keys(); +iterableIteratorOfPoint = map.values(); +iterableIteratorOfStringPoint = map[Symbol.iterator](); +iterableIteratorOfPointPoint = set.entries(); +iterableIteratorOfPoint = set.keys(); +iterableIteratorOfPoint = set.values(); +iterableIteratorOfPoint = set[Symbol.iterator](); +iterableIteratorOfNode = nodeList[Symbol.iterator](); + +$for(iterableOfPoint).of((value: Point) => { }); +arrayOfPoint = $for(iterableOfPoint).array(); +arrayOfPoint3D = $for(iterableOfPoint).array(p => point3d); +$forOfPoint = $for(iterableOfPoint).filter(p => b); +$forOfPoint3D = $for(iterableOfPoint).map(p => point3d); + +// ############################################################################################# +// ECMAScript 6: Promises +// Modules: es6.promise +// ############################################################################################# + +promiseLikeOfPoint.then((point: Point) => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint.then((point: Point) => { }); +promiseOfPoint = promiseOfPoint.then(); +promiseOfPoint = promiseOfPoint.then(p => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint = promiseOfPoint.catch(e => point); +promiseOfPoint = promiseOfPoint.catch(e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => { }); +promiseOfPoint3D = promiseOfPoint.catch(e => point3d); +promiseOfPoint3D = promiseOfPoint.catch(e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.catch(e => promiseLikeOfPoint3D); +promiseOfPoint = new Promise((resolve, reject) => resolve(point)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseLikeOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => reject(e)); +promiseOfArrayOfPoint = Promise.all(arrayOfPoint); +promiseOfArrayOfPoint = Promise.all(iterableOfPoint); +promiseOfPoint = Promise.race(arrayOfPoint); +promiseOfPoint = Promise.race(iterableOfPoint); +promiseOfVoid = Promise.resolve(); +promiseOfPoint = Promise.resolve(point3d); +promiseOfPoint = Promise.resolve(promiseOfPoint); +promiseOfPoint = Promise.resolve(promiseLikeOfPoint); +promiseOfVoid = Promise.reject(e); +promiseOfPoint = Promise.reject(e); + +// ############################################################################################# +// ECMAScript 6: Reflect +// Modules: es6.reflect +// ############################################################################################# + +a = Reflect.apply(f, a, arrayLikeOfAny); +a = Reflect.construct(f, arrayLikeOfAny, a); +b = Reflect.defineProperty(a, s, pd); +b = Reflect.defineProperty(a, i, pd); +b = Reflect.defineProperty(a, sym, pd); +b = Reflect.deleteProperty(a, s); +b = Reflect.deleteProperty(a, i); +b = Reflect.deleteProperty(a, sym); +iterableIteratorOfAny = Reflect.enumerate(a); +a = Reflect.get(a, s, a); +a = Reflect.get(a, i, a); +a = Reflect.get(a, sym, a); +pd = Reflect.getOwnPropertyDescriptor(a, s); +pd = Reflect.getOwnPropertyDescriptor(a, i); +pd = Reflect.getOwnPropertyDescriptor(a, sym); +a = Reflect.getPrototypeOf(a); +b = Reflect.has(a, s); +b = Reflect.has(a, i); +b = Reflect.has(a, sym); +b = Reflect.isExtensible(a); +arrayOfPropertyKey = Reflect.ownKeys(a); +b = Reflect.preventExtensions(a); +b = Reflect.set(a, s, a, a); +b = Reflect.set(a, i, a, a); +b = Reflect.set(a, sym, a, a); +b = Reflect.setPrototypeOf(a, a); + +// ############################################################################################# +// ECMAScript 7 +// Modules: es7.array.includes, es7.string.at, es7.string.lpad, es7.string.rpad, +// es7.object.to-array, es7.object.get-own-property-descriptors, es7.regexp.escape, +// es7.map.to-json, and es7.set.to-json +// ############################################################################################# + +b = arrayOfPoint.includes(point, i); +s = s.at(i); +s = s.lpad(i, s); +s = s.rpad(i, s); +arrayOfAny = Object.values(a); +arrayOfStringAny = Object.entries(a); +pdm = Object.getOwnPropertyDescriptors(a); +s = RegExp.escape(s); +a = map.toJSON(); +a = set.toJSON(); + +// ############################################################################################# +// Mozilla JavaScript: Array generics +// Modules: js.array.statics +// ############################################################################################# + +i = Array.push(arrayOfPoint, point, point); +point = Array.pop(arrayOfPoint); +arrayOfPoint = Array.concat(arrayOfPoint, arrayOfPoint); +s = Array.join(arrayOfPoint, s); +arrayOfPoint = Array.reverse(arrayOfPoint); +point = Array.shift(arrayOfPoint); +arrayOfPoint = Array.slice(arrayOfPoint, i, i); +arrayOfPoint = Array.sort(arrayOfPoint, (a: Point, b: Point) => i); +arrayOfPoint = Array.splice(arrayOfPoint, i); +arrayOfPoint = Array.splice(arrayOfPoint, i, i, point, point); +i = Array.unshift(arrayOfPoint, point, point); +i = Array.indexOf(arrayOfPoint, point, i); +i = Array.lastIndexOf(arrayOfPoint, point, i); +b = Array.every(arrayOfPoint, (value: Point, index: number, array: Point[]) => b, a); +b = Array.some(arrayOfPoint, (value: Point, index: number, array: Point[]) => b, a); +Array.forEach(arrayOfPoint, (value: Point, index: number, array: Point[]) => { }, a); +arrayOfPoint3D = Array.map(arrayOfPoint, (value: Point, index: number, array: Point[]) => point3d, a); +arrayOfPoint = Array.filter(arrayOfPoint, (value: Point, index: number, array: Point[]) => b, a); +point = Array.reduce(arrayOfPoint, (prev: Point, value: Point, index: number, array: Point[]) => point, point); +point3d = Array.reduce(arrayOfPoint, (prev: Point3D, value: Point, index: number, array: Point[]) => point3d, point3d); +point = Array.reduceRight(arrayOfPoint, (prev: Point, value: Point, index: number, array: Point[]) => point, point); +point3d = Array.reduceRight(arrayOfPoint, (prev: Point3D, value: Point, index: number, array: Point[]) => point3d, point3d); +iterableIteratorOfNumberPoint = Array.entries(arrayOfPoint); +iterableIteratorOfNumber = Array.keys(arrayOfPoint); +iterableIteratorOfPoint = Array.values(arrayOfPoint); +point = Array.find(arrayOfPoint, p => b); +i = Array.findIndex(arrayOfPoint, p => b); +arrayOfPoint = Array.fill(arrayOfPoint, point, i, arrayOfPoint.length); +arrayOfPoint = Array.copyWithin(arrayOfPoint, i, i, i); +b = Array.includes(arrayOfPoint, point, i); +arrayOfPoint = Array.turn(arrayOfPoint, (memo: Point[], value: Point, index: number, array: Point[]) => arrayOfPoint, arrayOfPoint); +arrayOfPoint3D = Array.turn(arrayOfPoint, (memo: Point3D[], value: Point, index: number, array: Point[]) => arrayOfPoint3D, arrayOfPoint3D); + +// ############################################################################################# +// Object - https://github.com/zloirock/core-js/#object +// Modules: core.object +// ############################################################################################# + +// Non-standard +b = Object.isObject(a); +s = Object.classof(a); +point = Object.define(point, a); +point = Object.make(point, a); + +// ############################################################################################# +// Console - https://github.com/zloirock/core-js/#console +// Modules: core.log +// ############################################################################################# + +// Non-standard +log(a, a, a); +log.log(a, a, a); +log.enable(); +log.disable(); + +// ############################################################################################# +// Dict - https://github.com/zloirock/core-js/#dict +// Modules: core.dict +// ############################################################################################# + +// Non-standard +point = dictOfPoint[s]; +point = dictOfPoint[i]; +point = dictOfPoint[sym]; +dictOfPoint = new Dict(dictOfPoint); +dictOfAny = new Dict(point); +dictOfPoint = Dict(dictOfPoint); +dictOfAny = Dict(point); +b = Dict.isDict(a); +iterableIteratorOfPoint = Dict.values(dictOfPoint); +iterableIteratorOfPropertyKey = Dict.keys(dictOfPoint); +iterableIteratorOfPropertyKeyPoint = Dict.entries(dictOfPoint); +b = Dict.has(dictOfPoint, s); +b = Dict.has(dictOfPoint, i); +b = Dict.has(dictOfPoint, sym); +point = Dict.get(dictOfPoint, s); +point = Dict.get(dictOfPoint, i); +point = Dict.get(dictOfPoint, sym); +dictOfPoint = Dict.set(dictOfPoint, s, point); +dictOfPoint = Dict.set(dictOfPoint, i, point); +dictOfPoint = Dict.set(dictOfPoint, sym, point); +Dict.forEach(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => { }, a); +dictOfPoint3D = Dict.map(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => point3d, a); +dictOfPoint3D = Dict.mapPairs(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => [s, point3d], a); +dictOfPoint3D = Dict.mapPairs(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => [i, point3d], a); +dictOfPoint3D = Dict.mapPairs(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => [sym, point3d], a); +dictOfPoint = Dict.filter(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => b, a); +b = Dict.some(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => b, a); +b = Dict.every(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => b, a); +point = Dict.find(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => b, a); +key = Dict.findKey(dictOfPoint, (value: Point, key: PropertyKey, dict: Dict) => b, a); +key = Dict.keyOf(dictOfPoint, point); +b = Dict.includes(dictOfPoint, point); +point = Dict.reduce(dictOfPoint, (prev: Point, value: Point, key: PropertyKey, dict: Dict) => point, point); +point3d = Dict.reduce(dictOfPoint, (prev: Point3D, value: Point, key: PropertyKey, dict: Dict) => point3d, point3d); +dictOfPoint = Dict.turn(dictOfPoint, (memo: Dict, value: Point, key: PropertyKey, dict: Dict) => { }, dictOfPoint); +dictOfPoint3D = Dict.turn(dictOfPoint, (memo: Dict, value: Point, key: PropertyKey, dict: Dict) => { }, dictOfPoint3D); + +// ############################################################################################# +// Partial application - https://github.com/zloirock/core-js/#partial-application +// Modules: core.function.part +// ############################################################################################# + +// Non-standard +a = f.part(a, a); + +// ############################################################################################# +// Date formatting - https://github.com/zloirock/core-js/#date-formatting +// Modules: core.date +// ############################################################################################# + +// Non-standard +s = date.format(s, s); +s = date.formatUTC(s, s); + +// ############################################################################################# +// Array - https://github.com/zloirock/core-js/#array +// Modules: core.array.turn +// ############################################################################################# + +// Non-standard +arrayOfPoint = arrayOfPoint.turn((memo: Point[], value: Point, key: PropertyKey, array: Point[]) => { }, arrayOfPoint); +arrayOfPoint3D = arrayOfPoint.turn((memo: Point3D[], value: Point, key: PropertyKey, array: Point[]) => { }, arrayOfPoint3D); + +// ############################################################################################# +// Number - https://github.com/zloirock/core-js/#number +// Modules: core.number.iterator +// ############################################################################################# + +iterableIteratorOfNumber = i[Symbol.iterator](); + +// ############################################################################################# +// Escaping characters - https://github.com/zloirock/core-js/#escaping-characters +// Modules: core.string.escape-html +// ############################################################################################# + +s = s.escapeHTML(); +s = s.unescapeHTML(); + +// ############################################################################################# +// delay - https://github.com/zloirock/core-js/#delay +// Modules: core.delay +// ############################################################################################# + +promiseOfVoid = delay(i); diff --git a/core-js/core-js-tests.ts.tscparams b/core-js/core-js-tests.ts.tscparams new file mode 100644 index 000000000..09674b570 Binary files /dev/null and b/core-js/core-js-tests.ts.tscparams differ diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts new file mode 100644 index 000000000..476ab9916 --- /dev/null +++ b/core-js/core-js.d.ts @@ -0,0 +1,3037 @@ +// Type definitions for core-js v0.9.7 +// Project: https://github.com/zloirock/core-js/ +// Definitions by: Ron Buckton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare type PropertyKey = string | number | symbol; + +// ############################################################################################# +// ECMAScript 6: Object & Function +// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, +// es6.object.to-string, es6.function.name and es6.function.has-instance. +// ############################################################################################# + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects to copy properties from. + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + * @remarks Requires `__proto__` support. + */ + setPrototypeOf(o: any, proto: any): any; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + name: string; + + /** + * Determines if a constructor object recognizes an object as one of the + * constructor’s instances. + * @param value The object to test. + */ + [Symbol.hasInstance](value: any): boolean; +} + +// ############################################################################################# +// ECMAScript 6: Array +// Modules: es6.array.from, es6.array.of, es6.array.copy-within, es6.array.fill, es6.array.find, +// and es6.array.find-index +// ############################################################################################# + +interface ArrayLike { + length: number; + [n: number]: T; +} + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; + + [Symbol.unscopables]: any; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +// ############################################################################################# +// ECMAScript 6: String & RegExp +// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, +// es6.string.ends-with, es6.string.includes, es6.string.repeat, +// es6.string.starts-with, and es6.regexp +// ############################################################################################# + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + flags: string; +} + +// ############################################################################################# +// ECMAScript 6: Number & Math +// Modules: es6.number.constructor, es6.number.statics, and es6.math +// ############################################################################################# + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[]): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +// ############################################################################################# +// ECMAScript 6: Symbols +// Modules: es6.symbol +// ############################################################################################# + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + [Symbol.toStringTag]: string; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string; + + // Well-known Symbols + + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + isConcatSpreadable: symbol; + + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + iterator: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + split: symbol; + + /** + * A method that converts an object to a corresponding primitive value.Called by the ToPrimitive + * abstract operation. + */ + toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the with + * environment bindings of the associated objects. + */ + unscopables: symbol; + + /** + * Non-standard. Use simple mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ + useSimple(): void; + + /** + * Non-standard. Use setter mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ + userSetter(): void; +} + +declare var Symbol: SymbolConstructor; + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface Math { + [Symbol.toStringTag]: string; +} + +interface JSON { + [Symbol.toStringTag]: string; +} + +// ############################################################################################# +// ECMAScript 6: Collections +// Modules: es6.map, es6.set, es6.weak-map, and es6.weak-set +// ############################################################################################# + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): Map; + size: number; +} + +interface MapConstructor { + new (): Map; + new (iterable: Iterable<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; +} + +interface SetConstructor { + new (): Set; + new (iterable: Iterable): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + add(value: T): WeakSet; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: Iterable): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +// ############################################################################################# +// ECMAScript 6: Iterators +// Modules: es6.string.iterator, es6.array.iterator, es6.map, es6.set, web.dom.iterable +// ############################################################################################# + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Map { + entries(): IterableIterator<[K, V]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[K, V]>; +} + +interface Set { + entries(): IterableIterator<[T, T]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator; +} + +interface $for extends IterableIterator { + of(callbackfn: (value: T, key: any) => void, thisArg?: any): void; + array(): T[]; + array(callbackfn: (value: T, key: any) => U, thisArg?: any): U[]; + filter(callbackfn: (value: T, key: any) => boolean, thisArg?: any): $for; + map(callbackfn: (value: T, key: any) => U, thisArg?: any): $for; +} + +declare function $for(iterable: Iterable): $for; + +// ############################################################################################# +// ECMAScript 6: Promises +// Modules: es6.promise +// ############################################################################################# + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +// ############################################################################################# +// ECMAScript 6: Reflect +// Modules: es6.reflect +// ############################################################################################# + +declare module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +// ############################################################################################# +// ECMAScript 7 +// Modules: es7.array.includes, es7.string.at, es7.string.lpad, es7.string.rpad, +// es7.object.to-array, es7.object.get-own-property-descriptors, es7.regexp.escape, +// es7.map.to-json, and es7.set.to-json +// ############################################################################################# + +interface Array { + includes(value: T, fromIndex?: number): boolean; +} + +interface String { + at(index: number): string; + lpad(length: number, fillStr?: string): string; + rpad(length: number, fillStr?: string): string; +} + +interface ObjectConstructor { + values(object: any): any[]; + entries(object: any): [string, any][]; + getOwnPropertyDescriptors(object: any): PropertyDescriptorMap; +} + +interface RegExpConstructor { + escape(str: string): string; +} + +interface Map { + toJSON(): any; +} + +interface Set { + toJSON(): any; +} + +// ############################################################################################# +// Mozilla JavaScript: Array generics +// Modules: js.array.statics +// ############################################################################################# + +interface ArrayConstructor { + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(array: ArrayLike, ...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(array: ArrayLike): T; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(array: ArrayLike, separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(array: ArrayLike): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(array: ArrayLike): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(array: ArrayLike, start?: number, end?: number): T[]; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(array: ArrayLike, start: number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(array: ArrayLike, ...items: T[]): number; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(array: ArrayLike): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(array: ArrayLike): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(array: ArrayLike): IterableIterator; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; + + includes(array: ArrayLike, value: T, fromIndex?: number): boolean; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; +} + +// ############################################################################################# +// Object - https://github.com/zloirock/core-js/#object +// Modules: core.object +// ############################################################################################# + +interface ObjectConstructor { + /** + * Non-standard. + */ + isObject(value: any): boolean; + + /** + * Non-standard. + */ + classof(value: any): string; + + /** + * Non-standard. + */ + define(target: T, mixin: any): T; + + /** + * Non-standard. + */ + make(proto: T, mixin?: any): T; +} + +// ############################################################################################# +// Console - https://github.com/zloirock/core-js/#console +// Modules: core.log +// ############################################################################################# + +interface Log extends Console { + (message?: any, ...optionalParams: any[]): void; + enable(): void; + disable(): void; +} + +/** + * Non-standard. + */ +declare var log: Log; + +// ############################################################################################# +// Dict - https://github.com/zloirock/core-js/#dict +// Modules: core.dict +// ############################################################################################# + +interface Dict { + [key: string]: T; + [key: number]: T; + //[key: symbol]: T; +} + +interface DictConstructor { + prototype: Dict; + + new (value?: Dict): Dict; + new (value?: any): Dict; + (value?: Dict): Dict; + (value?: any): Dict; + + isDict(value: any): boolean; + values(object: Dict): IterableIterator; + keys(object: Dict): IterableIterator; + entries(object: Dict): IterableIterator<[PropertyKey, T]>; + has(object: Dict, key: PropertyKey): boolean; + get(object: Dict, key: PropertyKey): T; + set(object: Dict, key: PropertyKey, value: T): Dict; + forEach(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => void, thisArg?: any): void; + map(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => U, thisArg?: any): Dict; + mapPairs(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => [PropertyKey, U], thisArg?: any): Dict; + filter(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): Dict; + some(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): boolean; + every(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): boolean; + find(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): T; + findKey(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): PropertyKey; + keyOf(object: Dict, value: T): PropertyKey; + includes(object: Dict, value: T): boolean; + reduce(object: Dict, callbackfn: (previousValue: U, value: T, key: PropertyKey, dict: Dict) => U, initialValue: U): U; + reduce(object: Dict, callbackfn: (previousValue: T, value: T, key: PropertyKey, dict: Dict) => T, initialValue?: T): T; + turn(object: Dict, callbackfn: (memo: Dict, value: T, key: PropertyKey, dict: Dict) => void, memo: Dict): Dict; + turn(object: Dict, callbackfn: (memo: Dict, value: T, key: PropertyKey, dict: Dict) => void, memo?: Dict): Dict; +} + +/** + * Non-standard. + */ +declare var Dict: DictConstructor; + +// ############################################################################################# +// Partial application - https://github.com/zloirock/core-js/#partial-application +// Modules: core.function.part +// ############################################################################################# + +interface Function { + /** + * Non-standard. + */ + part(...args: any[]): any; +} + +// ############################################################################################# +// Date formatting - https://github.com/zloirock/core-js/#date-formatting +// Modules: core.date +// ############################################################################################# + +interface Date { + /** + * Non-standard. + */ + format(template: string, locale?: string): string; + + /** + * Non-standard. + */ + formatUTC(template: string, locale?: string): string; +} + +// ############################################################################################# +// Array - https://github.com/zloirock/core-js/#array +// Modules: core.array.turn +// ############################################################################################# + +interface Array { + /** + * Non-standard. + */ + turn(callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + + /** + * Non-standard. + */ + turn(callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; +} + +// ############################################################################################# +// Number - https://github.com/zloirock/core-js/#number +// Modules: core.number.iterator +// ############################################################################################# + +interface Number { + /** + * Non-standard. + */ + [Symbol.iterator](): IterableIterator; +} + +// ############################################################################################# +// Escaping characters - https://github.com/zloirock/core-js/#escaping-characters +// Modules: core.string.escape-html +// ############################################################################################# + +interface String { + /** + * Non-standard. + */ + escapeHTML(): string; + + /** + * Non-standard. + */ + unescapeHTML(): string; +} + +// ############################################################################################# +// delay - https://github.com/zloirock/core-js/#delay +// Modules: core.delay +// ############################################################################################# + +declare function delay(msec: number): Promise; + +declare module core { + module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: string): boolean; + function has(target: any, propertyKey: symbol): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; + } + + var Object: { + getPrototypeOf(o: any): any; + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + getOwnPropertyNames(o: any): string[]; + create(o: any, properties?: PropertyDescriptorMap): any; + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + defineProperties(o: any, properties: PropertyDescriptorMap): any; + seal(o: T): T; + freeze(o: T): T; + preventExtensions(o: T): T; + isSealed(o: any): boolean; + isFrozen(o: any): boolean; + isExtensible(o: any): boolean; + keys(o: any): string[]; + assign(target: any, ...sources: any[]): any; + is(value1: any, value2: any): boolean; + setPrototypeOf(o: any, proto: any): any; + getOwnPropertySymbols(o: any): symbol[]; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; + values(object: any): any[]; + entries(object: any): any[]; + getOwnPropertyDescriptors(object: any): PropertyDescriptorMap; + isObject(value: any): boolean; + classof(value: any): string; + define(target: T, mixin: any): T; + make(proto: T, mixin?: any): T; + }; + + var Function: { + bind(target: Function, thisArg: any, ...argArray: any[]): any; + part(target: Function, ...args: any[]): any; + }; + + var Array: { + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + from(arrayLike: ArrayLike): Array; + from(iterable: Iterable): Array; + of(...items: T[]): Array; + push(array: ArrayLike, ...items: T[]): number; + pop(array: ArrayLike): T; + concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + join(array: ArrayLike, separator?: string): string; + reverse(array: ArrayLike): T[]; + shift(array: ArrayLike): T; + slice(array: ArrayLike, start?: number, end?: number): T[]; + sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; + splice(array: ArrayLike, start: number): T[]; + splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + unshift(array: ArrayLike, ...items: T[]): number; + indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; + lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; + every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + forEach(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + map(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + entries(array: ArrayLike): IterableIterator<[number, T]>; + keys(array: ArrayLike): IterableIterator; + values(array: ArrayLike): IterableIterator; + find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; + fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; + copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; + includes(array: ArrayLike, value: T, fromIndex?: number): boolean; + turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + }; + + var String: { + codePointAt(text: string, pos: number): number; + includes(text: string, searchString: string, position?: number): boolean; + endsWith(text: string, searchString: string, endPosition?: number): boolean; + repeat(text: string, count: number): string; + fromCodePoint(...codePoints: number[]): string; + raw(template: TemplateStringsArray, ...substitutions: any[]): string; + startsWith(text: string, searchString: string, position?: number): boolean; + at(text: string, index: number): string; + lpad(text: string, length: number, fillStr?: string): string; + rpad(text: string, length: number, fillStr?: string): string; + escapeHTML(text: string): string; + unescapeHTML(text: string): string; + }; + + var Date: { + now(): number; + toISOString(date: Date): string; + format(date: Date, template: string, locale?: string): string; + formatUTC(date: Date, template: string, locale?: string): string; + }; + + var Number: { + EPSILON: number; + isFinite(number: number): boolean; + isInteger(number: number): boolean; + isNaN(number: number): boolean; + isSafeInteger(number: number): boolean; + MAX_SAFE_INTEGER: number; + MIN_SAFE_INTEGER: number; + parseFloat(string: string): number; + parseInt(string: string, radix?: number): number; + clz32(x: number): number; + imul(x: number, y: number): number; + sign(x: number): number; + log10(x: number): number; + log2(x: number): number; + log1p(x: number): number; + expm1(x: number): number; + cosh(x: number): number; + sinh(x: number): number; + tanh(x: number): number; + acosh(x: number): number; + asinh(x: number): number; + atanh(x: number): number; + hypot(...values: number[]): number; + trunc(x: number): number; + fround(x: number): number; + cbrt(x: number): number; + random(lim?: number): number; + }; + + var Math: { + clz32(x: number): number; + imul(x: number, y: number): number; + sign(x: number): number; + log10(x: number): number; + log2(x: number): number; + log1p(x: number): number; + expm1(x: number): number; + cosh(x: number): number; + sinh(x: number): number; + tanh(x: number): number; + acosh(x: number): number; + asinh(x: number): number; + atanh(x: number): number; + hypot(...values: number[]): number; + trunc(x: number): number; + fround(x: number): number; + cbrt(x: number): number; + }; + + var RegExp: { + escape(str: string): string; + }; + + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; + var Promise: PromiseConstructor; + var Symbol: SymbolConstructor; + var Dict: DictConstructor; + var global: any; + var log: Log; + var _: boolean; + + function setTimeout(handler: any, timeout?: any, ...args: any[]): number; + + function setInterval(handler: any, timeout?: any, ...args: any[]): number; + + function setImmediate(expression: any, ...args: any[]): number; + + function clearImmediate(handle: number): void; + + function $for(iterable: Iterable): $for; + + function isIterable(value: any): boolean; + + function getIterator(iterable: Iterable): Iterator; + + interface Locale { + weekdays: string; + months: string; + } + + function addLocale(lang: string, locale: Locale): typeof core; + + function locale(lang?: string): string; + + function delay(msec: number): Promise; +} + +declare module "core-js" { + export = core; +} +declare module "core-js/shim" { + export = core; +} +declare module "core-js/core" { + export = core; +} +declare module "core-js/core/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/core/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/core/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/core/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/core/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/core/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/core/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/core/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/core/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/core/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/core/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/core/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/fn/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/fn/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/fn/clear-immediate" { + var clearImmediate: typeof core.clearImmediate; + export = clearImmediate; +} +declare module "core-js/fn/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/fn/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/fn/get-iterator" { + var getIterator: typeof core.getIterator; + export = getIterator; +} +declare module "core-js/fn/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/fn/is-iterable" { + var isIterable: typeof core.isIterable; + export = isIterable; +} +declare module "core-js/fn/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/fn/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/fn/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/fn/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/fn/set-immediate" { + var setImmediate: typeof core.setImmediate; + export = setImmediate; +} +declare module "core-js/fn/set-interval" { + var setInterval: typeof core.setInterval; + export = setInterval; +} +declare module "core-js/fn/set-timeout" { + var setTimeout: typeof core.setTimeout; + export = setTimeout; +} +declare module "core-js/fn/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/fn/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/fn/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/fn/array/concat" { + var concat: typeof core.Array.concat; + export = concat; +} +declare module "core-js/fn/array/copy-within" { + var copyWithin: typeof core.Array.copyWithin; + export = copyWithin; +} +declare module "core-js/fn/array/entries" { + var entries: typeof core.Array.entries; + export = entries; +} +declare module "core-js/fn/array/every" { + var every: typeof core.Array.every; + export = every; +} +declare module "core-js/fn/array/fill" { + var fill: typeof core.Array.fill; + export = fill; +} +declare module "core-js/fn/array/filter" { + var filter: typeof core.Array.filter; + export = filter; +} +declare module "core-js/fn/array/find" { + var find: typeof core.Array.find; + export = find; +} +declare module "core-js/fn/array/find-index" { + var findIndex: typeof core.Array.findIndex; + export = findIndex; +} +declare module "core-js/fn/array/for-each" { + var forEach: typeof core.Array.forEach; + export = forEach; +} +declare module "core-js/fn/array/from" { + var from: typeof core.Array.from; + export = from; +} +declare module "core-js/fn/array/includes" { + var includes: typeof core.Array.includes; + export = includes; +} +declare module "core-js/fn/array/index-of" { + var indexOf: typeof core.Array.indexOf; + export = indexOf; +} +declare module "core-js/fn/array/join" { + var join: typeof core.Array.join; + export = join; +} +declare module "core-js/fn/array/keys" { + var keys: typeof core.Array.keys; + export = keys; +} +declare module "core-js/fn/array/last-index-of" { + var lastIndexOf: typeof core.Array.lastIndexOf; + export = lastIndexOf; +} +declare module "core-js/fn/array/map" { + var map: typeof core.Array.map; + export = map; +} +declare module "core-js/fn/array/of" { + var of: typeof core.Array.of; + export = of; +} +declare module "core-js/fn/array/pop" { + var pop: typeof core.Array.pop; + export = pop; +} +declare module "core-js/fn/array/push" { + var push: typeof core.Array.push; + export = push; +} +declare module "core-js/fn/array/reduce" { + var reduce: typeof core.Array.reduce; + export = reduce; +} +declare module "core-js/fn/array/reduce-right" { + var reduceRight: typeof core.Array.reduceRight; + export = reduceRight; +} +declare module "core-js/fn/array/reverse" { + var reverse: typeof core.Array.reverse; + export = reverse; +} +declare module "core-js/fn/array/shift" { + var shift: typeof core.Array.shift; + export = shift; +} +declare module "core-js/fn/array/slice" { + var slice: typeof core.Array.slice; + export = slice; +} +declare module "core-js/fn/array/some" { + var some: typeof core.Array.some; + export = some; +} +declare module "core-js/fn/array/sort" { + var sort: typeof core.Array.sort; + export = sort; +} +declare module "core-js/fn/array/splice" { + var splice: typeof core.Array.splice; + export = splice; +} +declare module "core-js/fn/array/turn" { + var turn: typeof core.Array.turn; + export = turn; +} +declare module "core-js/fn/array/unshift" { + var unshift: typeof core.Array.unshift; + export = unshift; +} +declare module "core-js/fn/array/values" { + var values: typeof core.Array.values; + export = values; +} +declare module "core-js/fn/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/fn/date/add-locale" { + var addLocale: typeof core.addLocale; + export = addLocale; +} +declare module "core-js/fn/date/format" { + var format: typeof core.Date.format; + export = format; +} +declare module "core-js/fn/date/formatUTC" { + var formatUTC: typeof core.Date.formatUTC; + export = formatUTC; +} +declare module "core-js/fn/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/fn/function/has-instance" { + var hasInstance: (value: any) => boolean; + export = hasInstance; +} +declare module "core-js/fn/function/name" +{ +} +declare module "core-js/fn/function/part" { + var part: typeof core.Function.part; + export = part; +} +declare module "core-js/fn/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/fn/math/acosh" { + var acosh: typeof core.Math.acosh; + export = acosh; +} +declare module "core-js/fn/math/asinh" { + var asinh: typeof core.Math.asinh; + export = asinh; +} +declare module "core-js/fn/math/atanh" { + var atanh: typeof core.Math.atanh; + export = atanh; +} +declare module "core-js/fn/math/cbrt" { + var cbrt: typeof core.Math.cbrt; + export = cbrt; +} +declare module "core-js/fn/math/clz32" { + var clz32: typeof core.Math.clz32; + export = clz32; +} +declare module "core-js/fn/math/cosh" { + var cosh: typeof core.Math.cosh; + export = cosh; +} +declare module "core-js/fn/math/expm1" { + var expm1: typeof core.Math.expm1; + export = expm1; +} +declare module "core-js/fn/math/fround" { + var fround: typeof core.Math.fround; + export = fround; +} +declare module "core-js/fn/math/hypot" { + var hypot: typeof core.Math.hypot; + export = hypot; +} +declare module "core-js/fn/math/imul" { + var imul: typeof core.Math.imul; + export = imul; +} +declare module "core-js/fn/math/log10" { + var log10: typeof core.Math.log10; + export = log10; +} +declare module "core-js/fn/math/log1p" { + var log1p: typeof core.Math.log1p; + export = log1p; +} +declare module "core-js/fn/math/log2" { + var log2: typeof core.Math.log2; + export = log2; +} +declare module "core-js/fn/math/sign" { + var sign: typeof core.Math.sign; + export = sign; +} +declare module "core-js/fn/math/sinh" { + var sinh: typeof core.Math.sinh; + export = sinh; +} +declare module "core-js/fn/math/tanh" { + var tanh: typeof core.Math.tanh; + export = tanh; +} +declare module "core-js/fn/math/trunc" { + var trunc: typeof core.Math.trunc; + export = trunc; +} +declare module "core-js/fn/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/fn/number/epsilon" { + var EPSILON: typeof core.Number.EPSILON; + export = EPSILON; +} +declare module "core-js/fn/number/is-finite" { + var isFinite: typeof core.Number.isFinite; + export = isFinite; +} +declare module "core-js/fn/number/is-integer" { + var isInteger: typeof core.Number.isInteger; + export = isInteger; +} +declare module "core-js/fn/number/is-nan" { + var isNaN: typeof core.Number.isNaN; + export = isNaN; +} +declare module "core-js/fn/number/is-safe-integer" { + var isSafeInteger: typeof core.Number.isSafeInteger; + export = isSafeInteger; +} +declare module "core-js/fn/number/max-safe-integer" { + var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; + export = MAX_SAFE_INTEGER; +} +declare module "core-js/fn/number/min-safe-interger" { + var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; + export = MIN_SAFE_INTEGER; +} +declare module "core-js/fn/number/parse-float" { + var parseFloat: typeof core.Number.parseFloat; + export = parseFloat; +} +declare module "core-js/fn/number/parse-int" { + var parseInt: typeof core.Number.parseInt; + export = parseInt; +} +declare module "core-js/fn/number/random" { + var random: typeof core.Number.random; + export = random; +} +declare module "core-js/fn/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/fn/object/assign" { + var assign: typeof core.Object.assign; + export = assign; +} +declare module "core-js/fn/object/classof" { + var classof: typeof core.Object.classof; + export = classof; +} +declare module "core-js/fn/object/create" { + var create: typeof core.Object.create; + export = create; +} +declare module "core-js/fn/object/define" { + var define: typeof core.Object.define; + export = define; +} +declare module "core-js/fn/object/define-properties" { + var defineProperties: typeof core.Object.defineProperties; + export = defineProperties; +} +declare module "core-js/fn/object/define-property" { + var defineProperty: typeof core.Object.defineProperty; + export = defineProperty; +} +declare module "core-js/fn/object/entries" { + var entries: typeof core.Object.entries; + export = entries; +} +declare module "core-js/fn/object/freeze" { + var freeze: typeof core.Object.freeze; + export = freeze; +} +declare module "core-js/fn/object/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Object.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/fn/object/get-own-property-descriptors" { + var getOwnPropertyDescriptors: typeof core.Object.getOwnPropertyDescriptors; + export = getOwnPropertyDescriptors; +} +declare module "core-js/fn/object/get-own-property-names" { + var getOwnPropertyNames: typeof core.Object.getOwnPropertyNames; + export = getOwnPropertyNames; +} +declare module "core-js/fn/object/get-own-property-symbols" { + var getOwnPropertySymbols: typeof core.Object.getOwnPropertySymbols; + export = getOwnPropertySymbols; +} +declare module "core-js/fn/object/get-prototype-of" { + var getPrototypeOf: typeof core.Object.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/fn/object/is" { + var is: typeof core.Object.is; + export = is; +} +declare module "core-js/fn/object/is-extensible" { + var isExtensible: typeof core.Object.isExtensible; + export = isExtensible; +} +declare module "core-js/fn/object/is-frozen" { + var isFrozen: typeof core.Object.isFrozen; + export = isFrozen; +} +declare module "core-js/fn/object/is-object" { + var isObject: typeof core.Object.isObject; + export = isObject; +} +declare module "core-js/fn/object/is-sealed" { + var isSealed: typeof core.Object.isSealed; + export = isSealed; +} +declare module "core-js/fn/object/keys" { + var keys: typeof core.Object.keys; + export = keys; +} +declare module "core-js/fn/object/make" { + var make: typeof core.Object.make; + export = make; +} +declare module "core-js/fn/object/prevent-extensions" { + var preventExtensions: typeof core.Object.preventExtensions; + export = preventExtensions; +} +declare module "core-js/fn/object/seal" { + var seal: typeof core.Object.seal; + export = seal; +} +declare module "core-js/fn/object/set-prototype-of" { + var setPrototypeOf: typeof core.Object.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/fn/object/values" { + var values: typeof core.Object.values; + export = values; +} +declare module "core-js/fn/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/fn/reflect/apply" { + var apply: typeof core.Reflect.apply; + export = apply; +} +declare module "core-js/fn/reflect/construct" { + var construct: typeof core.Reflect.construct; + export = construct; +} +declare module "core-js/fn/reflect/define-property" { + var defineProperty: typeof core.Reflect.defineProperty; + export = defineProperty; +} +declare module "core-js/fn/reflect/delete-property" { + var deleteProperty: typeof core.Reflect.deleteProperty; + export = deleteProperty; +} +declare module "core-js/fn/reflect/enumerate" { + var enumerate: typeof core.Reflect.enumerate; + export = enumerate; +} +declare module "core-js/fn/reflect/get" { + var get: typeof core.Reflect.get; + export = get; +} +declare module "core-js/fn/reflect/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Reflect.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/fn/reflect/get-prototype-of" { + var getPrototypeOf: typeof core.Reflect.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/fn/reflect/has" { + var has: typeof core.Reflect.has; + export = has; +} +declare module "core-js/fn/reflect/is-extensible" { + var isExtensible: typeof core.Reflect.isExtensible; + export = isExtensible; +} +declare module "core-js/fn/reflect/own-keys" { + var ownKeys: typeof core.Reflect.ownKeys; + export = ownKeys; +} +declare module "core-js/fn/reflect/prevent-extensions" { + var preventExtensions: typeof core.Reflect.preventExtensions; + export = preventExtensions; +} +declare module "core-js/fn/reflect/set" { + var set: typeof core.Reflect.set; + export = set; +} +declare module "core-js/fn/reflect/set-prototype-of" { + var setPrototypeOf: typeof core.Reflect.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/fn/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/fn/regexp/escape" { + var escape: typeof core.RegExp.escape; + export = escape; +} +declare module "core-js/fn/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/fn/string/at" { + var at: typeof core.String.at; + export = at; +} +declare module "core-js/fn/string/code-point-at" { + var codePointAt: typeof core.String.codePointAt; + export = codePointAt; +} +declare module "core-js/fn/string/ends-with" { + var endsWith: typeof core.String.endsWith; + export = endsWith; +} +declare module "core-js/fn/string/escape-html" { + var escapeHTML: typeof core.String.escapeHTML; + export = escapeHTML; +} +declare module "core-js/fn/string/from-code-point" { + var fromCodePoint: typeof core.String.fromCodePoint; + export = fromCodePoint; +} +declare module "core-js/fn/string/includes" { + var includes: typeof core.String.includes; + export = includes; +} +declare module "core-js/fn/string/lpad" { + var lpad: typeof core.String.lpad; + export = lpad; +} +declare module "core-js/fn/string/raw" { + var raw: typeof core.String.raw; + export = raw; +} +declare module "core-js/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export = repeat; +} +declare module "core-js/fn/string/rpad" { + var rpad: typeof core.String.rpad; + export = rpad; +} +declare module "core-js/fn/string/starts-with" { + var startsWith: typeof core.String.startsWith; + export = startsWith; +} +declare module "core-js/fn/string/unescape-html" { + var unescapeHTML: typeof core.String.unescapeHTML; + export = unescapeHTML; +} +declare module "core-js/fn/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/fn/symbol/for" { + var _for: typeof core.Symbol.for; + export = _for; +} +declare module "core-js/fn/symbol/has-instance" { + var hasInstance: typeof core.Symbol.hasInstance; + export = hasInstance; +} +declare module "core-js/fn/symbol/is-concat-spreadable" { + var isConcatSpreadable: typeof core.Symbol.isConcatSpreadable; + export = isConcatSpreadable; +} +declare module "core-js/fn/symbol/iterator" { + var iterator: typeof core.Symbol.iterator; + export = iterator; +} +declare module "core-js/fn/symbol/key-for" { + var keyFor: typeof core.Symbol.keyFor; + export = keyFor; +} +declare module "core-js/fn/symbol/match" { + var match: typeof core.Symbol.match; + export = match; +} +declare module "core-js/fn/symbol/replace" { + var replace: typeof core.Symbol.replace; + export = replace; +} +declare module "core-js/fn/symbol/search" { + var search: typeof core.Symbol.search; + export = search; +} +declare module "core-js/fn/symbol/species" { + var species: typeof core.Symbol.species; + export = species; +} +declare module "core-js/fn/symbol/split" { + var split: typeof core.Symbol.split; + export = split; +} +declare module "core-js/fn/symbol/to-primitive" { + var toPrimitive: typeof core.Symbol.toPrimitive; + export = toPrimitive; +} +declare module "core-js/fn/symbol/to-string-tag" { + var toStringTag: typeof core.Symbol.toStringTag; + export = toStringTag; +} +declare module "core-js/fn/symbol/unscopables" { + var unscopables: typeof core.Symbol.unscopables; + export = unscopables; +} +declare module "core-js/es5" { + export = core; +} +declare module "core-js/es6" { + export = core; +} +declare module "core-js/es6/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/es6/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/es6/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/es6/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/es6/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/es6/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/es6/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/es6/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/es6/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/es6/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/es6/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/es6/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/es6/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/es6/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/es7" { + export = core; +} +declare module "core-js/es7/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/es7/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/es7/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/es7/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/es7/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/es7/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/js" { + export = core; +} +declare module "core-js/js/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/web" { + export = core; +} +declare module "core-js/web/dom" { + export = core; +} +declare module "core-js/web/immediate" { + export = core; +} +declare module "core-js/web/timers" { + export = core; +} +declare module "core-js/libary" { + export = core; +} +declare module "core-js/libary/shim" { + export = core; +} +declare module "core-js/libary/core" { + export = core; +} +declare module "core-js/libary/core/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/libary/core/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/libary/core/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/core/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/libary/core/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/libary/core/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/libary/core/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/core/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/libary/core/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/libary/core/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/core/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/core/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/fn/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/libary/fn/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/libary/fn/clear-immediate" { + var clearImmediate: typeof core.clearImmediate; + export = clearImmediate; +} +declare module "core-js/libary/fn/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/libary/fn/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/libary/fn/get-iterator" { + var getIterator: typeof core.getIterator; + export = getIterator; +} +declare module "core-js/libary/fn/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/libary/fn/is-iterable" { + var isIterable: typeof core.isIterable; + export = isIterable; +} +declare module "core-js/libary/fn/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/libary/fn/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/fn/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/libary/fn/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/fn/set-immediate" { + var setImmediate: typeof core.setImmediate; + export = setImmediate; +} +declare module "core-js/libary/fn/set-interval" { + var setInterval: typeof core.setInterval; + export = setInterval; +} +declare module "core-js/libary/fn/set-timeout" { + var setTimeout: typeof core.setTimeout; + export = setTimeout; +} +declare module "core-js/libary/fn/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/libary/fn/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/libary/fn/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/fn/array/concat" { + var concat: typeof core.Array.concat; + export = concat; +} +declare module "core-js/libary/fn/array/copy-within" { + var copyWithin: typeof core.Array.copyWithin; + export = copyWithin; +} +declare module "core-js/libary/fn/array/entries" { + var entries: typeof core.Array.entries; + export = entries; +} +declare module "core-js/libary/fn/array/every" { + var every: typeof core.Array.every; + export = every; +} +declare module "core-js/libary/fn/array/fill" { + var fill: typeof core.Array.fill; + export = fill; +} +declare module "core-js/libary/fn/array/filter" { + var filter: typeof core.Array.filter; + export = filter; +} +declare module "core-js/libary/fn/array/find" { + var find: typeof core.Array.find; + export = find; +} +declare module "core-js/libary/fn/array/find-index" { + var findIndex: typeof core.Array.findIndex; + export = findIndex; +} +declare module "core-js/libary/fn/array/for-each" { + var forEach: typeof core.Array.forEach; + export = forEach; +} +declare module "core-js/libary/fn/array/from" { + var from: typeof core.Array.from; + export = from; +} +declare module "core-js/libary/fn/array/includes" { + var includes: typeof core.Array.includes; + export = includes; +} +declare module "core-js/libary/fn/array/index-of" { + var indexOf: typeof core.Array.indexOf; + export = indexOf; +} +declare module "core-js/libary/fn/array/join" { + var join: typeof core.Array.join; + export = join; +} +declare module "core-js/libary/fn/array/keys" { + var keys: typeof core.Array.keys; + export = keys; +} +declare module "core-js/libary/fn/array/last-index-of" { + var lastIndexOf: typeof core.Array.lastIndexOf; + export = lastIndexOf; +} +declare module "core-js/libary/fn/array/map" { + var map: typeof core.Array.map; + export = map; +} +declare module "core-js/libary/fn/array/of" { + var of: typeof core.Array.of; + export = of; +} +declare module "core-js/libary/fn/array/pop" { + var pop: typeof core.Array.pop; + export = pop; +} +declare module "core-js/libary/fn/array/push" { + var push: typeof core.Array.push; + export = push; +} +declare module "core-js/libary/fn/array/reduce" { + var reduce: typeof core.Array.reduce; + export = reduce; +} +declare module "core-js/libary/fn/array/reduce-right" { + var reduceRight: typeof core.Array.reduceRight; + export = reduceRight; +} +declare module "core-js/libary/fn/array/reverse" { + var reverse: typeof core.Array.reverse; + export = reverse; +} +declare module "core-js/libary/fn/array/shift" { + var shift: typeof core.Array.shift; + export = shift; +} +declare module "core-js/libary/fn/array/slice" { + var slice: typeof core.Array.slice; + export = slice; +} +declare module "core-js/libary/fn/array/some" { + var some: typeof core.Array.some; + export = some; +} +declare module "core-js/libary/fn/array/sort" { + var sort: typeof core.Array.sort; + export = sort; +} +declare module "core-js/libary/fn/array/splice" { + var splice: typeof core.Array.splice; + export = splice; +} +declare module "core-js/libary/fn/array/turn" { + var turn: typeof core.Array.turn; + export = turn; +} +declare module "core-js/libary/fn/array/unshift" { + var unshift: typeof core.Array.unshift; + export = unshift; +} +declare module "core-js/libary/fn/array/values" { + var values: typeof core.Array.values; + export = values; +} +declare module "core-js/libary/fn/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/libary/fn/date/add-locale" { + var addLocale: typeof core.addLocale; + export = addLocale; +} +declare module "core-js/libary/fn/date/format" { + var format: typeof core.Date.format; + export = format; +} +declare module "core-js/libary/fn/date/formatUTC" { + var formatUTC: typeof core.Date.formatUTC; + export = formatUTC; +} +declare module "core-js/libary/fn/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/fn/function/has-instance" { + var hasInstance: (value: any) => boolean; + export = hasInstance; +} +declare module "core-js/libary/fn/function/name" { +} +declare module "core-js/libary/fn/function/part" { + var part: typeof core.Function.part; + export = part; +} +declare module "core-js/libary/fn/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/libary/fn/math/acosh" { + var acosh: typeof core.Math.acosh; + export = acosh; +} +declare module "core-js/libary/fn/math/asinh" { + var asinh: typeof core.Math.asinh; + export = asinh; +} +declare module "core-js/libary/fn/math/atanh" { + var atanh: typeof core.Math.atanh; + export = atanh; +} +declare module "core-js/libary/fn/math/cbrt" { + var cbrt: typeof core.Math.cbrt; + export = cbrt; +} +declare module "core-js/libary/fn/math/clz32" { + var clz32: typeof core.Math.clz32; + export = clz32; +} +declare module "core-js/libary/fn/math/cosh" { + var cosh: typeof core.Math.cosh; + export = cosh; +} +declare module "core-js/libary/fn/math/expm1" { + var expm1: typeof core.Math.expm1; + export = expm1; +} +declare module "core-js/libary/fn/math/fround" { + var fround: typeof core.Math.fround; + export = fround; +} +declare module "core-js/libary/fn/math/hypot" { + var hypot: typeof core.Math.hypot; + export = hypot; +} +declare module "core-js/libary/fn/math/imul" { + var imul: typeof core.Math.imul; + export = imul; +} +declare module "core-js/libary/fn/math/log10" { + var log10: typeof core.Math.log10; + export = log10; +} +declare module "core-js/libary/fn/math/log1p" { + var log1p: typeof core.Math.log1p; + export = log1p; +} +declare module "core-js/libary/fn/math/log2" { + var log2: typeof core.Math.log2; + export = log2; +} +declare module "core-js/libary/fn/math/sign" { + var sign: typeof core.Math.sign; + export = sign; +} +declare module "core-js/libary/fn/math/sinh" { + var sinh: typeof core.Math.sinh; + export = sinh; +} +declare module "core-js/libary/fn/math/tanh" { + var tanh: typeof core.Math.tanh; + export = tanh; +} +declare module "core-js/libary/fn/math/trunc" { + var trunc: typeof core.Math.trunc; + export = trunc; +} +declare module "core-js/libary/fn/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/fn/number/epsilon" { + var EPSILON: typeof core.Number.EPSILON; + export = EPSILON; +} +declare module "core-js/libary/fn/number/is-finite" { + var isFinite: typeof core.Number.isFinite; + export = isFinite; +} +declare module "core-js/libary/fn/number/is-integer" { + var isInteger: typeof core.Number.isInteger; + export = isInteger; +} +declare module "core-js/libary/fn/number/is-nan" { + var isNaN: typeof core.Number.isNaN; + export = isNaN; +} +declare module "core-js/libary/fn/number/is-safe-integer" { + var isSafeInteger: typeof core.Number.isSafeInteger; + export = isSafeInteger; +} +declare module "core-js/libary/fn/number/max-safe-integer" { + var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; + export = MAX_SAFE_INTEGER; +} +declare module "core-js/libary/fn/number/min-safe-interger" { + var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; + export = MIN_SAFE_INTEGER; +} +declare module "core-js/libary/fn/number/parse-float" { + var parseFloat: typeof core.Number.parseFloat; + export = parseFloat; +} +declare module "core-js/libary/fn/number/parse-int" { + var parseInt: typeof core.Number.parseInt; + export = parseInt; +} +declare module "core-js/libary/fn/number/random" { + var random: typeof core.Number.random; + export = random; +} +declare module "core-js/libary/fn/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/fn/object/assign" { + var assign: typeof core.Object.assign; + export = assign; +} +declare module "core-js/libary/fn/object/classof" { + var classof: typeof core.Object.classof; + export = classof; +} +declare module "core-js/libary/fn/object/create" { + var create: typeof core.Object.create; + export = create; +} +declare module "core-js/libary/fn/object/define" { + var define: typeof core.Object.define; + export = define; +} +declare module "core-js/libary/fn/object/define-properties" { + var defineProperties: typeof core.Object.defineProperties; + export = defineProperties; +} +declare module "core-js/libary/fn/object/define-property" { + var defineProperty: typeof core.Object.defineProperty; + export = defineProperty; +} +declare module "core-js/libary/fn/object/entries" { + var entries: typeof core.Object.entries; + export = entries; +} +declare module "core-js/libary/fn/object/freeze" { + var freeze: typeof core.Object.freeze; + export = freeze; +} +declare module "core-js/libary/fn/object/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Object.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/libary/fn/object/get-own-property-descriptors" { + var getOwnPropertyDescriptors: typeof core.Object.getOwnPropertyDescriptors; + export = getOwnPropertyDescriptors; +} +declare module "core-js/libary/fn/object/get-own-property-names" { + var getOwnPropertyNames: typeof core.Object.getOwnPropertyNames; + export = getOwnPropertyNames; +} +declare module "core-js/libary/fn/object/get-own-property-symbols" { + var getOwnPropertySymbols: typeof core.Object.getOwnPropertySymbols; + export = getOwnPropertySymbols; +} +declare module "core-js/libary/fn/object/get-prototype-of" { + var getPrototypeOf: typeof core.Object.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/libary/fn/object/is" { + var is: typeof core.Object.is; + export = is; +} +declare module "core-js/libary/fn/object/is-extensible" { + var isExtensible: typeof core.Object.isExtensible; + export = isExtensible; +} +declare module "core-js/libary/fn/object/is-frozen" { + var isFrozen: typeof core.Object.isFrozen; + export = isFrozen; +} +declare module "core-js/libary/fn/object/is-object" { + var isObject: typeof core.Object.isObject; + export = isObject; +} +declare module "core-js/libary/fn/object/is-sealed" { + var isSealed: typeof core.Object.isSealed; + export = isSealed; +} +declare module "core-js/libary/fn/object/keys" { + var keys: typeof core.Object.keys; + export = keys; +} +declare module "core-js/libary/fn/object/make" { + var make: typeof core.Object.make; + export = make; +} +declare module "core-js/libary/fn/object/prevent-extensions" { + var preventExtensions: typeof core.Object.preventExtensions; + export = preventExtensions; +} +declare module "core-js/libary/fn/object/seal" { + var seal: typeof core.Object.seal; + export = seal; +} +declare module "core-js/libary/fn/object/set-prototype-of" { + var setPrototypeOf: typeof core.Object.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/libary/fn/object/values" { + var values: typeof core.Object.values; + export = values; +} +declare module "core-js/libary/fn/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/libary/fn/reflect/apply" { + var apply: typeof core.Reflect.apply; + export = apply; +} +declare module "core-js/libary/fn/reflect/construct" { + var construct: typeof core.Reflect.construct; + export = construct; +} +declare module "core-js/libary/fn/reflect/define-property" { + var defineProperty: typeof core.Reflect.defineProperty; + export = defineProperty; +} +declare module "core-js/libary/fn/reflect/delete-property" { + var deleteProperty: typeof core.Reflect.deleteProperty; + export = deleteProperty; +} +declare module "core-js/libary/fn/reflect/enumerate" { + var enumerate: typeof core.Reflect.enumerate; + export = enumerate; +} +declare module "core-js/libary/fn/reflect/get" { + var get: typeof core.Reflect.get; + export = get; +} +declare module "core-js/libary/fn/reflect/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Reflect.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/libary/fn/reflect/get-prototype-of" { + var getPrototypeOf: typeof core.Reflect.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/libary/fn/reflect/has" { + var has: typeof core.Reflect.has; + export = has; +} +declare module "core-js/libary/fn/reflect/is-extensible" { + var isExtensible: typeof core.Reflect.isExtensible; + export = isExtensible; +} +declare module "core-js/libary/fn/reflect/own-keys" { + var ownKeys: typeof core.Reflect.ownKeys; + export = ownKeys; +} +declare module "core-js/libary/fn/reflect/prevent-extensions" { + var preventExtensions: typeof core.Reflect.preventExtensions; + export = preventExtensions; +} +declare module "core-js/libary/fn/reflect/set" { + var set: typeof core.Reflect.set; + export = set; +} +declare module "core-js/libary/fn/reflect/set-prototype-of" { + var setPrototypeOf: typeof core.Reflect.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/libary/fn/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/fn/regexp/escape" { + var escape: typeof core.RegExp.escape; + export = escape; +} +declare module "core-js/libary/fn/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/fn/string/at" { + var at: typeof core.String.at; + export = at; +} +declare module "core-js/libary/fn/string/code-point-at" { + var codePointAt: typeof core.String.codePointAt; + export = codePointAt; +} +declare module "core-js/libary/fn/string/ends-with" { + var endsWith: typeof core.String.endsWith; + export = endsWith; +} +declare module "core-js/libary/fn/string/escape-html" { + var escapeHTML: typeof core.String.escapeHTML; + export = escapeHTML; +} +declare module "core-js/libary/fn/string/from-code-point" { + var fromCodePoint: typeof core.String.fromCodePoint; + export = fromCodePoint; +} +declare module "core-js/libary/fn/string/includes" { + var includes: typeof core.String.includes; + export = includes; +} +declare module "core-js/libary/fn/string/lpad" { + var lpad: typeof core.String.lpad; + export = lpad; +} +declare module "core-js/libary/fn/string/raw" { + var raw: typeof core.String.raw; + export = raw; +} +declare module "core-js/libary/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export = repeat; +} +declare module "core-js/libary/fn/string/rpad" { + var rpad: typeof core.String.rpad; + export = rpad; +} +declare module "core-js/libary/fn/string/starts-with" { + var startsWith: typeof core.String.startsWith; + export = startsWith; +} +declare module "core-js/libary/fn/string/unescape-html" { + var unescapeHTML: typeof core.String.unescapeHTML; + export = unescapeHTML; +} +declare module "core-js/libary/fn/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/libary/fn/symbol/for" { + var _for: typeof core.Symbol.for; + export = _for; +} +declare module "core-js/libary/fn/symbol/has-instance" { + var hasInstance: typeof core.Symbol.hasInstance; + export = hasInstance; +} +declare module "core-js/libary/fn/symbol/is-concat-spreadable" { + var isConcatSpreadable: typeof core.Symbol.isConcatSpreadable; + export = isConcatSpreadable; +} +declare module "core-js/libary/fn/symbol/iterator" { + var iterator: typeof core.Symbol.iterator; + export = iterator; +} +declare module "core-js/libary/fn/symbol/key-for" { + var keyFor: typeof core.Symbol.keyFor; + export = keyFor; +} +declare module "core-js/libary/fn/symbol/match" { + var match: typeof core.Symbol.match; + export = match; +} +declare module "core-js/libary/fn/symbol/replace" { + var replace: typeof core.Symbol.replace; + export = replace; +} +declare module "core-js/libary/fn/symbol/search" { + var search: typeof core.Symbol.search; + export = search; +} +declare module "core-js/libary/fn/symbol/species" { + var species: typeof core.Symbol.species; + export = species; +} +declare module "core-js/libary/fn/symbol/split" { + var split: typeof core.Symbol.split; + export = split; +} +declare module "core-js/libary/fn/symbol/to-primitive" { + var toPrimitive: typeof core.Symbol.toPrimitive; + export = toPrimitive; +} +declare module "core-js/libary/fn/symbol/to-string-tag" { + var toStringTag: typeof core.Symbol.toStringTag; + export = toStringTag; +} +declare module "core-js/libary/fn/symbol/unscopables" { + var unscopables: typeof core.Symbol.unscopables; + export = unscopables; +} +declare module "core-js/libary/es5" { + export = core; +} +declare module "core-js/libary/es6" { + export = core; +} +declare module "core-js/libary/es6/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/es6/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/es6/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/es6/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/libary/es6/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/es6/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/es6/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/libary/es6/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/libary/es6/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/es6/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/es6/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/es6/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/libary/es6/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/libary/es6/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/libary/es7" { + export = core; +} +declare module "core-js/libary/es7/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/es7/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/es7/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/es7/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/es7/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/es7/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/js" { + export = core; +} +declare module "core-js/libary/js/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/web" { + export = core; +} +declare module "core-js/libary/web/dom" { + export = core; +} +declare module "core-js/libary/web/immediate" { + export = core; +} +declare module "core-js/libary/web/timers" { + export = core; +} diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 37719a5f4..50d6fbdaa 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -2810,7 +2810,7 @@ declare module d3 { nodes(root: T): T[]; - links(nodes: T[]): cluster.Link; + links(nodes: T[]): cluster.Link[]; children(): (node: T) => T[]; children(accessor: (node: T) => T[]): Cluster; diff --git a/dojo/dojox.widget.d.ts b/dojo/dojox.widget.d.ts index dbcc6083b..afbb2eed5 100644 --- a/dojo/dojox.widget.d.ts +++ b/dojo/dojox.widget.d.ts @@ -23018,7 +23018,7 @@ declare module dojox { */ class PortletSettings extends dijit._Container implements dijit.layout.ContentPane { constructor(params?: Object, srcNodeRef?: HTMLElement); - inherited: { (arguments: IArguments): any }; + inherited: { (args: IArguments): any }; /** * Custom press, release, and click synthetic events * which trigger on a left mouse click, touch, or space/enter keyup. diff --git a/drop/drop-tests.ts b/drop/drop-tests.ts index 22f83dc2e..cc19621fb 100644 --- a/drop/drop-tests.ts +++ b/drop/drop-tests.ts @@ -25,10 +25,10 @@ d.destroy(); d.element.appendChild(document.createElement("div")); d.tether.position(); -d.on("open", () => null); -d.on("close", () => null); -d.once("close", () => null); -d.off("close", () => null); +d.on("open", () => false); +d.on("close", () => false); +d.once("close", () => false); +d.off("close", () => false); d.off("open"); var e = new Drop({ diff --git a/ember/ember.d.ts b/ember/ember.d.ts index a1b829ddf..00ea077dd 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1420,7 +1420,7 @@ declare module Ember { Creates an instance of the class. @param arguments A hash containing values with which to initialize the newly instantiated object. **/ - static create(...arguments: CoreObjectArguments[]): T; + static create(...args: CoreObjectArguments[]): T; detect(obj: any): boolean; reopen(args?: {}): T; } diff --git a/emscripten/emscripten-tests.ts b/emscripten/emscripten-tests.ts index 2f3a2b09c..0a614a540 100644 --- a/emscripten/emscripten-tests.ts +++ b/emscripten/emscripten-tests.ts @@ -50,7 +50,7 @@ function FSTest(): void { FS.symlink('file', 'link'); FS.writeFile('forbidden', 'can\'t touch this'); - FS.chmod('forbidden', 0000); + FS.chmod('forbidden', parseInt("0000", 8)); FS.writeFile('file', 'foobar'); FS.truncate('file', 3); diff --git a/es6-collections/es6-collections-tests.ts b/es6-collections/es6-collections-tests.ts new file mode 100644 index 000000000..256994272 --- /dev/null +++ b/es6-collections/es6-collections-tests.ts @@ -0,0 +1,59 @@ +/// + +interface Point { x: number; y: number; } +let a: any; +let s: string; +let b: boolean; +let i: number; +let pt: Point; +let arrayOfPoint: Point[]; +let arrayOfStringPoint: [string, Point][]; +let arrayOfPointString: [Point, string][]; +let map: Map; +let set: Set; +let weakMap: WeakMap; +let weakSet: WeakSet; +let iteratorOfString: Iterator; +let iteratorOfStringPoint: Iterator<[String, Point]>; +let iteratorOfPoint: Iterator; +let iteratorOfPointPoint: Iterator<[Point, Point]>; + +map = new Map(); +map = new Map(arrayOfStringPoint); +map.clear(); +b = map.delete(s); +map.forEach((value: Point, key: string, map: Map) => { }, a); +pt = map.get(s); +b = map.has(s); +map = map.set(s, pt); +iteratorOfStringPoint = map.entries(); +iteratorOfString = map.keys(); +iteratorOfPoint = map.values(); +i = map.size; + +set = new Set(); +set = new Set(arrayOfPoint); +set.clear(); +b = set.delete(pt); +set.forEach((value: Point, key: Point, set: Set) => { }, a); +b = set.has(pt); +set = set.add(pt); +iteratorOfPointPoint = set.entries(); +iteratorOfPoint = set.keys(); +iteratorOfPoint = set.values(); +i = set.size; + +weakMap = new WeakMap(); +weakMap = new WeakMap(arrayOfPointString); +weakMap.clear(); +b = weakMap.delete(pt); +s = weakMap.get(pt); +b = weakMap.has(pt); +weakMap = weakMap.set(pt, s); + +weakSet = new WeakSet(); +weakSet = new WeakSet(arrayOfPoint); +weakSet.clear(); +b = weakSet.delete(pt); +b = weakSet.has(pt); +weakSet = weakSet.add(pt); \ No newline at end of file diff --git a/es6-collections/es6-collections-tests.ts.tscparams b/es6-collections/es6-collections-tests.ts.tscparams new file mode 100644 index 000000000..4169d3605 --- /dev/null +++ b/es6-collections/es6-collections-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --target es5 \ No newline at end of file diff --git a/es6-collections/es6-collections.d.ts b/es6-collections/es6-collections.d.ts new file mode 100644 index 000000000..54bcbca01 --- /dev/null +++ b/es6-collections/es6-collections.d.ts @@ -0,0 +1,113 @@ +// Type definitions for es6-collections v0.5.1 +// Project: https://github.com/WebReflection/es6-collections/ +// Definitions by: Ron Buckton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface ForEachable { + forEach(callbackfn: (value: T) => void): void; +} + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): Map; + entries(): Iterator<[K, V]>; + keys(): Iterator; + values(): Iterator; + size: number; +} + +interface MapConstructor { + new (): Map; + new (iterable: ForEachable<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + entries(): Iterator<[T, T]>; + keys(): Iterator; + values(): Iterator; + size: number; +} + +interface SetConstructor { + new (): Set; + new (iterable: ForEachable): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + clear(): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: ForEachable<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + delete(value: T): boolean; + clear(): void; + add(value: T): WeakSet; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: ForEachable): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +declare module "es6-collections" { + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; +} \ No newline at end of file diff --git a/es6-shim/es6-shim-tests.ts b/es6-shim/es6-shim-tests.ts new file mode 100644 index 000000000..3bcb0ba7d --- /dev/null +++ b/es6-shim/es6-shim-tests.ts @@ -0,0 +1,222 @@ +/// + +interface Point { x: number; y: number; } +interface Point3D extends Point { z: number; } + +let a: any; +let s: string; +let i: number; +let b: boolean; +let f: () => void; +let o: Object; +let r: RegExp; +let sym: symbol; +let e: Error; +let date: Date; +let key: PropertyKey; +let point: Point; +let point3d: Point3D; +let arrayOfPoint: Point[]; +let arrayOfPoint3D: Point3D[]; +let arrayOfSymbol: symbol[]; +let arrayOfPropertyKey: PropertyKey[]; +let arrayOfAny: any[]; +let arrayOfStringAny: [string, any][]; +let arrayLikeOfAny: ArrayLike; +let iterableOfPoint: IterableShim; +let iterableOfStringPoint: IterableShim<[string, Point]>; +let iterableOfPointPoint3D: IterableShim<[Point, Point3D]>; +let iterableIteratorOfPoint: IterableIteratorShim; +let iterableIteratorOfNumberPoint: IterableIteratorShim<[number, Point]>; +let iterableIteratorOfNumber: IterableIteratorShim; +let iterableIteratorOfString: IterableIteratorShim; +let iterableIteratorOfPointPoint: IterableIteratorShim<[Point, Point]>; +let iterableIteratorOfNode: IterableIteratorShim; +let iterableIteratorOfStringPoint: IterableIteratorShim<[string, Point]>; +let iterableIteratorOfAny: IterableIteratorShim; +let iterableIteratorOfPropertyKey: IterableIteratorShim; +let iterableIteratorOfPropertyKeyPoint: IterableIteratorShim<[PropertyKey, Point]>; +let nodeList: NodeList; +let pd: PropertyDescriptor; +let pdm: PropertyDescriptorMap; +let map: Map; +let set: Set; +let weakMap: WeakMap; +let weakSet: WeakSet; +let promiseLikeOfPoint: PromiseLike; +let promiseLikeOfPoint3D: PromiseLike; +let promiseOfPoint: Promise; +let promiseOfPoint3D: Promise; +let promiseOfArrayOfPoint: Promise; +let promiseOfVoid: Promise; + +point = Object.assign(point, point); +b = Object.is(point, point); +Object.setPrototypeOf(point, point); +point = arrayOfPoint.find(p => b); +i = arrayOfPoint.findIndex(p => b); +arrayOfPoint = arrayOfPoint.fill(point, i, arrayOfPoint.length); +arrayOfPoint = arrayOfPoint.copyWithin(i, i, i); +arrayOfPoint = Array.from(arrayOfPoint); +arrayOfPoint = Array.from(iterableOfPoint); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d, a); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d, a); +arrayOfPoint = Array.of(point, point); +i = s.codePointAt(i); +b = s.includes(s, i); +b = s.endsWith(s, i); +s = s.repeat(i); +b = s.startsWith(s, i); +s = String.fromCodePoint(i, i); +s = String.raw`abc`; +s = r.flags; +i = Number.EPSILON; +b = Number.isFinite(i); +b = Number.isInteger(i); +b = Number.isNaN(i); +b = Number.isSafeInteger(i); +i = Number.MAX_SAFE_INTEGER; +i = Number.MIN_SAFE_INTEGER; +i = Number.parseFloat(s); +i = Number.parseInt(s); +i = Number.parseInt(s, i); +i = Math.clz32(i); +i = Math.imul(i, i); +i = Math.sign(i); +i = Math.log10(i); +i = Math.log2(i); +i = Math.log1p(i); +i = Math.expm1(i); +i = Math.cosh(i); +i = Math.sinh(i); +i = Math.tanh(i); +i = Math.acosh(i); +i = Math.asinh(i); +i = Math.atanh(i); +i = Math.hypot(i, i); +i = Math.trunc(i); +i = Math.fround(i); +i = Math.cbrt(i); +map.clear(); +map.delete(s); +map.forEach((value: Point, key: string) => { }); +point = map.get(s); +b = map.has(s); +map = map.set(s, point); +i = map.size; +map = new Map(); +map = new Map(iterableOfStringPoint); +set.clear(); +set.delete(point); +set.forEach((value: Point, key: Point) => { }); +b = set.has(point); +set = set.add(point); +i = set.size; +set = new Set(); +set = new Set(iterableOfPoint); +weakMap.delete(point); +point3d = weakMap.get(point); +b = weakMap.has(point); +weakMap = weakMap.set(point, point3d); +weakMap = new WeakMap(); +weakMap = new WeakMap(iterableOfPointPoint3D); +weakSet.delete(point); +weakSet = weakSet.add(point); +b = weakSet.has(point); +weakSet = new WeakSet(); +weakSet = new WeakSet(iterableOfPoint); +iterableIteratorOfNumberPoint = arrayOfPoint.entries(); +iterableIteratorOfNumber = arrayOfPoint.keys(); +iterableIteratorOfPoint = arrayOfPoint.values(); +iterableIteratorOfPointPoint = set.entries(); +iterableIteratorOfPoint = set.keys(); +iterableIteratorOfPoint = set.values(); +promiseLikeOfPoint.then((point: Point) => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint.then((point: Point) => { }); +promiseOfPoint = promiseOfPoint.then(); +promiseOfPoint = promiseOfPoint.then(p => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint = promiseOfPoint.catch(e => point); +promiseOfPoint = promiseOfPoint.catch(e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => { }); +promiseOfPoint3D = promiseOfPoint.catch(e => point3d); +promiseOfPoint3D = promiseOfPoint.catch(e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.catch(e => promiseLikeOfPoint3D); +promiseOfPoint = new Promise((resolve, reject) => resolve(point)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseLikeOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => reject(e)); +promiseOfArrayOfPoint = Promise.all(arrayOfPoint); +promiseOfArrayOfPoint = Promise.all(iterableOfPoint); +promiseOfPoint = Promise.race(arrayOfPoint); +promiseOfPoint = Promise.race(iterableOfPoint); +promiseOfVoid = Promise.resolve(); +promiseOfPoint = Promise.resolve(point3d); +promiseOfPoint = Promise.resolve(promiseOfPoint); +promiseOfPoint = Promise.resolve(promiseLikeOfPoint); +promiseOfVoid = Promise.reject(e); +promiseOfPoint = Promise.reject(e); +a = Reflect.apply(f, a, arrayLikeOfAny); +a = Reflect.construct(f, arrayLikeOfAny); +b = Reflect.defineProperty(a, s, pd); +b = Reflect.defineProperty(a, i, pd); +b = Reflect.defineProperty(a, sym, pd); +b = Reflect.deleteProperty(a, s); +b = Reflect.deleteProperty(a, i); +b = Reflect.deleteProperty(a, sym); +iterableIteratorOfAny = Reflect.enumerate(a); +a = Reflect.get(a, s, a); +a = Reflect.get(a, i, a); +a = Reflect.get(a, sym, a); +pd = Reflect.getOwnPropertyDescriptor(a, s); +pd = Reflect.getOwnPropertyDescriptor(a, i); +pd = Reflect.getOwnPropertyDescriptor(a, sym); +a = Reflect.getPrototypeOf(a); +b = Reflect.has(a, s); +b = Reflect.has(a, i); +b = Reflect.has(a, sym); +b = Reflect.isExtensible(a); +arrayOfPropertyKey = Reflect.ownKeys(a); +b = Reflect.preventExtensions(a); +b = Reflect.set(a, s, a, a); +b = Reflect.set(a, i, a, a); +b = Reflect.set(a, sym, a, a); +b = Reflect.setPrototypeOf(a, a); \ No newline at end of file diff --git a/es6-shim/es6-shim-tests.ts.tscparams b/es6-shim/es6-shim-tests.ts.tscparams new file mode 100644 index 000000000..4169d3605 --- /dev/null +++ b/es6-shim/es6-shim-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --target es5 \ No newline at end of file diff --git a/es6-shim/es6-shim.d.ts b/es6-shim/es6-shim.d.ts new file mode 100644 index 000000000..cff5a9b7e --- /dev/null +++ b/es6-shim/es6-shim.d.ts @@ -0,0 +1,673 @@ +// Type definitions for es6-shim v0.31.2 +// Project: https://github.com/paulmillr/es6-shim +// Definitions by: Ron Buckton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare type PropertyKey = string | number | symbol; + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface IterableShim { + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): Iterator; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface IterableIteratorShim extends IterableShim, Iterator { + /** + * Shim for an ES6 iterable iterator. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface ArrayLike { + length: number; + [n: number]: T; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: IterableShim, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: IterableShim): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIteratorShim<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIteratorShim; + + /** + * Returns an list of values in the array + */ + values(): IterableIteratorShim; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects to copy properties from. + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + * @remarks Requires `__proto__` support. + */ + setPrototypeOf(o: any, proto: any): any; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + flags: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[]): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: IterableShim>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: IterableShim>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): Map; + size: number; + entries(): IterableIteratorShim<[K, V]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; +} + +interface MapConstructor { + new (): Map; + new (iterable: IterableShim<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; + entries(): IterableIteratorShim<[T, T]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; +} + +interface SetConstructor { + new (): Set; + new (iterable: IterableShim): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: IterableShim<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + add(value: T): WeakSet; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: IterableShim): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +declare module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIteratorShim; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +declare module "es6-shim" { + var String: StringConstructor; + var Array: ArrayConstructor; + var Number: NumberConstructor; + var Math: Math; + var Object: ObjectConstructor; + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; + var Promise: PromiseConstructor; + module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): Iterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; + } +} \ No newline at end of file diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts index c3dfd8d6d..621b104bd 100644 --- a/fabricjs/fabricjs-tests.ts +++ b/fabricjs/fabricjs-tests.ts @@ -740,7 +740,7 @@ function sample8() { } for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = true; + activeObjectButtons[i]; } canvas.on('object:selected', onObjectSelected); @@ -750,7 +750,7 @@ function sample8() { var selectedObject = e.target; for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = false; + activeObjectButtons[i]; } lockHorizontallyEl.innerHTML = (selectedObject.lockMovementX ? 'Unlock horizontal movement' : 'Lock horizontal movement'); @@ -762,7 +762,7 @@ function sample8() { canvas.on('selection:cleared', function(e) { for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = true; + activeObjectButtons[i]; } }); @@ -889,7 +889,6 @@ function sample8() { var cmdUnderlineBtn = document.getElementById('text-cmd-underline'); if (cmdUnderlineBtn) { activeObjectButtons.push(cmdUnderlineBtn); - cmdUnderlineBtn.disabled = true; cmdUnderlineBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -903,7 +902,6 @@ function sample8() { var cmdLinethroughBtn = document.getElementById('text-cmd-linethrough'); if (cmdLinethroughBtn) { activeObjectButtons.push(cmdLinethroughBtn); - cmdLinethroughBtn.disabled = true; cmdLinethroughBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -917,7 +915,6 @@ function sample8() { var cmdOverlineBtn = document.getElementById('text-cmd-overline'); if (cmdOverlineBtn) { activeObjectButtons.push(cmdOverlineBtn); - cmdOverlineBtn.disabled = true; cmdOverlineBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -931,7 +928,6 @@ function sample8() { var cmdBoldBtn = document.getElementById('text-cmd-bold'); if (cmdBoldBtn) { activeObjectButtons.push(cmdBoldBtn); - cmdBoldBtn.disabled = true; cmdBoldBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -945,7 +941,6 @@ function sample8() { var cmdItalicBtn = document.getElementById('text-cmd-italic'); if (cmdItalicBtn) { activeObjectButtons.push(cmdItalicBtn); - cmdItalicBtn.disabled = true; cmdItalicBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -959,7 +954,6 @@ function sample8() { var cmdShadowBtn = document.getElementById('text-cmd-shadow'); if (cmdShadowBtn) { activeObjectButtons.push(cmdShadowBtn); - cmdShadowBtn.disabled = true; cmdShadowBtn.onclick = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -973,7 +967,6 @@ function sample8() { var textAlignSwitch = document.getElementById('text-align'); if (textAlignSwitch) { activeObjectButtons.push(textAlignSwitch); - textAlignSwitch.disabled = true; textAlignSwitch.onchange = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { @@ -986,7 +979,6 @@ function sample8() { var fontFamilySwitch = document.getElementById('font-family'); if (fontFamilySwitch) { activeObjectButtons.push(fontFamilySwitch); - fontFamilySwitch.disabled = true; fontFamilySwitch.onchange = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { diff --git a/fluxxor/fluxxor.d.ts b/fluxxor/fluxxor.d.ts index e8b89a66d..c6a5849d1 100644 --- a/fluxxor/fluxxor.d.ts +++ b/fluxxor/fluxxor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Yuichi Murata // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// /// declare module Fluxxor { @@ -14,7 +14,7 @@ declare module Fluxxor { doDispatchLoop(action: Function): void; waitForStores(store: Store, stores: string[], fn: Function): void; } - + class Flux extends EventEmitter3.EventEmitter { constructor(stores: any, actions: any); addActions(actions: any): void; @@ -26,40 +26,40 @@ declare module Fluxxor { stores: any; actions: any; } - + interface Store extends EventEmitter3.EventEmitter { bindActions(...args: Array): void; bindActions(args: Array): void; waitFor(stores: string[], fn: Function): void; } - + interface StoreSpec { initialize?(instance?: any, options?: {}): void; actions?: any; } - + interface StoreClass { new (options?: {}): any; } - + interface Context { flux: Flux; } - + interface FluxMixin { getFlux(): Flux; } - + interface FluxChildMixin { getFlux(): Flux; } - + interface StoreWatchMixin { getStateFromFlux(): StoreState; } - - function FluxMixin(React: React.Exports): FluxMixin; - function FluxChildMixin(React: React.Exports): FluxChildMixin; + + function FluxMixin(React: typeof __React): FluxMixin; + function FluxChildMixin(React: typeof __React): FluxChildMixin; function StoreWatchMixin(...storeNames: string[]): StoreWatchMixin; function createStore(spec: StoreSpec): StoreClass; var version: string; diff --git a/git-config/git-config-tests.ts b/git-config/git-config-tests.ts new file mode 100644 index 000000000..800597a5a --- /dev/null +++ b/git-config/git-config-tests.ts @@ -0,0 +1,9 @@ +/// + +import gitConfig = require('git-config'); + +var config: Object = gitConfig.sync(); +console.log(JSON.stringify(config)); + +config = gitConfig.sync('gitconfig'); +console.log(JSON.stringify(config)); diff --git a/git-config/git-config.d.ts b/git-config/git-config.d.ts new file mode 100644 index 000000000..0db2f294b --- /dev/null +++ b/git-config/git-config.d.ts @@ -0,0 +1,8 @@ +// Type definitions for git-config +// Project: https://github.com/eugeneware/git-config +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "git-config" { + export function sync(gitFile?: string): Object; // Synchronous version. +} diff --git a/git-config/gitconfig b/git-config/gitconfig new file mode 100644 index 000000000..0ee61d5b1 --- /dev/null +++ b/git-config/gitconfig @@ -0,0 +1,5 @@ +[user] + name = A Git User + email = git.user@domain.xyz +[push] + default = simple diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 697a91071..ed7908df7 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1,2122 +1,2121 @@ -// Type definitions for Google Maps JavaScript API 3.20 -// Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* -The MIT License - -Copyright (c) 2012 Folia A/S. http://www.folia.dk - -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. -*/ - -declare module google.maps { - /***** Map *****/ - export class Map extends MVCObject { - constructor(mapDiv: Element, opts?: MapOptions); - fitBounds(bounds: LatLngBounds): void; - getBounds(): LatLngBounds; - getCenter(): LatLng; - getDiv(): Element; - getHeading(): number; - getMapTypeId(): MapTypeId|string; - getProjection(): Projection; - getStreetView(): StreetViewPanorama; - getTilt(): number; - getZoom(): number; - panBy(x: number, y: number): void; - panTo(latLng: LatLng|LatLngLiteral): void; - panToBounds(latLngBounds: LatLngBounds): void; - setCenter(latlng: LatLng|LatLngLiteral): void; - setHeading(heading: number): void; - setMapTypeId(mapTypeId: MapTypeId|string): void; - setOptions(options: MapOptions): void; - setStreetView(panorama: StreetViewPanorama): void; - setTilt(tilt: number): void; - setZoom(zoom: number): void; - controls: MVCArray[]; //Array> - data: Data; - mapTypes: MapTypeRegistry; - overlayMapTypes: MVCArray; // MVCArray - } - - export interface MapOptions { - backgroundColor?: string; - center?: LatLng; - disableDefaultUI?: boolean; - disableDoubleClickZoom?: boolean; - draggable?: boolean; - draggableCursor?: string; - draggingCursor?: string; - heading?: number; - keyboardShortcuts?: boolean; - mapMaker?: boolean; - mapTypeControl?: boolean; - mapTypeControlOptions?: MapTypeControlOptions; - mapTypeId?: MapTypeId; - maxZoom?: number; - minZoom?: number; - noClear?: boolean; - overviewMapControl?: boolean; - overviewMapControlOptions?: OverviewMapControlOptions; - panControl?: boolean; - panControlOptions?: PanControlOptions; - rotateControl?: boolean; - rotateControlOptions?: RotateControlOptions; - scaleControl?: boolean; - scaleControlOptions?: ScaleControlOptions; - scrollwheel?: boolean; - streetView?: StreetViewPanorama; - streetViewControl?: boolean; - streetViewControlOptions?: StreetViewControlOptions; - styles?: MapTypeStyle[]; - tilt?: number; - zoom?: number; - zoomControl?: boolean; - zoomControlOptions?: ZoomControlOptions; - } - - export enum MapTypeId { - HYBRID, - ROADMAP, - SATELLITE, - TERRAIN - } - - /***** Controls *****/ - export interface MapTypeControlOptions { - mapTypeIds?: (MapTypeId|string)[]; - position?: ControlPosition; - style?: MapTypeControlStyle; - } - - export enum MapTypeControlStyle { - DEFAULT, - DROPDOWN_MENU, - HORIZONTAL_BAR - } - - export interface OverviewMapControlOptions { - opened?: boolean; - } - - export interface PanControlOptions { - position: ControlPosition; - } - - export interface RotateControlOptions { - position: ControlPosition; - } - - export interface ScaleControlOptions { - style?: ScaleControlStyle; - } - - export enum ScaleControlStyle { - DEFAULT - } - - export interface StreetViewControlOptions { - position: ControlPosition; - } - - export interface ZoomControlOptions { - position?: ControlPosition; - style?: ZoomControlStyle; - } - - export enum ZoomControlStyle { - DEFAULT, - LARGE, - SMALL - } - - export enum ControlPosition { - BOTTOM_CENTER, - BOTTOM_LEFT, - BOTTOM_RIGHT, - LEFT_BOTTOM, - LEFT_CENTER, - LEFT_TOP, - RIGHT_BOTTOM, - RIGHT_CENTER, - RIGHT_TOP, - TOP_CENTER, - TOP_LEFT, - TOP_RIGHT - } - - /***** Data *****/ - export class Data extends MVCObject { - constructor(options?: Data.DataOptions); - add(feature: Data.Feature|Data.FeatureOptions): Data.Feature; - addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; - contains(feature: Data.Feature): boolean; - forEach(callback: (feature: Data.Feature) => void): void; - getControlPosition(): ControlPosition; - getControls(): string[]; - getDrawingMode(): string; - getFeatureById(id: number|string): Data.Feature; - getMap(): Map; - getStyle(): Data.StylingFunction|Data.StyleOptions; - loadGeoJson(url: string, options?: Data.GeoJsonOptions, callback?: (features: Data.Feature[]) => void): void; - overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; - remove(feature: Data.Feature): void; - revertStyle(feature?: Data.Feature): void; - setControlPosition(controlPosition: ControlPosition): void; - setControls(controls: string[]): void; - setDrawingMode(drawingMode: string): void; - setMap(map: Map): void; - setStyle(style: Data.StylingFunction|Data.StyleOptions): void; - toGeoJson(callback: (feature: Object) => void): void; - } - - export module Data { - export interface DataOptions { - controlPosition?: ControlPosition; - controls?: string[]; - drawingMode?: string; - featureFactory?: (geometry: Data.Geometry) => Data.Feature; - map?: Map; - style?: Data.StylingFunction|Data.StyleOptions; - } - - export interface GeoJsonOptions { - idPropertyName?: string; - } - - export interface StyleOptions { - clickable?: boolean; - cursor?: string; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - icon?: string|Icon|Symbol; - shape?: MarkerShape; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - title?: string; - visible?: boolean; - zIndex?: number; - } - - export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions; - - export class Feature { - constructor(options?: Data.FeatureOptions); - forEachProperty(callback: (value: any, name: string) => void): void; - getGeometry(): Data.Geometry; - getId(): number|string; - getProperty(name: string): any; - removeProperty(name: string): void; - setGeometry(newGeometry: Data.Geometry|LatLng|LatLngLiteral): void; - setProperty(name: string, newValue: any): void; - toGeoJson(callback: (feature: Object) => void): void; - } - - export interface FeatureOptions { - geometry?: Data.Geometry|LatLng|LatLngLiteral; - id?: number|string; - properties?: Object; - } - - export class Geometry { - getType(): string; - } - - export class Point extends Data.Geometry { - constructor(latLng: LatLng|LatLngLiteral); - get(): LatLng; - } - - export class MultiPoint extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class LineString extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class MultiLineString extends Data.Geometry { - constructor(elements: (Data.LineString|(LatLng|LatLngLiteral)[])[]); - getArray(): Data.LineString[]; - getAt(n: number): Data.LineString; - getLength(): number; - } - - export class LinearRing extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class Polygon extends Data.Geometry { - constructor(elements: (Data.LinearRing|(LatLng|LatLngLiteral)[])[]); - getArray(): Data.LinearRing[]; - getAt(n: number): Data.LinearRing; - getLength(): number; - } - - export class MultiPolygon extends Data.Geometry { - constructor(elements: (Data.Polygon|(LinearRing|(LatLng|LatLngLiteral)[])[])[]); - getArray(): Data.Polygon[]; - getAt(n: number): Data.Polygon; - getLength(): number; - } - - export class GeometryCollection extends Data.Geometry { - constructor(elements: (Data.Geometry[]|LatLng[]|LatLngLiteral)[]); - getArray(): Data.Geometry[]; - getAt(n: number): Data.Geometry; - getLength(): number; - } - - export interface MouseEvent extends google.maps.MouseEvent { - feature: Data.Feature; - } - - export interface AddFeatureEvent { - feature: Data.Feature; - } - - export interface RemoveFeatureEvent { - feature: Data.Feature; - } - - export interface SetGeometryEvent { - feature: Data.Feature; - newGeometry: Data.Geometry; - oldGeometry: Data.Geometry; - } - - export interface SetPropertyEvent { - feature: Data.Feature; - name: string; - newValue: any; - oldValue: any; - } - - export interface RemovePropertyEvent { - feature: Data.Feature; - name: string; - oldValue: any; - } - } - - /***** Overlays *****/ - export class Marker extends MVCObject { - static MAX_ZINDEX: number; - constructor(opts?: MarkerOptions); - getAnimation(): Animation; - getAttribution(): Attribution; - getClickable(): boolean; - getCursor(): string; - getDraggable(): boolean; - getIcon(): string|Icon|Symbol; - getMap(): Map|StreetViewPanorama; - getOpacity(): number; - getPlace(): Place; - getPosition(): LatLng; - getShape(): MarkerShape; - getTitle(): string; - getVisible(): boolean; - getZIndex(): number; - setAnimation(animation: Animation): void; - setAttribution(attribution: Attribution): void; - setClickable(flag: boolean): void; - setCursor(cursor: string): void; - setDraggable(flag: boolean): void; - setIcon(icon: string|Icon|Symbol): void; - setMap(map: Map|StreetViewPanorama): void; - getOpacity(opacity: number): void; - setOptions(options: MarkerOptions): void; - setPlace(place: Place): void; - setPosition(latlng: LatLng|LatLngLiteral): void; - setShape(shape: MarkerShape): void; - setTitle(title: string): void; - setVisible(visible: boolean): void; - setZIndex(zIndex: number): void; - } - - export interface MarkerOptions { - /** - * The offset from the marker's position to the tip of an InfoWindow - * that has been opened with the marker as anchor. - */ - anchorPoint?: Point; - /** Which animation to play when marker is added to a map. */ - animation?: Animation; - /** - * If true, the marker receives mouse and touch events. - * @default true - */ - clickable?: boolean; - /** Mouse cursor to show on hover. */ - cursor?: string; - /** - * If true, the marker can be dragged. - * @default false - */ - draggable?: boolean; - /** - * Icon for the foreground. - * If a string is provided, it is treated as though it were an Icon with the string as url. - * @type {(string|Icon|Symbol)} - */ - icon?: string|Icon|Symbol; - /** - * Map on which to display Marker. - * @type {(Map|StreetViewPanorama)} - * - */ - map?: Map|StreetViewPanorama; - /** The marker's opacity between 0.0 and 1.0. */ - opacity?: number; - /** - * Optimization renders many markers as a single static element. - * Optimized rendering is enabled by default. - * Disable optimized rendering for animated GIFs or PNGs, or when each - * marker must be rendered as a separate DOM element (advanced usage - * only). - */ - optimized?: boolean; - /** - * Place information, used to identify and describe the place - * associated with this Marker. In this context, 'place' means a - * business, point of interest or geographic location. To allow a user - * to save this place, open an info window anchored on this marker. - * The info window will contain information about the place and an - * option for the user to save it. Only one of position or place can - * be specified. - */ - place?: Place; - /** - * Marker position. Required. - */ - position: LatLng; - /** Image map region definition used for drag/click. */ - shape?: MarkerShape; - /** Rollover text. */ - title?: string; - /** If true, the marker is visible. */ - visible?: boolean; - /** - * All markers are displayed on the map in order of their zIndex, - * with higher values displaying in front of markers with lower values. - * By default, markers are displayed according to their vertical position on screen, - * with lower markers appearing in front of markers further up the screen. - */ - zIndex?: number; - } - - export interface Icon { - /** - * The position at which to anchor an image in correspondence to the - * location of the marker on the map. By default, the anchor is - * located along the center point of the bottom of the image. - */ - anchor?: Point; - /** - * The origin of the label relative to the top-left corner of the icon - * image, if a label is supplied by the marker. By default, the origin - * is located in the center point of the image. - */ - labelOrigin?: Point; - /** - * The position of the image within a sprite, if any. By default, the - * origin is located at the top left corner of the image (0, 0). - */ - origin?: Point; - /** - * The size of the entire image after scaling, if any. Use this - * property to stretch/ shrink an image or a sprite. - */ - scaledSize?: Size; - /** - * The display size of the sprite or image. When using sprites, you - * must specify the sprite size. If the size is not provided, it will - * be set when the image loads. - */ - size?: Size; - /** The URL of the image or sprite sheet. */ - url?: string; - } - - export interface MarkerShape { - coords?: number[]; - type?: string; - } - - export interface Symbol { - /** - * The position of the symbol relative to the marker or polyline. - * The coordinates of the symbol's path are translated left and up by the anchor's x and y coordinates respectively. - * By default, a symbol is anchored at (0, 0). - * The position is expressed in the same coordinate system as the symbol's path. - */ - anchor?: Point; - /** - * The symbol's fill color. - * All CSS3 colors are supported except for extended named colors. For symbol markers, this defaults to 'black'. - * For symbols on polylines, this defaults to the stroke color of the corresponding polyline. - */ - fillColor?: string; - /** - * The symbol's fill opacity. - * @default 0 - */ - fillOpacity?: number; - /** - * The symbol's path, which is a built-in symbol path, or a custom path expressed using SVG path notation. Required. - * @type {(SymbolPath|string)} - */ - path?: SymbolPath|string; - /** - * The angle by which to rotate the symbol, expressed clockwise in degrees. - * Defaults to 0. - * A symbol in an IconSequence where fixedRotation is false is rotated relative to the angle of the edge on which it lies. - */ - rotation?: number; - /** - * The amount by which the symbol is scaled in size. - * For symbol markers, this defaults to 1; after scaling, the symbol may be of any size. - * For symbols on a polyline, this defaults to the stroke weight of the polyline; - * after scaling, the symbol must lie inside a square 22 pixels in size centered at the symbol's anchor. - */ - scale?: number; - /** - * The symbol's stroke color. All CSS3 colors are supported except for extended named colors. - * For symbol markers, this defaults to 'black'. - * For symbols on a polyline, this defaults to the stroke color of the polyline. - */ - strokeColor?: string; - /** - * The symbol's stroke opacity. For symbol markers, this defaults to 1. - * For symbols on a polyline, this defaults to the stroke opacity of the polyline. - */ - strokeOpacity?: number; - /** The symbol's stroke weight. Defaults to the scale of the symbol.v*/ - strokeWeight?: number; - } - - /** Built-in symbol paths. */ - export enum SymbolPath { - /** A backward-pointing closed arrow. */ - BACKWARD_CLOSED_ARROW, - /** A backward-pointing open arrow. */ - BACKWARD_OPEN_ARROW, - /** A circle. */ - CIRCLE, - /** A forward-pointing closed arrow. */ - FORWARD_CLOSED_ARROW, - /** A forward-pointing open arrow. */ - FORWARD_OPEN_ARROW - } - - export enum Animation { - BOUNCE, - DROP - } - - /** - * An overlay that looks like a bubble and is often connected to a marker. - * This class extends MVCObject. - */ - export class InfoWindow extends MVCObject { - /** - * Creates an info window with the given options. An InfoWindow can be - * placed on a map at a particular position or above a marker, - * depending on what is specified in the options. Unless auto-pan is - * disabled, an InfoWindow will pan the map to make itself visible - * when it is opened. After constructing an InfoWindow, you must call - * open to display it on the map. The user can click the close button - * on the InfoWindow to remove it from the map, or the developer can - * call close() for the same effect. - */ - constructor(opts?: InfoWindowOptions); - /** Closes this InfoWindow by removing it from the DOM structure. */ - close(): void; - getContent(): string|Element; - getPosition(): LatLng; - getZIndex(): number; - /** - * Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. - * In the core API, the only anchor is the Marker class. - * However, an anchor can be any MVCObject that exposes a LatLng position property and optionally - * a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). - * The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow. - */ - open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; - setContent(content: string|Node): void; - setOptions(options: InfoWindowOptions): void; - setPosition(position: LatLng): void; - setZIndex(zIndex: number): void; - } - - export interface InfoWindowOptions { - /** - * Content to display in the InfoWindow. This can be an HTML element, a plain-text string, or a string containing HTML. - * The InfoWindow will be sized according to the content. - * To set an explicit size for the content, set content to be a HTML element with that size. - * @type {(string|Node)} - */ - content?: string|Node; - /** - * Disable auto-pan on open. By default, the info window will pan the map so that it is fully visible when it opens. - */ - disableAutoPan?: boolean; - /** - * Maximum width of the infowindow, regardless of content's width. - * This value is only considered if it is set before a call to open. - * To change the maximum width when changing content, call close, setOptions, and then open. - */ - maxWidth?: number; - /** - * The offset, in pixels, of the tip of the info window from the point on the map - * at whose geographical coordinates the info window is anchored. - * If an InfoWindow is opened with an anchor, the pixelOffset will be calculated from the anchor's anchorPoint property. - */ - pixelOffset?: Size; - /** - * The LatLng at which to display this InfoWindow. If the InfoWindow is opened with an anchor, the anchor's position will be used instead. - */ - position?: LatLng|LatLngLiteral; - /** - * All InfoWindows are displayed on the map in order of their zIndex, - * with higher values displaying in front of InfoWindows with lower values. - * By default, InfoWindows are displayed according to their latitude, - * with InfoWindows of lower latitudes appearing in front of InfoWindows at higher latitudes. - * InfoWindows are always displayed in front of markers. - */ - zIndex?: number; - } - - export class Polyline extends MVCObject { - constructor(opts?: PolylineOptions); - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getPath(): MVCArray; // MVCArray - getVisible(): boolean; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map): void; - setOptions(options: PolylineOptions): void; - setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; // MVCArray|Array - setVisible(visible: boolean): void; - } - - export interface PolylineOptions { - clickable?: boolean; - draggable?: boolean; - editable?: boolean; - geodesic?: boolean; - icons?: IconSequence[]; - map?: Map; - path?: MVCArray|LatLng[]|LatLngLiteral[]; // MVCArray|Array - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - visible?: boolean; - zIndex?: number; - } - - export interface IconSequence { - fixedRotation?: boolean; - icon?: Symbol; - offset?: string; - repeat?: string; - } - - export class Polygon extends MVCObject { - constructor(opts?: PolygonOptions); - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getPath(): MVCArray; // MVCArray - getPaths(): MVCArray; // MVCArray> - getVisible(): boolean; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map): void; - setOptions(options: PolygonOptions): void; - setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; - setPaths(paths: MVCArray): void; - setPaths(paths: MVCArray[]): void; - setPaths(path: LatLng[]): void; - setPaths(path: LatLng[][]): void; - setPaths(path: LatLngLiteral[]): void; - setPaths(path: LatLngLiteral[][]): void; - setVisible(visible: boolean): void; - } - - export interface PolygonOptions { - clickable?: boolean; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - geodesic?: boolean; - map?: Map; - paths?: any[]; // MVCArray>|MVCArray|Array>|Array - strokeColor?: string; - strokeOpacity?: number; - strokePosition?: StrokePosition; - strokeWeight?: number; - visible?: boolean; - zIndex?: number; - } - - export interface PolyMouseEvent { - edge?: number; - path?: number; - vertex?: number; - } - - export class Rectangle extends MVCObject { - constructor(opts?: RectangleOptions); - getBounds(): LatLngBounds; - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getVisible(): boolean; - setBounds(bounds: LatLngBounds): void; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map): void; - setOptions(options: RectangleOptions): void; - setVisible(visible: boolean): void; - } - - export interface RectangleOptions { - bounds?: LatLngBounds; - clickable?: boolean; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - map?: Map; - strokeColor?: string; - strokeOpacity?: number; - strokePosition?: StrokePosition; - strokeWeight?: number; - visible?: boolean; - zIndex?: number; - } - - export class Circle extends MVCObject { - constructor(opts?: CircleOptions); - getBounds(): LatLngBounds; - getCenter(): LatLng; - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getRadius(): number; - getVisible(): boolean; - setCenter(center: LatLng|LatLngLiteral): void; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map): void; - setOptions(options: CircleOptions): void; - setRadius(radius: number): void; - setVisible(visible: boolean): void; - } - - export interface CircleOptions { - center?: LatLng; - clickable?: boolean; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - map?: Map; - radius?: number; - strokeColor?: string; - strokeOpacity?: number; - strokePosition?: StrokePosition; - strokeWeight?: number; - visible?: boolean; - zIndex?: number; - } - - export enum StrokePosition { - CENTER, - INSIDE, - OUTSIDE - } - - export class GroundOverlay extends MVCObject { - constructor(url: string, bounds: LatLngBounds, opts?: GroundOverlayOptions); - getBounds(): LatLngBounds; - getMap(): Map; - getOpacity(): number; - getUrl(): string; - setMap(map: Map): void; - setOpacity(opacity: number): void; - } - - export interface GroundOverlayOptions { - clickable?: boolean; - map?: Map; - opacity?: number; - } - - export class OverlayView extends MVCObject { - draw(): void; - getMap(): Map|StreetViewPanorama; - getPanes(): MapPanes; - getProjection(): MapCanvasProjection; - onAdd(): void; - onRemove(): void; - setMap(map: Map|StreetViewPanorama): void; - } - - export interface MapPanes { - floatPane: Element; - mapPane: Element; - markerLayer: Element; - overlayLayer: Element; - overlayMouseTarget: Element; - } - - export class MapCanvasProjection extends MVCObject { - fromContainerPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; - fromDivPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; - fromLatLngToContainerPixel(latLng: LatLng): Point; - fromLatLngToDivPixel(latLng: LatLng): Point; - getWorldWidth(): number; - } - - /***** Services *****/ - export class Geocoder { - geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; - } - - export interface GeocoderRequest { - address?: string; - bounds?: LatLngBounds; - componentRestrictions: GeocoderComponentRestrictions; - location?: LatLng|LatLngLiteral; - region?: string; - } - - export interface GeocoderComponentRestrictions { - administrativeArea: string; - country: string; - locality: string; - postalCode: string; - route: string; - } - - export enum GeocoderStatus { - ERROR, - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface GeocoderResult { - address_components: GeocoderAddressComponent[]; - formatted_address: string; - geometry: GeocoderGeometry; - partial_match: boolean; - postcode_localities: string[] - types: string[]; - } - - export interface GeocoderAddressComponent { - long_name: string; - short_name: string; - types: string[]; - } - - export interface GeocoderGeometry { - bounds: LatLngBounds; - location: LatLng; - location_type: GeocoderLocationType; - viewport: LatLngBounds; - } - - export enum GeocoderLocationType { - APPROXIMATE, - GEOMETRIC_CENTER, - RANGE_INTERPOLATED, - ROOFTOP - } - - export class DirectionsRenderer extends MVCObject { - constructor(opts?: DirectionsRendererOptions); - getDirections(): DirectionsResult; - getMap(): Map; - getPanel(): Element; - getRouteIndex(): number; - setDirections(directions: DirectionsResult): void; - setMap(map: Map): void; - setOptions(options: DirectionsRendererOptions): void; - setPanel(panel: Element): void; - setRouteIndex(routeIndex: number): void; - } - - export interface DirectionsRendererOptions { - directions?: DirectionsResult; - draggable?: boolean; - hideRouteList?: boolean; - infoWindow?: InfoWindow; - map?: Map; - markerOptions?: MarkerOptions; - panel?: Element; - polylineOptions?: PolylineOptions; - preserveViewport?: boolean; - routeIndex?: number; - suppressBicyclingLayer?: boolean; - suppressInfoWindows?: boolean; - suppressMarkers?: boolean; - suppressPolylines?: boolean; - } - - export class DirectionsService { - route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; - } - - export interface DirectionsRequest { - avoidFerries?: boolean; - avoidHighways?: boolean; - avoidTolls?: boolean; - destination?: LatLng|string; - durationInTraffic?: boolean; - optimizeWaypoints?: boolean; - origin?: LatLng|string; - provideRouteAlternatives?: boolean; - region?: string; - transitOptions?: TransitOptions; - travelMode?: TravelMode; - unitSystem?: UnitSystem; - waypoints?: DirectionsWaypoint[]; - } - - export enum TravelMode { - BICYCLING, - DRIVING, - TRANSIT, - WALKING - } - - export enum UnitSystem { - IMPERIAL, - METRIC - } - - export interface TransitOptions { - arrivalTime?: Date; - departureTime?: Date; - modes: TransitMode[]; - routingPreference: TransitRoutePreference; - } - - export enum TransitMode { - BUS, - RAIL, - SUBWAY, - TRAIN, - TRAM - } - - export enum TransitRoutePreference - { - FEWER_TRANSFERS, - LESS_WALKING - } - - export interface TransitFare { } - - export interface DirectionsWaypoint { - location: LatLng|string; - stopover: boolean; - } - - export enum DirectionsStatus { - INVALID_REQUEST, - MAX_WAYPOINTS_EXCEEDED, - NOT_FOUND, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface DirectionsResult { - routes: DirectionsRoute[]; - } - - export interface DirectionsRoute { - bounds: LatLngBounds; - copyrights: string; - fare: TransitFare; - legs: DirectionsLeg[]; - overview_path: LatLng[]; - overview_polyline: string; - warnings: string[]; - waypoint_order: number[]; - } - - export interface DirectionsLeg { - arrival_time: Time; - departure_time: Time; - distance: Distance; - duration: Duration; - duration_in_traffic: Duration; - end_address: string; - end_location: LatLng; - start_address: string; - start_location: LatLng; - steps: DirectionsStep[]; - via_waypoints: LatLng[]; - } - - export interface DirectionsStep { - distance: Distance; - duration: Duration; - end_location: LatLng; - instructions: string; - path: LatLng[]; - start_location: LatLng; - steps: DirectionsStep; - transit: TransitDetails; - travel_mode: TravelMode; - } - - export interface Distance { - text: string; - value: number; - } - - export interface Duration { - text: string; - value: number; - } - - export interface Time { - text: string; - time_zone: string; - value: Date; - } - - export interface TransitDetails { - arrival_stop: TransitStop; - arrival_time: Time; - departure_stop: TransitStop; - departure_time: Time; - headsign: string; - headway: number; - line: TransitLine; - num_stops: number; - } - - export interface TransitStop { - location: LatLng; - name: string; - } - - export interface TransitLine { - agencies: TransitAgency[]; - color: string; - icon: string; - name: string; - short_name: string; - text_color: string; - url: string; - vehicle: TransitVehicle; - } - - export interface TransitAgency { - name: string; - phone: string; - url: string; - } - - export interface TransitVehicle { - icon: string; - local_icon: string; - name: string; - type: VehicleType; - } - - export enum VehicleType - { - BUS, - CABLE_CAR, - COMMUTER_TRAIN, - FERRY, - FUNICULAR, - GONDOLA_LIFT, - HEAVY_RAIL, - HIGH_SPEED_TRAIN, - INTERCITY_BUS, - METRO_RAIL, - MONORAIL, - OTHER, - RAIL, - SHARE_TAXI, - SUBWAY, - TRAM, - TROLLEYBUS - } - - export class ElevationService { - getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - } - - export interface LocationElevationRequest { - locations: LatLng[]; - } - - export interface PathElevationRequest { - path?: LatLng[]; - samples?: number; - } - - export interface ElevationResult { - elevation: number; - location: LatLng; - resolution: number; - } - - export enum ElevationStatus { - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export class MaxZoomService { - getMaxZoomAtLatLng(latlng: LatLng|LatLngLiteral, callback: (result: MaxZoomResult) => void ): void; - } - - export interface MaxZoomResult { - status: MaxZoomStatus; - zoom: number; - } - - export enum MaxZoomStatus { - ERROR, - OK - } - - export class DistanceMatrixService { - getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; - } - - export interface DistanceMatrixRequest { - avoidFerries?: boolean; - avoidHighways?: boolean; - avoidTolls?: boolean; - destinations?: LatLng[]|string[]; - durationInTraffic?: boolean; - origins?: LatLng[]|string[]; - region?: string; - transitOptions?: TransitOptions; - travelMode?: TravelMode; - unitSystem?: UnitSystem; - } - - export interface DistanceMatrixResponse { - destinationAddresses: string[]; - originAddresses: string[]; - rows: DistanceMatrixResponseRow[]; - } - - export interface DistanceMatrixResponseRow { - elements: DistanceMatrixResponseElement[]; - } - - export interface DistanceMatrixResponseElement { - distance: Distance; - duration: Duration; - fare: TransitFare; - status: DistanceMatrixElementStatus; - } - - export enum DistanceMatrixStatus { - INVALID_REQUEST, - MAX_DIMENSIONS_EXCEEDED, - MAX_ELEMENTS_EXCEEDED, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export enum DistanceMatrixElementStatus { - NOT_FOUND, - OK, - ZERO_RESULTS - } - - /***** Save to Google Maps *****/ - export interface Attribution { - iosDeepLinkId?: string; - source?: string; - webUrl?: string; - } - - export interface Place { - location?: LatLng|LatLngLiteral; - placeId?: string; - query?: string; - } - - export class SaveWidget { - constructor(container: Node, opts?: SaveWidgetOptions); - getAttribution(): Attribution; - getPlace(): Place; - setAttribution(attribution: Attribution): void; - setOptions(opts: SaveWidgetOptions): void; - setPlace(place: Place): void; - } - - export interface SaveWidgetOptions{ - attribution?: Attribution; - place?: Place; - } - - /***** Map Types *****/ - export interface MapType { - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - projection?: Projection; - radius?: number; - tileSize?: Size; - } - - export class MapTypeRegistry extends MVCObject { - constructor(); - set(id: string, mapType: MapType): void; - } - - export interface Projection { - fromLatLngToPoint(latLng: LatLng, point?: Point): Point; - fromPointToLatLng(pixel: Point, noWrap?: boolean): LatLng; - } - - export class ImageMapType extends MVCObject implements MapType { - constructor(opts: ImageMapTypeOptions); - getOpacity(): number; - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - setOpacity(opacity: number): void; - } - - export interface ImageMapTypeOptions { - alt?: string; - getTileUrl(tileCoord: Point, zoom: number): string; - maxZoom?: number; - minZoom?: number; - name?: string; - opacity?: number; - tileSize?: Size; - } - - export class StyledMapType extends MVCObject implements MapType { - constructor(styles: MapTypeStyle[], options?: StyledMapTypeOptions); - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - } - - export interface StyledMapTypeOptions { - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - } - - export interface MapTypeStyle { - elementType?: MapTypeStyleElementType; - featureType?: MapTypeStyleFeatureType; - stylers?: MapTypeStyler[]; - } - - export interface MapTypeStyleFeatureType { - administrative?: { - country?: string; - land_parcel?: string; - locality?: string; - neighborhood?: string; - province?: string; - }; - all?: string; - landscape?: { - man_made?: string; - natural?: { - landcover?: string; - terrain?: string; - }; - }; - poi?: { - attraction?: string; - business?: string; - government?: string; - medical?: string; - park?: string; - place_of_worship?: string; - school?: string; - sports_complex?: string; - }; - road?: { - arterial?: string; - highway?: { - controlled_access?: string; - }; - local?: string; - }; - transit?: { - line?: string; - station?: { - airport?: string; - bus?: string; - rail?: string; - }; - }; - water?: string; - } - - export interface MapTypeStyleElementType { - all?: string; - geometry?: { - fill?: string; - stroke?: string; - }; - labels?: { - icon?: string; - text?: { - fill?: string; - stroke?: string; - } - }; - } - - export interface MapTypeStyler { - color?: string; - gamma?: number; - hue?: string; - invert_lightness?: boolean; - lightness?: number; - saturation?: number; - visibility?: string; - } - - /***** Layers *****/ - export class BicyclingLayer extends MVCObject { - constructor(); - getMap(): Map; - setMap(map: Map): void; - } - - export class FusionTablesLayer extends MVCObject { - constructor(options: FusionTablesLayerOptions); - getMap(): Map; - setMap(map: Map): void; - setOptions(options: FusionTablesLayerOptions): void; - } - - export interface FusionTablesLayerOptions { - clickable?: boolean; - heatmap?: FusionTablesHeatmap; - map?: Map; - query?: FusionTablesQuery; - styles?: FusionTablesStyle[]; - suppressInfoWindows?: boolean; - } - - export interface FusionTablesQuery { - from?: string; - limit?: number; - offset?: number; - orderBy?: string; - select?: string; - where?: string; - } - - export interface FusionTablesStyle { - markerOptions?: FusionTablesMarkerOptions; - polygonOptions?: FusionTablesPolygonOptions; - polylineOptions?: FusionTablesPolylineOptions; - where?: string; - } - - export interface FusionTablesHeatmap { - enabled: boolean; - } - - export interface FusionTablesMarkerOptions { - iconName: string; - } - - export interface FusionTablesPolygonOptions { - fillColor?: string; - fillOpacity?: number; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesPolylineOptions { - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesMouseEvent { - infoWindowHtml?: string; - latLng?: LatLng; - pixelOffset?: Size; - row?: Object; // Object - } - - export interface FusionTablesCell { - columnName?: string; - value?: string; - } - - export class KmlLayer extends MVCObject { - constructor(opts?: KmlLayerOptions); - getDefaultViewport(): LatLngBounds; - getMap(): Map; - getMetadata(): KmlLayerMetadata; - getStatus(): KmlLayerStatus; - getUrl(): string; - getZIndex(): number; - setMap(map: Map): void; - setUrl(url: string): void; - setZIndez(zIndex: number): void; - } - - export interface KmlLayerOptions { - clickable?: boolean; - map?: Map; - preserveViewport?: boolean; - screenOverlays?: boolean; - suppressInfoWindows?: boolean; - url?: string; - zIndex?: number; - } - - export interface KmlLayerMetadata { - author: KmlAuthor; - description: string; - hasScreenOverlays: boolean; - name: string; - snippet: string; - } - - export enum KmlLayerStatus { - DOCUMENT_NOT_FOUND, - DOCUMENT_TOO_LARGE, - FETCH_ERROR, - INVALID_DOCUMENT, - INVALID_REQUEST, - LIMITS_EXCEEDED, - OK, - TIMED_OUT, - UNKNOWN - } - - export interface KmlMouseEvent { - featureData: KmlFeatureData; - latLng: LatLng; - pixelOffset: Size; - } - - export interface KmlFeatureData { - author: KmlAuthor; - description: string; - id: string; - infoWindowHtml: string; - name: string; - snippet: string; - } - - export interface KmlAuthor { - email: string; - name: string; - uri: string; - } - - export class TrafficLayer extends MVCObject { - constructor(); - getMap(): void; - setMap(map: Map): void; - } - - export class TransitLayer extends MVCObject { - constructor(); - getMap(): void; - setMap(map: Map): void; - } - - /***** Street View *****/ - export class StreetViewPanorama { - constructor(container: Element, opts?: StreetViewPanoramaOptions); - controls: MVCArray[]; // Array> - getLinks(): StreetViewLink[]; - getLocation(): StreetViewLocation; - getPano(): string; - getPhotographerPov(): StreetViewPov; - getPosition(): LatLng; - getPov(): StreetViewPov; - getStatus(): StreetViewStatus; - getVisible(): boolean; - getZoom(): number; - registerPanoProvider(provider: (input: string) => StreetViewPanoramaData): void; - setLinks(links: Array): void; - setOptions(options: StreetViewPanoramaOptions): void; - setPano(pano: string): void; - setPosition(latLng: LatLng|LatLngLiteral): void; - setPov(pov: StreetViewPov): void; - setVisible(flag: boolean): void; - setZoom(zoom: number): void; - } - - export interface StreetViewPanoramaOptions { - addressControl?: boolean; - addressControlOptions?: StreetViewAddressControlOptions; - clickToGo?: boolean; - disableDefaultUi?: boolean; - disableDoubleClickZoom?: boolean; - enableCloseButton?: boolean; - imageDateControl?: boolean; - linksControl?: boolean; - panControl?: boolean; - panControlOptions?: PanControlOptions; - pano?: string; - panoProvider?: (input: string) => StreetViewPanoramaData; - position?: LatLng|LatLngLiteral; - pov?: StreetViewPov; - scrollwheel?: boolean; - visible?: boolean; - zoomControl?: boolean; - zoomControlOptions?: ZoomControlOptions; - } - - export interface StreetViewAddressControlOptions { - position: ControlPosition; - } - - export interface StreetViewLink { - description?: string; - heading?: number; - pano?: string; - } - - export interface StreetViewPov { - heading?: number; - pitch?: number; - } - - export interface StreetViewPanoramaData { - copyright?: string; - imageDate?: string; - links?: StreetViewLink[]; - location?: StreetViewLocation; - tiles?: StreetViewTileData; - } - - export interface StreetViewLocation { - description?: string; - latLng?: LatLng; - pano?: string; - shortDescription?: string; - } - - export interface StreetViewTileData { - getTileUrl(pano: string, tileZoom: number, tileX: number, tileY: number): string; - centerHeading?: number; - tileSize?: Size; - worldSize?: Size; - } - - export class StreetViewService { - getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void): void; - getPanoramaByLocation(latlng: LatLng|LatLngLiteral, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ): void; - } - - export enum StreetViewStatus { - OK, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export class StreetViewCoverageLayer extends MVCObject { - getMap(): Map; - setMap(map: Map): void; - } - - /***** Events *****/ - export interface MapsEventListener { } - - export class event { - static addDomListener(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; - static addDomListenerOnce(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; - static addListener(instance: Object, eventName: string, handler: Function): MapsEventListener; - static addListenerOnce(instance: Object, eventName: string, handler: Function): MapsEventListener; - static clearInstanceListeners(instance: Object): void; - static clearListeners(instance: Object, eventName: string): void; - static removeListener(listener: MapsEventListener): void; - static trigger(instance: any, eventName: string, ...args: any[]): void; - } - - export interface MouseEvent { - stop(): void; - latLng: LatLng; - } - - /* **** Base **** */ - - /** - * A LatLng is a point in geographical coordinates: latitude and longitude. - * - * * Latitude ranges between -90 and 90 degrees, inclusive. Values above or - * below this range will be clamped to the range [-90, 90]. This means - * that if the value specified is less than -90, it will be set to -90. - * And if the value is greater than 90, it will be set to 90. - * * Longitude ranges between -180 and 180 degrees, inclusive. Values above - * or below this range will be wrapped so that they fall within the - * range. For example, a value of -190 will be converted to 170. A value - * of 190 will be converted to -170. This reflects the fact that - * longitudes wrap around the globe. - * - * Although the default map projection associates longitude with the - * x-coordinate of the map, and latitude with the y-coordinate, the - * latitude coordinate is always written first, followed by the longitude. - * Notice that you cannot modify the coordinates of a LatLng. If you want - * to compute another point, you have to create a new one. - */ - export class LatLng { - /** - * Creates a LatLng object representing a geographic point. - * Note the ordering of latitude and longitude. - * @param lat Latitude is specified in degrees within the range [-90, 90]. - * @param lng Longitude is specified in degrees within the range [-180, 180]. - * @param noWrap Set noWrap to true to enable values outside of this range. - */ - constructor(lat: number, lng: number, noWrap?: boolean); - /** Comparison function. */ - equals(other: LatLng): boolean; - /** Returns the latitude in degrees. */ - lat(): number; - /** Returns the longitude in degrees. */ - lng(): number; - /** Converts to string representation. */ - toString(): string; - /** Returns a string of the form "lat,lng". We round the lat/lng values to 6 decimal places by default. */ - toUrlValue(precision?: number): string; - } - - export type LatLngLiteral = { lat: number; lng: number } - - export class LatLngBounds { - constructor(sw?: LatLng, ne?: LatLng); - contains(latLng: LatLng): boolean; - equals(other: LatLngBounds): boolean; - extend(point: LatLng): LatLngBounds; - getCenter(): LatLng; - getNorthEast(): LatLng; - getSouthWest(): LatLng; - intersects(other: LatLngBounds): boolean; - isEmpty(): boolean; - toSpan(): LatLng; - toString(): string; - toUrlValue(precision?: number): string; - union(other: LatLngBounds): LatLngBounds; - } - - export class Point { - /** A point on a two-dimensional plane. */ - constructor(x: number, y: number); - /** The X coordinate */ - x: number; - /** The Y coordinate */ - y: number; - /** Compares two Points */ - equals(other: Point): boolean; - /** Returns a string representation of this Point. */ - toString(): string; - } - - export class Size { - constructor(width: number, height: number, widthUnit?: string, heightUnit?: string); - height: number; - width: number; - equals(other: Size): boolean; - toString(): string; - } - - /***** MVC *****/ - export class MVCObject { - constructor(); - addListener(eventName: string, handler: (...args: any[]) => void): MapsEventListener; - bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: boolean): void; - changed(key: string): void; - get(key: string): any; - notify(key: string): void; - set(key: string, value: any): void; - setValues(values: any): void; - unbind(key: string): void; - unbindAll(): void; - } - - export class MVCArray extends MVCObject { - constructor(array?: any[]); - clear(): void; - forEach(callback: (elem: any, i: number) => void): void; - getArray(): any[]; - getAt(i: number): any; - getLength(): number; - insertAt(i: number, elem: any): void; - pop(): any; - push(elem: any): number; - removeAt(i: number): any; - setAt(i: number, elem: any): void; - } - - /***** Geometry Library *****/ - export module geometry { - export class encoding { - static decodePath(encodedPath: string): LatLng[]; - static encodePath(path: any[]): string; // LatLng[]|MVCArray - } - - export class spherical { - static computeArea(path: any[], radius?: number): number; // LatLng[]|MVCArray - static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; - static computeHeading(from: LatLng, to: LatLng): number; - static computeLength(path: any[], radius?: number): number; // LatLng[]|MVCArray - static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; - static computeOffsetOrigin(to: LatLng, distance: number, heading: number, radius?: number): LatLng; - static computeSignedArea(loop: any[], radius?: number): number; // LatLng[]|MVCArray - static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; - } - - export class poly { - static containsLocation(point: LatLng, polygon: Polygon): boolean; - static isLocationOnEdge(point: LatLng, poly: Polygon|Polyline, tolerance?: number): boolean; - } - } - - /***** AdSense Library *****/ - export module adsense { - export class AdUnit extends MVCObject { - constructor(container: Element, opts: AdUnitOptions); - getBackgroundColor(): string; - getBorderColor(): string; - getChannelNumber(): string; - getContainer(): Element; - getFormat(): AdFormat; - getMap(): Map; - getPosition(): ControlPosition; - getPublisherId(): string; - getTextColor(): string; - getTitleColor(): string; - getUrlColor(): string; - setBackgroundColor(backgroundColor: string): void; - setBorderColor(borderColor: string): void; - setChannelNumber(channelNumber: string): void; - setFormat(format: AdFormat): void; - setMap(map: Map): void; - setPosition(position: ControlPosition): void; - setTextColor(textColor: string): void; - setTitleColor(titleColor: string): void; - setUrlColor(urlColor: string): void; - } - - export interface AdUnitOptions { - backgroundColor?: string; - borderColor?: string; - channelNumber?: string; - format?: AdFormat; - map?: Map; - position?: ControlPosition; - publisherId?: string; - textColor?: string; - titleColor?: string; - urlColor?: string; - } - - export enum AdFormat { - BANNER, - BUTTON, - HALF_BANNER, - LARGE_HORIZONTAL_LINK_UNIT, - LARGE_RECTANGLE, - LARGE_VERTICAL_LINK_UNIT, - LEADERBOARD, - MEDIUM_RECTANGLE, - MEDIUM_VERTICAL_LINK_UNIT, - SKYSCRAPER, - SMALL_HORIZONTAL_LINK_UNIT, - SMALL_RECTANGLE, - SMALL_SQUARE, - SMALL_VERTICAL_LINK_UNIT, - SQUARE, - VERTICAL_BANNER, - WIDE_SKYSCRAPER, - X_LARGE_VERTICAL_LINK_UNIT - } - } - - /***** Places Library *****/ - export module places { - export class Autocomplete extends MVCObject { - constructor(inputField: HTMLInputElement, opts?: AutocompleteOptions); - getBounds(): LatLngBounds; - getPlace(): PlaceResult; - setBounds(bounds: LatLngBounds): void; - setComponentRestrictions(restrictions: ComponentRestrictions): void; - setTypes(types: string[]): void; - } - - export interface AutocompleteOptions { - bounds?: LatLngBounds; - componentRestrictions?: ComponentRestrictions; - types?: string[]; - } - - export interface AutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - terms: PredictionTerm[]; - types: string[] - } - - export interface PredictionTerm { - offset: number; - value: string; - } - - export interface PredictionSubstring { - length: number; - offset: number; - } - - export class AutocompleteService { - constructor(); - getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; - getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; - } - - export interface AutocompletionRequest { - bounds?: LatLngBounds; - componentRestrictions?: ComponentRestrictions; - input: string; - location?: LatLng; - offset?: number; - radius?: number; - types?: string[]; - } - - export interface ComponentRestrictions { - country: string; - } - - export interface PlaceAspectRating { - rating: number; - type: string; - } - - export interface PlaceDetailsRequest { - placeId: string; - } - - export interface PlaceGeometry { - location: LatLng; - viewport: LatLngBounds; - } - - export interface PlacePhoto { - height: number; - html_attributions: string[]; - width: number; - getUrl(opts: PhotoOptions): string; - } - - export interface PhotoOptions { - maxHeight?: number; - maxWidth?: number; - } - - export interface PlaceResult { - address_components: GeocoderAddressComponent[]; - aspects: PlaceAspectRating[]; - formatted_address: string; - formatted_phone_number: string; - geometry: PlaceGeometry; - html_attributions: string[]; - icon: string; - international_phone_number: string; - name: string; - permanently_closed: boolean; - photos: PlacePhoto[]; - place_id: string; - price_level: number; - rating: number; - reviews: PlaceReview[]; - types: string[]; - url: string; - vicinity: string; - website: string; - } - - export interface PlaceReview { - aspects: PlaceAspectRating[]; - author_name: string; - author_url: string; - language: string; - text: string; - } - - export interface PlaceSearchPagination { - nextPage(): void; - hasNextPage: boolean; - } - - export interface PlaceSearchRequest { - bounds: LatLngBounds; - keyword: string; - location: LatLng|LatLngLiteral; - maxPriceLevel?: number; - minPriceLevel?: number; - name: string; - openNow: boolean; - radius: number; - rankBy: RankBy; - types: string[]; - } - - export class PlacesService { - constructor(attrContainer: HTMLDivElement|Map); - getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void): void; - nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void): void; - radarSearch(request: RadarSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; - textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; - } - - export enum PlacesServiceStatus { - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface QueryAutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - terms: PredictionTerm[]; - } - - export interface QueryAutocompletionRequest { - bounds?: LatLngBounds; - input?: string; - location?: LatLng; - radius?: number; - } - - export interface RadarSearchRequest { - bounds: LatLngBounds; - keyword: string; - location: LatLng|LatLngLiteral; - name: string; - radius: number; - types: string[]; - } - - export enum RankBy { - DISTANCE, - PROMINENCE - } - - export class SearchBox extends MVCObject { - constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); - getBounds(): LatLngBounds; - getPlaces(): PlaceResult[]; - setBounds(bounds: LatLngBounds): void; - } - - export interface SearchBoxOptions { - bounds: LatLngBounds; - } - - export interface TextSearchRequest { - bounds: LatLngBounds; - location: LatLng|LatLngLiteral; - query: string; - radius: number; - types: string[]; - } - } - - /***** Drawing Library *****/ - export module drawing { - export class DrawingManager extends MVCObject { - constructor(options?: DrawingManagerOptions); - getDrawingMode(): OverlayType; - getMap(): Map; - setDrawingMode(drawingMode: OverlayType): void; - setMap(map: Map): void; - setOptions(options: DrawingManagerOptions): void; - } - - export interface DrawingManagerOptions { - circleOptions?: CircleOptions; - drawingControl?: boolean; - drawingControlOptions?: DrawingControlOptions; - drawingMode?: OverlayType; - map?: Map; - markerOptions?: MarkerOptions; - polygonOptions?: PolygonOptions; - polylineOptions?: PolylineOptions; - rectangleOptions?: RectangleOptions; - } - - export interface DrawingControlOptions { - drawingModes?: OverlayType[]; - position?: ControlPosition; - } - - export interface OverlayCompleteEvent { - overlay: Marker|Polygon|Polyline|Rectangle|Circle; - type: OverlayType; - } - - export enum OverlayType { - CIRCLE, - MARKER, - POLYGON, - POLYLINE, - RECTANGLE - } - } - - /***** Visualization Library *****/ - export module visualization { - export class MapsEngineLayer extends MVCObject { - constructor(options: MapsEngineLayerOptions) - getLayerId(): string; - getLayerKey(): string; - getMap(): Map; - getMapId(): string; - getOpacity(): number; - getProperties(): MapsEngineLayerProperties; - getStatus(): MapsEngineStatus; - getZIndex(): number; - setLayerId(layerId: string): void; - setLayerKey(layerKey: string): void; - setMap(map: Map): void; - setMapId(mapId: string): void; - setOpacity(opacity: number): void; - setOptions(options: MapsEngineLayerOptions): void; - setZIndex(zIndex: number): void; - } - - export interface MapsEngineLayerOptions { - accessToken?: string; - clickable?: boolean; - fitBounds?: boolean; - layerId?: string; - layerKey?: string; - map?: Map; - mapId?: string; - opacity?: number; - suppressInfoWindows?: boolean; - zIndex?: number; - } - - export interface MapsEngineLayerProperties { - name: string; - } - - export interface MapsEngineMouseEvent { - featureId?: string; - infoWindowHtml?: string; - latLng?: LatLng; - pixelOffset?: Size; - } - - export enum MapsEngineStatus { - INVALID_LAYER, - OK, - UNKNOWN_ERROR - } - - export class HeatmapLayer extends MVCObject { - constructor(opts?: HeatmapLayerOptions); - getData(): MVCArray; - getMap(): Map; - setData(data: MVCArray): void; - setData(data: LatLng[]): void; - setData(data: WeightedLocation[]): void; - setMap(map: Map): void; - } - - export interface HeatmapLayerOptions { - data: any; - dissipating?: boolean; - gradient?: string[]; - map?: Map; - maxIntensity?: number; - opacity?: number; - radius?: number; - } - - export interface WeightedLocation { - location: LatLng; - weight: number; - } - - export class MouseEvent { - stop(): void; - } - - export class MapsEventListener { - - } - } -} +// Type definitions for Google Maps JavaScript API 3.20 +// Project: https://developers.google.com/maps/ +// Definitions by: Folia A/S , Chris Wrench +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* +The MIT License + +Copyright (c) 2012 Folia A/S. http://www.folia.dk + +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. +*/ + +declare module google.maps { + /***** Map *****/ + export class Map extends MVCObject { + constructor(mapDiv: Element, opts?: MapOptions);fitBounds(bounds: LatLngBounds): void; + getBounds(): LatLngBounds; + getCenter(): LatLng; + getDiv(): Element; + getHeading(): number; + getMapTypeId(): MapTypeId|string; + getProjection(): Projection; + getStreetView(): StreetViewPanorama; + getTilt(): number; + getZoom(): number; + panBy(x: number, y: number): void; + panTo(latLng: LatLng|LatLngLiteral): void; + panToBounds(latLngBounds: LatLngBounds): void; + setCenter(latlng: LatLng|LatLngLiteral): void; + setHeading(heading: number): void; + setMapTypeId(mapTypeId: MapTypeId|string): void; + setOptions(options: MapOptions): void; + setStreetView(panorama: StreetViewPanorama): void; + setTilt(tilt: number): void; + setZoom(zoom: number): void; + controls: MVCArray[]; //Array> + data: Data; + mapTypes: MapTypeRegistry; + overlayMapTypes: MVCArray; // MVCArray + } + + export interface MapOptions { + backgroundColor?: string; + center?: LatLng; + disableDefaultUI?: boolean; + disableDoubleClickZoom?: boolean; + draggable?: boolean; + draggableCursor?: string; + draggingCursor?: string; + heading?: number; + keyboardShortcuts?: boolean; + mapMaker?: boolean; + mapTypeControl?: boolean; + mapTypeControlOptions?: MapTypeControlOptions; + mapTypeId?: MapTypeId; + maxZoom?: number; + minZoom?: number; + noClear?: boolean; + overviewMapControl?: boolean; + overviewMapControlOptions?: OverviewMapControlOptions; + panControl?: boolean; + panControlOptions?: PanControlOptions; + rotateControl?: boolean; + rotateControlOptions?: RotateControlOptions; + scaleControl?: boolean; + scaleControlOptions?: ScaleControlOptions; + scrollwheel?: boolean; + streetView?: StreetViewPanorama; + streetViewControl?: boolean; + streetViewControlOptions?: StreetViewControlOptions; + styles?: MapTypeStyle[]; + tilt?: number; + zoom?: number; + zoomControl?: boolean; + zoomControlOptions?: ZoomControlOptions; + } + + export enum MapTypeId { + HYBRID, + ROADMAP, + SATELLITE, + TERRAIN + } + + /***** Controls *****/ + export interface MapTypeControlOptions { + mapTypeIds?: (MapTypeId|string)[]; + position?: ControlPosition; + style?: MapTypeControlStyle; + } + + export enum MapTypeControlStyle { + DEFAULT, + DROPDOWN_MENU, + HORIZONTAL_BAR + } + + export interface OverviewMapControlOptions { + opened?: boolean; + } + + export interface PanControlOptions { + position?: ControlPosition; + } + + export interface RotateControlOptions { + position?: ControlPosition; + } + + export interface ScaleControlOptions { + style?: ScaleControlStyle; + } + + export enum ScaleControlStyle { + DEFAULT + } + + export interface StreetViewControlOptions { + position?: ControlPosition; + } + + export interface ZoomControlOptions { + position?: ControlPosition; + style?: ZoomControlStyle; + } + + export enum ZoomControlStyle { + DEFAULT, + LARGE, + SMALL + } + + export enum ControlPosition { + BOTTOM_CENTER, + BOTTOM_LEFT, + BOTTOM_RIGHT, + LEFT_BOTTOM, + LEFT_CENTER, + LEFT_TOP, + RIGHT_BOTTOM, + RIGHT_CENTER, + RIGHT_TOP, + TOP_CENTER, + TOP_LEFT, + TOP_RIGHT + } + + /***** Data *****/ + export class Data extends MVCObject { + constructor(options?: Data.DataOptions); + add(feature: Data.Feature|Data.FeatureOptions): Data.Feature; + addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; + contains(feature: Data.Feature): boolean; + forEach(callback: (feature: Data.Feature) => void): void; + getControlPosition(): ControlPosition; + getControls(): string[]; + getDrawingMode(): string; + getFeatureById(id: number|string): Data.Feature; + getMap(): Map; + getStyle(): Data.StylingFunction|Data.StyleOptions; + loadGeoJson(url: string, options?: Data.GeoJsonOptions, callback?: (features: Data.Feature[]) => void): void; + overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; + remove(feature: Data.Feature): void; + revertStyle(feature?: Data.Feature): void; + setControlPosition(controlPosition: ControlPosition): void; + setControls(controls: string[]): void; + setDrawingMode(drawingMode: string): void; + setMap(map: Map): void; + setStyle(style: Data.StylingFunction|Data.StyleOptions): void; + toGeoJson(callback: (feature: Object) => void): void; + } + + export module Data { + export interface DataOptions { + controlPosition?: ControlPosition; + controls?: string[]; + drawingMode?: string; + featureFactory?: (geometry: Data.Geometry) => Data.Feature; + map?: Map; + style?: Data.StylingFunction|Data.StyleOptions; + } + + export interface GeoJsonOptions { + idPropertyName?: string; + } + + export interface StyleOptions { + clickable?: boolean; + cursor?: string; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + icon?: string|Icon|Symbol; + shape?: MarkerShape; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + title?: string; + visible?: boolean; + zIndex?: number; + } + + export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions; + + export class Feature { + constructor(options?: Data.FeatureOptions); + forEachProperty(callback: (value: any, name: string) => void): void; + getGeometry(): Data.Geometry; + getId(): number|string; + getProperty(name: string): any; + removeProperty(name: string): void; + setGeometry(newGeometry: Data.Geometry|LatLng|LatLngLiteral): void; + setProperty(name: string, newValue: any): void; + toGeoJson(callback: (feature: Object) => void): void; + } + + export interface FeatureOptions { + geometry?: Data.Geometry|LatLng|LatLngLiteral; + id?: number|string; + properties?: Object; + } + + export class Geometry { + getType(): string; + } + + export class Point extends Data.Geometry { + constructor(latLng: LatLng|LatLngLiteral); + get(): LatLng; + } + + export class MultiPoint extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class LineString extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class MultiLineString extends Data.Geometry { + constructor(elements: (Data.LineString|(LatLng|LatLngLiteral)[])[]); + getArray(): Data.LineString[]; + getAt(n: number): Data.LineString; + getLength(): number; + } + + export class LinearRing extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class Polygon extends Data.Geometry { + constructor(elements: (Data.LinearRing|(LatLng|LatLngLiteral)[])[]); + getArray(): Data.LinearRing[]; + getAt(n: number): Data.LinearRing; + getLength(): number; + } + + export class MultiPolygon extends Data.Geometry { + constructor(elements: (Data.Polygon|(LinearRing|(LatLng|LatLngLiteral)[])[])[]); + getArray(): Data.Polygon[]; + getAt(n: number): Data.Polygon; + getLength(): number; + } + + export class GeometryCollection extends Data.Geometry { + constructor(elements: (Data.Geometry[]|LatLng[]|LatLngLiteral)[]); + getArray(): Data.Geometry[]; + getAt(n: number): Data.Geometry; + getLength(): number; + } + + export interface MouseEvent extends google.maps.MouseEvent { + feature: Data.Feature; + } + + export interface AddFeatureEvent { + feature: Data.Feature; + } + + export interface RemoveFeatureEvent { + feature: Data.Feature; + } + + export interface SetGeometryEvent { + feature: Data.Feature; + newGeometry: Data.Geometry; + oldGeometry: Data.Geometry; + } + + export interface SetPropertyEvent { + feature: Data.Feature; + name: string; + newValue: any; + oldValue: any; + } + + export interface RemovePropertyEvent { + feature: Data.Feature; + name: string; + oldValue: any; + } + } + + /***** Overlays *****/ + export class Marker extends MVCObject { + static MAX_ZINDEX: number; + constructor(opts?: MarkerOptions); + getAnimation(): Animation; + getAttribution(): Attribution; + getClickable(): boolean; + getCursor(): string; + getDraggable(): boolean; + getIcon(): string|Icon|Symbol; + getMap(): Map|StreetViewPanorama; + getOpacity(): number; + getPlace(): Place; + getPosition(): LatLng; + getShape(): MarkerShape; + getTitle(): string; + getVisible(): boolean; + getZIndex(): number; + setAnimation(animation: Animation): void; + setAttribution(attribution: Attribution): void; + setClickable(flag: boolean): void; + setCursor(cursor: string): void; + setDraggable(flag: boolean): void; + setIcon(icon: string|Icon|Symbol): void; + setMap(map: Map|StreetViewPanorama): void; + getOpacity(opacity: number): void; + setOptions(options: MarkerOptions): void; + setPlace(place: Place): void; + setPosition(latlng: LatLng|LatLngLiteral): void; + setShape(shape: MarkerShape): void; + setTitle(title: string): void; + setVisible(visible: boolean): void; + setZIndex(zIndex: number): void; + } + + export interface MarkerOptions { + /** + * The offset from the marker's position to the tip of an InfoWindow + * that has been opened with the marker as anchor. + */ + anchorPoint?: Point; + /** Which animation to play when marker is added to a map. */ + animation?: Animation; + /** + * If true, the marker receives mouse and touch events. + * @default true + */ + clickable?: boolean; + /** Mouse cursor to show on hover. */ + cursor?: string; + /** + * If true, the marker can be dragged. + * @default false + */ + draggable?: boolean; + /** + * Icon for the foreground. + * If a string is provided, it is treated as though it were an Icon with the string as url. + * @type {(string|Icon|Symbol)} + */ + icon?: string|Icon|Symbol; + /** + * Map on which to display Marker. + * @type {(Map|StreetViewPanorama)} + * + */ + map?: Map|StreetViewPanorama; + /** The marker's opacity between 0.0 and 1.0. */ + opacity?: number; + /** + * Optimization renders many markers as a single static element. + * Optimized rendering is enabled by default. + * Disable optimized rendering for animated GIFs or PNGs, or when each + * marker must be rendered as a separate DOM element (advanced usage + * only). + */ + optimized?: boolean; + /** + * Place information, used to identify and describe the place + * associated with this Marker. In this context, 'place' means a + * business, point of interest or geographic location. To allow a user + * to save this place, open an info window anchored on this marker. + * The info window will contain information about the place and an + * option for the user to save it. Only one of position or place can + * be specified. + */ + place?: Place; + /** + * Marker position. Required. + */ + position: LatLng; + /** Image map region definition used for drag/click. */ + shape?: MarkerShape; + /** Rollover text. */ + title?: string; + /** If true, the marker is visible. */ + visible?: boolean; + /** + * All markers are displayed on the map in order of their zIndex, + * with higher values displaying in front of markers with lower values. + * By default, markers are displayed according to their vertical position on screen, + * with lower markers appearing in front of markers further up the screen. + */ + zIndex?: number; + } + + export interface Icon { + /** + * The position at which to anchor an image in correspondence to the + * location of the marker on the map. By default, the anchor is + * located along the center point of the bottom of the image. + */ + anchor?: Point; + /** + * The origin of the label relative to the top-left corner of the icon + * image, if a label is supplied by the marker. By default, the origin + * is located in the center point of the image. + */ + labelOrigin?: Point; + /** + * The position of the image within a sprite, if any. By default, the + * origin is located at the top left corner of the image (0, 0). + */ + origin?: Point; + /** + * The size of the entire image after scaling, if any. Use this + * property to stretch/ shrink an image or a sprite. + */ + scaledSize?: Size; + /** + * The display size of the sprite or image. When using sprites, you + * must specify the sprite size. If the size is not provided, it will + * be set when the image loads. + */ + size?: Size; + /** The URL of the image or sprite sheet. */ + url?: string; + } + + export interface MarkerShape { + coords?: number[]; + type?: string; + } + + export interface Symbol { + /** + * The position of the symbol relative to the marker or polyline. + * The coordinates of the symbol's path are translated left and up by the anchor's x and y coordinates respectively. + * By default, a symbol is anchored at (0, 0). + * The position is expressed in the same coordinate system as the symbol's path. + */ + anchor?: Point; + /** + * The symbol's fill color. + * All CSS3 colors are supported except for extended named colors. For symbol markers, this defaults to 'black'. + * For symbols on polylines, this defaults to the stroke color of the corresponding polyline. + */ + fillColor?: string; + /** + * The symbol's fill opacity. + * @default 0 + */ + fillOpacity?: number; + /** + * The symbol's path, which is a built-in symbol path, or a custom path expressed using SVG path notation. Required. + * @type {(SymbolPath|string)} + */ + path?: SymbolPath|string; + /** + * The angle by which to rotate the symbol, expressed clockwise in degrees. + * Defaults to 0. + * A symbol in an IconSequence where fixedRotation is false is rotated relative to the angle of the edge on which it lies. + */ + rotation?: number; + /** + * The amount by which the symbol is scaled in size. + * For symbol markers, this defaults to 1; after scaling, the symbol may be of any size. + * For symbols on a polyline, this defaults to the stroke weight of the polyline; + * after scaling, the symbol must lie inside a square 22 pixels in size centered at the symbol's anchor. + */ + scale?: number; + /** + * The symbol's stroke color. All CSS3 colors are supported except for extended named colors. + * For symbol markers, this defaults to 'black'. + * For symbols on a polyline, this defaults to the stroke color of the polyline. + */ + strokeColor?: string; + /** + * The symbol's stroke opacity. For symbol markers, this defaults to 1. + * For symbols on a polyline, this defaults to the stroke opacity of the polyline. + */ + strokeOpacity?: number; + /** The symbol's stroke weight. Defaults to the scale of the symbol.v*/ + strokeWeight?: number; + } + + /** Built-in symbol paths. */ + export enum SymbolPath { + /** A backward-pointing closed arrow. */ + BACKWARD_CLOSED_ARROW, + /** A backward-pointing open arrow. */ + BACKWARD_OPEN_ARROW, + /** A circle. */ + CIRCLE, + /** A forward-pointing closed arrow. */ + FORWARD_CLOSED_ARROW, + /** A forward-pointing open arrow. */ + FORWARD_OPEN_ARROW + } + + export enum Animation { + BOUNCE, + DROP + } + + /** + * An overlay that looks like a bubble and is often connected to a marker. + * This class extends MVCObject. + */ + export class InfoWindow extends MVCObject { + /** + * Creates an info window with the given options. An InfoWindow can be + * placed on a map at a particular position or above a marker, + * depending on what is specified in the options. Unless auto-pan is + * disabled, an InfoWindow will pan the map to make itself visible + * when it is opened. After constructing an InfoWindow, you must call + * open to display it on the map. The user can click the close button + * on the InfoWindow to remove it from the map, or the developer can + * call close() for the same effect. + */ + constructor(opts?: InfoWindowOptions); + /** Closes this InfoWindow by removing it from the DOM structure. */ + close(): void; + getContent(): string|Element; + getPosition(): LatLng; + getZIndex(): number; + /** + * Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. + * In the core API, the only anchor is the Marker class. + * However, an anchor can be any MVCObject that exposes a LatLng position property and optionally + * a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). + * The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow. + */ + open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; + setContent(content: string|Node): void; + setOptions(options: InfoWindowOptions): void; + setPosition(position: LatLng): void; + setZIndex(zIndex: number): void; + } + + export interface InfoWindowOptions { + /** + * Content to display in the InfoWindow. This can be an HTML element, a plain-text string, or a string containing HTML. + * The InfoWindow will be sized according to the content. + * To set an explicit size for the content, set content to be a HTML element with that size. + * @type {(string|Node)} + */ + content?: string|Node; + /** + * Disable auto-pan on open. By default, the info window will pan the map so that it is fully visible when it opens. + */ + disableAutoPan?: boolean; + /** + * Maximum width of the infowindow, regardless of content's width. + * This value is only considered if it is set before a call to open. + * To change the maximum width when changing content, call close, setOptions, and then open. + */ + maxWidth?: number; + /** + * The offset, in pixels, of the tip of the info window from the point on the map + * at whose geographical coordinates the info window is anchored. + * If an InfoWindow is opened with an anchor, the pixelOffset will be calculated from the anchor's anchorPoint property. + */ + pixelOffset?: Size; + /** + * The LatLng at which to display this InfoWindow. If the InfoWindow is opened with an anchor, the anchor's position will be used instead. + */ + position?: LatLng|LatLngLiteral; + /** + * All InfoWindows are displayed on the map in order of their zIndex, + * with higher values displaying in front of InfoWindows with lower values. + * By default, InfoWindows are displayed according to their latitude, + * with InfoWindows of lower latitudes appearing in front of InfoWindows at higher latitudes. + * InfoWindows are always displayed in front of markers. + */ + zIndex?: number; + } + + export class Polyline extends MVCObject { + constructor(opts?: PolylineOptions); + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getPath(): MVCArray; // MVCArray + getVisible(): boolean; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map): void; + setOptions(options: PolylineOptions): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; // MVCArray|Array + setVisible(visible: boolean): void; + } + + export interface PolylineOptions { + clickable?: boolean; + draggable?: boolean; + editable?: boolean; + geodesic?: boolean; + icons?: IconSequence[]; + map?: Map; + path?: MVCArray|LatLng[]|LatLngLiteral[]; // MVCArray|Array + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: boolean; + zIndex?: number; + } + + export interface IconSequence { + fixedRotation?: boolean; + icon?: Symbol; + offset?: string; + repeat?: string; + } + + export class Polygon extends MVCObject { + constructor(opts?: PolygonOptions); + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getPath(): MVCArray; // MVCArray + getPaths(): MVCArray; // MVCArray> + getVisible(): boolean; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map): void; + setOptions(options: PolygonOptions): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; + setPaths(paths: MVCArray): void; + setPaths(paths: MVCArray[]): void; + setPaths(path: LatLng[]): void; + setPaths(path: LatLng[][]): void; + setPaths(path: LatLngLiteral[]): void; + setPaths(path: LatLngLiteral[][]): void; + setVisible(visible: boolean): void; + } + + export interface PolygonOptions { + clickable?: boolean; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + geodesic?: boolean; + map?: Map; + paths?: any[]; // MVCArray>|MVCArray|Array>|Array + strokeColor?: string; + strokeOpacity?: number; + strokePosition?: StrokePosition; + strokeWeight?: number; + visible?: boolean; + zIndex?: number; + } + + export interface PolyMouseEvent { + edge?: number; + path?: number; + vertex?: number; + } + + export class Rectangle extends MVCObject { + constructor(opts?: RectangleOptions); + getBounds(): LatLngBounds; + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getVisible(): boolean; + setBounds(bounds: LatLngBounds): void; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map): void; + setOptions(options: RectangleOptions): void; + setVisible(visible: boolean): void; + } + + export interface RectangleOptions { + bounds?: LatLngBounds; + clickable?: boolean; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + map?: Map; + strokeColor?: string; + strokeOpacity?: number; + strokePosition?: StrokePosition; + strokeWeight?: number; + visible?: boolean; + zIndex?: number; + } + + export class Circle extends MVCObject { + constructor(opts?: CircleOptions); + getBounds(): LatLngBounds; + getCenter(): LatLng; + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getRadius(): number; + getVisible(): boolean; + setCenter(center: LatLng|LatLngLiteral): void; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map): void; + setOptions(options: CircleOptions): void; + setRadius(radius: number): void; + setVisible(visible: boolean): void; + } + + export interface CircleOptions { + center?: LatLng; + clickable?: boolean; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + map?: Map; + radius?: number; + strokeColor?: string; + strokeOpacity?: number; + strokePosition?: StrokePosition; + strokeWeight?: number; + visible?: boolean; + zIndex?: number; + } + + export enum StrokePosition { + CENTER, + INSIDE, + OUTSIDE + } + + export class GroundOverlay extends MVCObject { + constructor(url: string, bounds: LatLngBounds, opts?: GroundOverlayOptions); + getBounds(): LatLngBounds; + getMap(): Map; + getOpacity(): number; + getUrl(): string; + setMap(map: Map): void; + setOpacity(opacity: number): void; + } + + export interface GroundOverlayOptions { + clickable?: boolean; + map?: Map; + opacity?: number; + } + + export class OverlayView extends MVCObject { + draw(): void; + getMap(): Map|StreetViewPanorama; + getPanes(): MapPanes; + getProjection(): MapCanvasProjection; + onAdd(): void; + onRemove(): void; + setMap(map: Map|StreetViewPanorama): void; + } + + export interface MapPanes { + floatPane: Element; + mapPane: Element; + markerLayer: Element; + overlayLayer: Element; + overlayMouseTarget: Element; + } + + export class MapCanvasProjection extends MVCObject { + fromContainerPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; + fromDivPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; + fromLatLngToContainerPixel(latLng: LatLng): Point; + fromLatLngToDivPixel(latLng: LatLng): Point; + getWorldWidth(): number; + } + + /***** Services *****/ + export class Geocoder { + geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; + } + + export interface GeocoderRequest { + address?: string; + bounds?: LatLngBounds; + componentRestrictions: GeocoderComponentRestrictions; + location?: LatLng|LatLngLiteral; + region?: string; + } + + export interface GeocoderComponentRestrictions { + administrativeArea?: string; + country?: string; + locality?: string; + postalCode?: string; + route?: string; + } + + export enum GeocoderStatus { + ERROR, + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface GeocoderResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + geometry: GeocoderGeometry; + partial_match: boolean; + postcode_localities: string[] + types: string[]; + } + + export interface GeocoderAddressComponent { + long_name: string; + short_name: string; + types: string[]; + } + + export interface GeocoderGeometry { + bounds: LatLngBounds; + location: LatLng; + location_type: GeocoderLocationType; + viewport: LatLngBounds; + } + + export enum GeocoderLocationType { + APPROXIMATE, + GEOMETRIC_CENTER, + RANGE_INTERPOLATED, + ROOFTOP + } + + export class DirectionsRenderer extends MVCObject { + constructor(opts?: DirectionsRendererOptions); + getDirections(): DirectionsResult; + getMap(): Map; + getPanel(): Element; + getRouteIndex(): number; + setDirections(directions: DirectionsResult): void; + setMap(map: Map): void; + setOptions(options: DirectionsRendererOptions): void; + setPanel(panel: Element): void; + setRouteIndex(routeIndex: number): void; + } + + export interface DirectionsRendererOptions { + directions?: DirectionsResult; + draggable?: boolean; + hideRouteList?: boolean; + infoWindow?: InfoWindow; + map?: Map; + markerOptions?: MarkerOptions; + panel?: Element; + polylineOptions?: PolylineOptions; + preserveViewport?: boolean; + routeIndex?: number; + suppressBicyclingLayer?: boolean; + suppressInfoWindows?: boolean; + suppressMarkers?: boolean; + suppressPolylines?: boolean; + } + + export class DirectionsService { + route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; + } + + export interface DirectionsRequest { + avoidFerries?: boolean; + avoidHighways?: boolean; + avoidTolls?: boolean; + destination?: LatLng|string; + durationInTraffic?: boolean; + optimizeWaypoints?: boolean; + origin?: LatLng|string; + provideRouteAlternatives?: boolean; + region?: string; + transitOptions?: TransitOptions; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + waypoints?: DirectionsWaypoint[]; + } + + export enum TravelMode { + BICYCLING, + DRIVING, + TRANSIT, + WALKING + } + + export enum UnitSystem { + IMPERIAL, + METRIC + } + + export interface TransitOptions { + arrivalTime?: Date; + departureTime?: Date; + modes: TransitMode[]; + routingPreference: TransitRoutePreference; + } + + export enum TransitMode { + BUS, + RAIL, + SUBWAY, + TRAIN, + TRAM + } + + export enum TransitRoutePreference + { + FEWER_TRANSFERS, + LESS_WALKING + } + + export interface TransitFare { } + + export interface DirectionsWaypoint { + location: LatLng|string; + stopover: boolean; + } + + export enum DirectionsStatus { + INVALID_REQUEST, + MAX_WAYPOINTS_EXCEEDED, + NOT_FOUND, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface DirectionsResult { + routes: DirectionsRoute[]; + } + + export interface DirectionsRoute { + bounds: LatLngBounds; + copyrights: string; + fare: TransitFare; + legs: DirectionsLeg[]; + overview_path: LatLng[]; + overview_polyline: string; + warnings: string[]; + waypoint_order: number[]; + } + + export interface DirectionsLeg { + arrival_time: Time; + departure_time: Time; + distance: Distance; + duration: Duration; + duration_in_traffic: Duration; + end_address: string; + end_location: LatLng; + start_address: string; + start_location: LatLng; + steps: DirectionsStep[]; + via_waypoints: LatLng[]; + } + + export interface DirectionsStep { + distance: Distance; + duration: Duration; + end_location: LatLng; + instructions: string; + path: LatLng[]; + start_location: LatLng; + steps: DirectionsStep; + transit: TransitDetails; + travel_mode: TravelMode; + } + + export interface Distance { + text: string; + value: number; + } + + export interface Duration { + text: string; + value: number; + } + + export interface Time { + text: string; + time_zone: string; + value: Date; + } + + export interface TransitDetails { + arrival_stop: TransitStop; + arrival_time: Time; + departure_stop: TransitStop; + departure_time: Time; + headsign: string; + headway: number; + line: TransitLine; + num_stops: number; + } + + export interface TransitStop { + location: LatLng; + name: string; + } + + export interface TransitLine { + agencies: TransitAgency[]; + color: string; + icon: string; + name: string; + short_name: string; + text_color: string; + url: string; + vehicle: TransitVehicle; + } + + export interface TransitAgency { + name: string; + phone: string; + url: string; + } + + export interface TransitVehicle { + icon: string; + local_icon: string; + name: string; + type: VehicleType; + } + + export enum VehicleType + { + BUS, + CABLE_CAR, + COMMUTER_TRAIN, + FERRY, + FUNICULAR, + GONDOLA_LIFT, + HEAVY_RAIL, + HIGH_SPEED_TRAIN, + INTERCITY_BUS, + METRO_RAIL, + MONORAIL, + OTHER, + RAIL, + SHARE_TAXI, + SUBWAY, + TRAM, + TROLLEYBUS + } + + export class ElevationService { + getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + } + + export interface LocationElevationRequest { + locations: LatLng[]; + } + + export interface PathElevationRequest { + path?: LatLng[]; + samples?: number; + } + + export interface ElevationResult { + elevation: number; + location: LatLng; + resolution: number; + } + + export enum ElevationStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export class MaxZoomService { + getMaxZoomAtLatLng(latlng: LatLng|LatLngLiteral, callback: (result: MaxZoomResult) => void ): void; + } + + export interface MaxZoomResult { + status: MaxZoomStatus; + zoom: number; + } + + export enum MaxZoomStatus { + ERROR, + OK + } + + export class DistanceMatrixService { + getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; + } + + export interface DistanceMatrixRequest { + avoidFerries?: boolean; + avoidHighways?: boolean; + avoidTolls?: boolean; + destinations?: LatLng[]|string[]; + durationInTraffic?: boolean; + origins?: LatLng[]|string[]; + region?: string; + transitOptions?: TransitOptions; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + } + + export interface DistanceMatrixResponse { + destinationAddresses: string[]; + originAddresses: string[]; + rows: DistanceMatrixResponseRow[]; + } + + export interface DistanceMatrixResponseRow { + elements: DistanceMatrixResponseElement[]; + } + + export interface DistanceMatrixResponseElement { + distance: Distance; + duration: Duration; + fare: TransitFare; + status: DistanceMatrixElementStatus; + } + + export enum DistanceMatrixStatus { + INVALID_REQUEST, + MAX_DIMENSIONS_EXCEEDED, + MAX_ELEMENTS_EXCEEDED, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export enum DistanceMatrixElementStatus { + NOT_FOUND, + OK, + ZERO_RESULTS + } + + /***** Save to Google Maps *****/ + export interface Attribution { + iosDeepLinkId?: string; + source?: string; + webUrl?: string; + } + + export interface Place { + location?: LatLng|LatLngLiteral; + placeId?: string; + query?: string; + } + + export class SaveWidget { + constructor(container: Node, opts?: SaveWidgetOptions); + getAttribution(): Attribution; + getPlace(): Place; + setAttribution(attribution: Attribution): void; + setOptions(opts: SaveWidgetOptions): void; + setPlace(place: Place): void; + } + + export interface SaveWidgetOptions{ + attribution?: Attribution; + place?: Place; + } + + /***** Map Types *****/ + export interface MapType { + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + projection?: Projection; + radius?: number; + tileSize?: Size; + } + + export class MapTypeRegistry extends MVCObject { + constructor(); + set(id: string, mapType: MapType): void; + } + + export interface Projection { + fromLatLngToPoint(latLng: LatLng, point?: Point): Point; + fromPointToLatLng(pixel: Point, noWrap?: boolean): LatLng; + } + + export class ImageMapType extends MVCObject implements MapType { + constructor(opts: ImageMapTypeOptions); + getOpacity(): number; + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + setOpacity(opacity: number): void; + } + + export interface ImageMapTypeOptions { + alt?: string; + getTileUrl(tileCoord: Point, zoom: number): string; + maxZoom?: number; + minZoom?: number; + name?: string; + opacity?: number; + tileSize?: Size; + } + + export class StyledMapType extends MVCObject implements MapType { + constructor(styles: MapTypeStyle[], options?: StyledMapTypeOptions); + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + } + + export interface StyledMapTypeOptions { + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + } + + export interface MapTypeStyle { + elementType?: MapTypeStyleElementType; + featureType?: MapTypeStyleFeatureType; + stylers?: MapTypeStyler[]; + } + + export interface MapTypeStyleFeatureType { + administrative?: { + country?: string; + land_parcel?: string; + locality?: string; + neighborhood?: string; + province?: string; + }; + all?: string; + landscape?: { + man_made?: string; + natural?: { + landcover?: string; + terrain?: string; + }; + }; + poi?: { + attraction?: string; + business?: string; + government?: string; + medical?: string; + park?: string; + place_of_worship?: string; + school?: string; + sports_complex?: string; + }; + road?: { + arterial?: string; + highway?: { + controlled_access?: string; + }; + local?: string; + }; + transit?: { + line?: string; + station?: { + airport?: string; + bus?: string; + rail?: string; + }; + }; + water?: string; + } + + export interface MapTypeStyleElementType { + all?: string; + geometry?: { + fill?: string; + stroke?: string; + }; + labels?: { + icon?: string; + text?: { + fill?: string; + stroke?: string; + } + }; + } + + export interface MapTypeStyler { + color?: string; + gamma?: number; + hue?: string; + invert_lightness?: boolean; + lightness?: number; + saturation?: number; + visibility?: string; + } + + /***** Layers *****/ + export class BicyclingLayer extends MVCObject { + constructor(); + getMap(): Map; + setMap(map: Map): void; + } + + export class FusionTablesLayer extends MVCObject { + constructor(options: FusionTablesLayerOptions); + getMap(): Map; + setMap(map: Map): void; + setOptions(options: FusionTablesLayerOptions): void; + } + + export interface FusionTablesLayerOptions { + clickable?: boolean; + heatmap?: FusionTablesHeatmap; + map?: Map; + query?: FusionTablesQuery; + styles?: FusionTablesStyle[]; + suppressInfoWindows?: boolean; + } + + export interface FusionTablesQuery { + from?: string; + limit?: number; + offset?: number; + orderBy?: string; + select?: string; + where?: string; + } + + export interface FusionTablesStyle { + markerOptions?: FusionTablesMarkerOptions; + polygonOptions?: FusionTablesPolygonOptions; + polylineOptions?: FusionTablesPolylineOptions; + where?: string; + } + + export interface FusionTablesHeatmap { + enabled: boolean; + } + + export interface FusionTablesMarkerOptions { + iconName: string; + } + + export interface FusionTablesPolygonOptions { + fillColor?: string; + fillOpacity?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesPolylineOptions { + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesMouseEvent { + infoWindowHtml?: string; + latLng?: LatLng; + pixelOffset?: Size; + row?: Object; // Object + } + + export interface FusionTablesCell { + columnName?: string; + value?: string; + } + + export class KmlLayer extends MVCObject { + constructor(opts?: KmlLayerOptions); + getDefaultViewport(): LatLngBounds; + getMap(): Map; + getMetadata(): KmlLayerMetadata; + getStatus(): KmlLayerStatus; + getUrl(): string; + getZIndex(): number; + setMap(map: Map): void; + setUrl(url: string): void; + setZIndez(zIndex: number): void; + } + + export interface KmlLayerOptions { + clickable?: boolean; + map?: Map; + preserveViewport?: boolean; + screenOverlays?: boolean; + suppressInfoWindows?: boolean; + url?: string; + zIndex?: number; + } + + export interface KmlLayerMetadata { + author: KmlAuthor; + description: string; + hasScreenOverlays: boolean; + name: string; + snippet: string; + } + + export enum KmlLayerStatus { + DOCUMENT_NOT_FOUND, + DOCUMENT_TOO_LARGE, + FETCH_ERROR, + INVALID_DOCUMENT, + INVALID_REQUEST, + LIMITS_EXCEEDED, + OK, + TIMED_OUT, + UNKNOWN + } + + export interface KmlMouseEvent { + featureData: KmlFeatureData; + latLng: LatLng; + pixelOffset: Size; + } + + export interface KmlFeatureData { + author: KmlAuthor; + description: string; + id: string; + infoWindowHtml: string; + name: string; + snippet: string; + } + + export interface KmlAuthor { + email: string; + name: string; + uri: string; + } + + export class TrafficLayer extends MVCObject { + constructor(); + getMap(): void; + setMap(map: Map): void; + } + + export class TransitLayer extends MVCObject { + constructor(); + getMap(): void; + setMap(map: Map): void; + } + + /***** Street View *****/ + export class StreetViewPanorama { + constructor(container: Element, opts?: StreetViewPanoramaOptions); + controls: MVCArray[]; // Array> + getLinks(): StreetViewLink[]; + getLocation(): StreetViewLocation; + getPano(): string; + getPhotographerPov(): StreetViewPov; + getPosition(): LatLng; + getPov(): StreetViewPov; + getStatus(): StreetViewStatus; + getVisible(): boolean; + getZoom(): number; + registerPanoProvider(provider: (input: string) => StreetViewPanoramaData): void; + setLinks(links: Array): void; + setOptions(options: StreetViewPanoramaOptions): void; + setPano(pano: string): void; + setPosition(latLng: LatLng|LatLngLiteral): void; + setPov(pov: StreetViewPov): void; + setVisible(flag: boolean): void; + setZoom(zoom: number): void; + } + + export interface StreetViewPanoramaOptions { + addressControl?: boolean; + addressControlOptions?: StreetViewAddressControlOptions; + clickToGo?: boolean; + disableDefaultUi?: boolean; + disableDoubleClickZoom?: boolean; + enableCloseButton?: boolean; + imageDateControl?: boolean; + linksControl?: boolean; + panControl?: boolean; + panControlOptions?: PanControlOptions; + pano?: string; + panoProvider?: (input: string) => StreetViewPanoramaData; + position?: LatLng|LatLngLiteral; + pov?: StreetViewPov; + scrollwheel?: boolean; + visible?: boolean; + zoomControl?: boolean; + zoomControlOptions?: ZoomControlOptions; + } + + export interface StreetViewAddressControlOptions { + position?: ControlPosition; + } + + export interface StreetViewLink { + description?: string; + heading?: number; + pano?: string; + } + + export interface StreetViewPov { + heading?: number; + pitch?: number; + } + + export interface StreetViewPanoramaData { + copyright?: string; + imageDate?: string; + links?: StreetViewLink[]; + location?: StreetViewLocation; + tiles?: StreetViewTileData; + } + + export interface StreetViewLocation { + description?: string; + latLng?: LatLng; + pano?: string; + shortDescription?: string; + } + + export interface StreetViewTileData { + getTileUrl(pano: string, tileZoom: number, tileX: number, tileY: number): string; + centerHeading?: number; + tileSize?: Size; + worldSize?: Size; + } + + export class StreetViewService { + getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void): void; + getPanoramaByLocation(latlng: LatLng|LatLngLiteral, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ): void; + } + + export enum StreetViewStatus { + OK, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export class StreetViewCoverageLayer extends MVCObject { + getMap(): Map; + setMap(map: Map): void; + } + + /***** Events *****/ + export interface MapsEventListener { } + + export class event { + static addDomListener(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; + static addDomListenerOnce(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; + static addListener(instance: Object, eventName: string, handler: Function): MapsEventListener; + static addListenerOnce(instance: Object, eventName: string, handler: Function): MapsEventListener; + static clearInstanceListeners(instance: Object): void; + static clearListeners(instance: Object, eventName: string): void; + static removeListener(listener: MapsEventListener): void; + static trigger(instance: any, eventName: string, ...args: any[]): void; + } + + export interface MouseEvent { + stop(): void; + latLng: LatLng; + } + + /* **** Base **** */ + + /** + * A LatLng is a point in geographical coordinates: latitude and longitude. + * + * * Latitude ranges between -90 and 90 degrees, inclusive. Values above or + * below this range will be clamped to the range [-90, 90]. This means + * that if the value specified is less than -90, it will be set to -90. + * And if the value is greater than 90, it will be set to 90. + * * Longitude ranges between -180 and 180 degrees, inclusive. Values above + * or below this range will be wrapped so that they fall within the + * range. For example, a value of -190 will be converted to 170. A value + * of 190 will be converted to -170. This reflects the fact that + * longitudes wrap around the globe. + * + * Although the default map projection associates longitude with the + * x-coordinate of the map, and latitude with the y-coordinate, the + * latitude coordinate is always written first, followed by the longitude. + * Notice that you cannot modify the coordinates of a LatLng. If you want + * to compute another point, you have to create a new one. + */ + export class LatLng { + /** + * Creates a LatLng object representing a geographic point. + * Note the ordering of latitude and longitude. + * @param lat Latitude is specified in degrees within the range [-90, 90]. + * @param lng Longitude is specified in degrees within the range [-180, 180]. + * @param noWrap Set noWrap to true to enable values outside of this range. + */ + constructor(lat: number, lng: number, noWrap?: boolean); + /** Comparison function. */ + equals(other: LatLng): boolean; + /** Returns the latitude in degrees. */ + lat(): number; + /** Returns the longitude in degrees. */ + lng(): number; + /** Converts to string representation. */ + toString(): string; + /** Returns a string of the form "lat,lng". We round the lat/lng values to 6 decimal places by default. */ + toUrlValue(precision?: number): string; + } + + export type LatLngLiteral = { lat: number; lng: number } + + export class LatLngBounds { + constructor(sw?: LatLng, ne?: LatLng); + contains(latLng: LatLng): boolean; + equals(other: LatLngBounds): boolean; + extend(point: LatLng): LatLngBounds; + getCenter(): LatLng; + getNorthEast(): LatLng; + getSouthWest(): LatLng; + intersects(other: LatLngBounds): boolean; + isEmpty(): boolean; + toSpan(): LatLng; + toString(): string; + toUrlValue(precision?: number): string; + union(other: LatLngBounds): LatLngBounds; + } + + export class Point { + /** A point on a two-dimensional plane. */ + constructor(x: number, y: number); + /** The X coordinate */ + x: number; + /** The Y coordinate */ + y: number; + /** Compares two Points */ + equals(other: Point): boolean; + /** Returns a string representation of this Point. */ + toString(): string; + } + + export class Size { + constructor(width: number, height: number, widthUnit?: string, heightUnit?: string); + height: number; + width: number; + equals(other: Size): boolean; + toString(): string; + } + + /***** MVC *****/ + export class MVCObject { + constructor(); + addListener(eventName: string, handler: (...args: any[]) => void): MapsEventListener; + bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: boolean): void; + changed(key: string): void; + get(key: string): any; + notify(key: string): void; + set(key: string, value: any): void; + setValues(values: any): void; + unbind(key: string): void; + unbindAll(): void; + } + + export class MVCArray extends MVCObject { + constructor(array?: any[]); + clear(): void; + forEach(callback: (elem: any, i: number) => void): void; + getArray(): any[]; + getAt(i: number): any; + getLength(): number; + insertAt(i: number, elem: any): void; + pop(): any; + push(elem: any): number; + removeAt(i: number): any; + setAt(i: number, elem: any): void; + } + + /***** Geometry Library *****/ + export module geometry { + export class encoding { + static decodePath(encodedPath: string): LatLng[]; + static encodePath(path: any[]): string; // LatLng[]|MVCArray + } + + export class spherical { + static computeArea(path: any[], radius?: number): number; // LatLng[]|MVCArray + static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; + static computeHeading(from: LatLng, to: LatLng): number; + static computeLength(path: any[], radius?: number): number; // LatLng[]|MVCArray + static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; + static computeOffsetOrigin(to: LatLng, distance: number, heading: number, radius?: number): LatLng; + static computeSignedArea(loop: any[], radius?: number): number; // LatLng[]|MVCArray + static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; + } + + export class poly { + static containsLocation(point: LatLng, polygon: Polygon): boolean; + static isLocationOnEdge(point: LatLng, poly: Polygon|Polyline, tolerance?: number): boolean; + } + } + + /***** AdSense Library *****/ + export module adsense { + export class AdUnit extends MVCObject { + constructor(container: Element, opts: AdUnitOptions); + getBackgroundColor(): string; + getBorderColor(): string; + getChannelNumber(): string; + getContainer(): Element; + getFormat(): AdFormat; + getMap(): Map; + getPosition(): ControlPosition; + getPublisherId(): string; + getTextColor(): string; + getTitleColor(): string; + getUrlColor(): string; + setBackgroundColor(backgroundColor: string): void; + setBorderColor(borderColor: string): void; + setChannelNumber(channelNumber: string): void; + setFormat(format: AdFormat): void; + setMap(map: Map): void; + setPosition(position: ControlPosition): void; + setTextColor(textColor: string): void; + setTitleColor(titleColor: string): void; + setUrlColor(urlColor: string): void; + } + + export interface AdUnitOptions { + backgroundColor?: string; + borderColor?: string; + channelNumber?: string; + format?: AdFormat; + map?: Map; + position?: ControlPosition; + publisherId?: string; + textColor?: string; + titleColor?: string; + urlColor?: string; + } + + export enum AdFormat { + BANNER, + BUTTON, + HALF_BANNER, + LARGE_HORIZONTAL_LINK_UNIT, + LARGE_RECTANGLE, + LARGE_VERTICAL_LINK_UNIT, + LEADERBOARD, + MEDIUM_RECTANGLE, + MEDIUM_VERTICAL_LINK_UNIT, + SKYSCRAPER, + SMALL_HORIZONTAL_LINK_UNIT, + SMALL_RECTANGLE, + SMALL_SQUARE, + SMALL_VERTICAL_LINK_UNIT, + SQUARE, + VERTICAL_BANNER, + WIDE_SKYSCRAPER, + X_LARGE_VERTICAL_LINK_UNIT + } + } + + /***** Places Library *****/ + export module places { + export class Autocomplete extends MVCObject { + constructor(inputField: HTMLInputElement, opts?: AutocompleteOptions); + getBounds(): LatLngBounds; + getPlace(): PlaceResult; + setBounds(bounds: LatLngBounds): void; + setComponentRestrictions(restrictions: ComponentRestrictions): void; + setTypes(types: string[]): void; + } + + export interface AutocompleteOptions { + bounds?: LatLngBounds; + componentRestrictions?: ComponentRestrictions; + types?: string[]; + } + + export interface AutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + types: string[] + } + + export interface PredictionTerm { + offset: number; + value: string; + } + + export interface PredictionSubstring { + length: number; + offset: number; + } + + export class AutocompleteService { + constructor(); + getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; + getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; + } + + export interface AutocompletionRequest { + bounds?: LatLngBounds; + componentRestrictions?: ComponentRestrictions; + input: string; + location?: LatLng; + offset?: number; + radius?: number; + types?: string[]; + } + + export interface ComponentRestrictions { + country: string; + } + + export interface PlaceAspectRating { + rating: number; + type: string; + } + + export interface PlaceDetailsRequest { + placeId: string; + } + + export interface PlaceGeometry { + location: LatLng; + viewport: LatLngBounds; + } + + export interface PlacePhoto { + height: number; + html_attributions: string[]; + width: number; + getUrl(opts: PhotoOptions): string; + } + + export interface PhotoOptions { + maxHeight?: number; + maxWidth?: number; + } + + export interface PlaceResult { + address_components: GeocoderAddressComponent[]; + aspects: PlaceAspectRating[]; + formatted_address: string; + formatted_phone_number: string; + geometry: PlaceGeometry; + html_attributions: string[]; + icon: string; + international_phone_number: string; + name: string; + permanently_closed: boolean; + photos: PlacePhoto[]; + place_id: string; + price_level: number; + rating: number; + reviews: PlaceReview[]; + types: string[]; + url: string; + vicinity: string; + website: string; + } + + export interface PlaceReview { + aspects: PlaceAspectRating[]; + author_name: string; + author_url: string; + language: string; + text: string; + } + + export interface PlaceSearchPagination { + nextPage(): void; + hasNextPage: boolean; + } + + export interface PlaceSearchRequest { + bounds: LatLngBounds; + keyword: string; + location: LatLng|LatLngLiteral; + maxPriceLevel?: number; + minPriceLevel?: number; + name: string; + openNow: boolean; + radius: number; + rankBy: RankBy; + types: string[]; + } + + export class PlacesService { + constructor(attrContainer: HTMLDivElement|Map); + getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void): void; + nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void): void; + radarSearch(request: RadarSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; + textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; + } + + export enum PlacesServiceStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface QueryAutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + } + + export interface QueryAutocompletionRequest { + bounds?: LatLngBounds; + input?: string; + location?: LatLng; + radius?: number; + } + + export interface RadarSearchRequest { + bounds?: LatLngBounds; + keyword: string; + location: LatLng|LatLngLiteral; + name: string; + radius: number; + types: string[]; + } + + export enum RankBy { + DISTANCE, + PROMINENCE + } + + export class SearchBox extends MVCObject { + constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); + getBounds(): LatLngBounds; + getPlaces(): PlaceResult[]; + setBounds(bounds: LatLngBounds): void; + } + + export interface SearchBoxOptions { + bounds: LatLngBounds; + } + + export interface TextSearchRequest { + bounds?: LatLngBounds; + location: LatLng|LatLngLiteral; + query: string; + radius: number; + types: string[]; + } + } + + /***** Drawing Library *****/ + export module drawing { + export class DrawingManager extends MVCObject { + constructor(options?: DrawingManagerOptions); + getDrawingMode(): OverlayType; + getMap(): Map; + setDrawingMode(drawingMode: OverlayType): void; + setMap(map: Map): void; + setOptions(options: DrawingManagerOptions): void; + } + + export interface DrawingManagerOptions { + circleOptions?: CircleOptions; + drawingControl?: boolean; + drawingControlOptions?: DrawingControlOptions; + drawingMode?: OverlayType; + map?: Map; + markerOptions?: MarkerOptions; + polygonOptions?: PolygonOptions; + polylineOptions?: PolylineOptions; + rectangleOptions?: RectangleOptions; + } + + export interface DrawingControlOptions { + drawingModes?: OverlayType[]; + position?: ControlPosition; + } + + export interface OverlayCompleteEvent { + overlay: Marker|Polygon|Polyline|Rectangle|Circle; + type: OverlayType; + } + + export enum OverlayType { + CIRCLE, + MARKER, + POLYGON, + POLYLINE, + RECTANGLE + } + } + + /***** Visualization Library *****/ + export module visualization { + export class MapsEngineLayer extends MVCObject { + constructor(options: MapsEngineLayerOptions) + getLayerId(): string; + getLayerKey(): string; + getMap(): Map; + getMapId(): string; + getOpacity(): number; + getProperties(): MapsEngineLayerProperties; + getStatus(): MapsEngineStatus; + getZIndex(): number; + setLayerId(layerId: string): void; + setLayerKey(layerKey: string): void; + setMap(map: Map): void; + setMapId(mapId: string): void; + setOpacity(opacity: number): void; + setOptions(options: MapsEngineLayerOptions): void; + setZIndex(zIndex: number): void; + } + + export interface MapsEngineLayerOptions { + accessToken?: string; + clickable?: boolean; + fitBounds?: boolean; + layerId?: string; + layerKey?: string; + map?: Map; + mapId?: string; + opacity?: number; + suppressInfoWindows?: boolean; + zIndex?: number; + } + + export interface MapsEngineLayerProperties { + name: string; + } + + export interface MapsEngineMouseEvent { + featureId?: string; + infoWindowHtml?: string; + latLng?: LatLng; + pixelOffset?: Size; + } + + export enum MapsEngineStatus { + INVALID_LAYER, + OK, + UNKNOWN_ERROR + } + + export class HeatmapLayer extends MVCObject { + constructor(opts?: HeatmapLayerOptions); + getData(): MVCArray; + getMap(): Map; + setData(data: MVCArray): void; + setData(data: LatLng[]): void; + setData(data: WeightedLocation[]): void; + setMap(map: Map): void; + } + + export interface HeatmapLayerOptions { + data: any; + dissipating?: boolean; + gradient?: string[]; + map?: Map; + maxIntensity?: number; + opacity?: number; + radius?: number; + } + + export interface WeightedLocation { + location: LatLng; + weight: number; + } + + export class MouseEvent { + stop(): void; + } + + export class MapsEventListener { + + } + } +} diff --git a/gulp-concat/gulp-concat-tests.ts b/gulp-concat/gulp-concat-tests.ts index a2a475b97..68f6e529d 100644 --- a/gulp-concat/gulp-concat-tests.ts +++ b/gulp-concat/gulp-concat-tests.ts @@ -18,6 +18,6 @@ gulp.task("concat:newLine", () => { gulp.task("concat:vinyl", () => { gulp.src(["file*.txt"]) - .pipe(concat({ path: "file.txt", stat: { mode: 0666 } })) + .pipe(concat({ path: "file.txt", stat: { mode: parseInt("0666", 8) } })) .pipe(gulp.dest("build")); }); diff --git a/hooker/hooker-tests.ts b/hooker/hooker-tests.ts index d9aea606c..edd2c25e9 100644 --- a/hooker/hooker-tests.ts +++ b/hooker/hooker-tests.ts @@ -11,11 +11,11 @@ function tests() { hello: 'world' }; hooker.hook(objectToHook, 'hello', () => { }); - hooker.hook(objectToHook, 'hello', () => { + hooker.hook(objectToHook, 'hello', (): any => { return null; }); hooker.hook(objectToHook, ['hello', 'foo'], () => { }); - hooker.hook(objectToHook, ['hello', 'bar'], () => { + hooker.hook(objectToHook, ['hello', 'bar'], (): any => { return null; }); hooker.hook(objectToHook, 'bar', () => { diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 3d24c9b96..060335af0 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -85,8 +85,8 @@ interface I18nextStatic { toLanguages(language: string): string[]; regexEscape(str: string): string; }; - init(callback?: (t: (key: string, options?: any) => string) => void ): JQueryDeferred; - init(options?: I18nextOptions, callback?: (t: (key: string, options?: any) => string) => void ): JQueryDeferred; + init(callback?: (err: any, t: (key: string, options?: any) => string) => void ): JQueryDeferred; + init(options?: I18nextOptions, callback?: (err: any, t: (key: string, options?: any) => string) => void ): JQueryDeferred; lng(): string; loadNamespace(namespace: string, callback?: () => void ): void; loadNamespaces(namespaces: string[], callback?: () => void ): void; @@ -100,10 +100,10 @@ interface I18nextStatic { rules: any; setCurrentLng: (language: string) => void; }; - preload(language: string, callback?: (t: (key: string, options?: any) => string) => void ): void; - preload(languages: string[], callback?: (t: (key: string, options?: any) => string) => void ): void; + preload(language: string, callback?: (err: any, t: (key: string, options?: any) => string) => void ): void; + preload(languages: string[], callback?: (err: any, t: (key: string, options?: any) => string) => void ): void; setDefaultNamespace(namespace: string): void; - setLng(language: string, callback?: (t: (key: string, options?: any) => string) => void ): void; + setLng(language: string, callback?: (err: any, t: (key: string, options?: any) => string) => void ): void; sync: { load: (languages: string[], options: I18nextOptions, callback: (err: Error, store: IResourceStore) => void ) => void; postMissing: (language: string, namespace: string, key: string, defaultValue: any, languages: string[]) => void; diff --git a/jquery-knob/jquery-knob-tests.ts b/jquery-knob/jquery-knob-tests.ts new file mode 100644 index 000000000..a6c85e2c8 --- /dev/null +++ b/jquery-knob/jquery-knob-tests.ts @@ -0,0 +1,37 @@ +/// + +// create from html attrs +$('').knob(); + +// create with object +$('').knob({ + min: 0, + max: 100, + angleArc: 270 +}); + +// hooks +var hookKnob = $('').knob({ + release: function(value) { + console.log(value); + }, + change: function(value) { + console.log(value); + }, + draw: function() { + console.log(this); + }, + cancel: function() { + console.log(this); + }, + format: function(value) { + console.log(value); + } +}); + +// trigger +hookKnob.trigger('release'); +hookKnob.trigger('change'); +hookKnob.trigger('draw'); +hookKnob.trigger('cancel'); +hookKnob.trigger('format'); \ No newline at end of file diff --git a/jquery-knob/jquery-knob.d.ts b/jquery-knob/jquery-knob.d.ts new file mode 100644 index 000000000..7d02fa34f --- /dev/null +++ b/jquery-knob/jquery-knob.d.ts @@ -0,0 +1,116 @@ +// Type definitions for jQuery Knob 1.2.11 +// Project: http://anthonyterrien.com/knob/ +// Definitions by: Iain Buchanan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryKnob { + export interface JQueryKnobOptions { + /** + * min value | default=0 + */ + min?: number; + /** + * max value | default=100 + */ + max?: number; + /** + * step size | default=1 + */ + step?: number; + /** + * starting angle in degrees | default=0 + */ + angleOffset?: number; + /** + * arc size in degrees | default=360 + */ + angleArc?: number; + /** + * stop at min & max on keydown/mousewheel | default=true + */ + stopper?: boolean; + /** + * disable input and events | default=false + */ + readOnly?: boolean; + /** + * direction of progression | default=clockwise + */ + rotation?: string; + /** + * display mode "cursor", cursor size could be changed passing a + * numeric value to the option, default width is used when passing + * boolean value "true" | default=gauge + */ + cursor?: string | boolean; + /** + * gauge thickness + */ + thickness?: number; + /** + * gauge stroke endings | default=butt, round=rounded line endings + */ + lineCap?: string; + /** + * dial width + */ + width?: number; + /** + * default=true | false=hide input + */ + displayInput?: boolean; + /** + * default=false | true=displays the previous value with transparency + */ + displayPrevious?: boolean; + /** + * foreground color + */ + fgColor?: string; + /** + * input value (number) color + */ + inputColor?: string; + /** + * font family + */ + font?: string; + /** + * font weight + */ + fontWeight?: string; + /** + * background color + */ + bgColor?: string; + /** + * executed on release + */ + release?: (value: number) => void; + /** + * executed at each change of the value + */ + change?: (value: number) => void; + /** + * when drawing the canvas + */ + draw?: () => void; + /** + * triggered on [esc] keydown + */ + cancel?: () => void; + /** + * allows to format output (add unit %, ms...) + */ + format?: (value: number) => void; + } +} + +interface JQuery { + /** + * Create a knob for the given input field, with optional options + */ + knob(options?: JQueryKnob.JQueryKnobOptions): JQuery; +} \ No newline at end of file diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 79263027f..ef02b40d6 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1618,7 +1618,7 @@ function test_spinner() { }, _parse: function (value) { if (typeof value === "string") { - if (Number(value) == value) { + if (Number(value) == value) { return Number(value); } return 123; @@ -1822,4 +1822,4 @@ function test_widget() { var isDisabled = $(".selector").jQuery.Widget("option", "disabled"); $(".selector").jQuery.Widget("option", "disabled", true); $(".selector").jQuery.Widget("option", { disabled: true }); -} \ No newline at end of file +} diff --git a/jsdom/jsdom-tests.ts b/jsdom/jsdom-tests.ts index cb6992b49..504f1f064 100644 --- a/jsdom/jsdom-tests.ts +++ b/jsdom/jsdom-tests.ts @@ -47,5 +47,4 @@ jsdom.env({ } }); -var window: Window = jsdom.jsdom("
foobar
").parentWindow; -var document: Document = jsdom.jsdom(""); \ No newline at end of file +var document: Document = jsdom.jsdom(""); diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 167428733..9b4548502 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1092,7 +1092,29 @@ result = <{ a: number; b: number; c: number; }>_.transform(<{ [index: string]: n r[key] = num * 3; }); -result = _.values({ 'one': 1, 'two': 2, 'three': 3 }); +// _.values +class TestValues { + public a = 1; + public b = 2; + public c: string; +} +TestValues.prototype.c = 'a'; +result = _.values(new TestValues()); +// → [1, 2] (iteration order is not guaranteed) +result = _(new TestValues()).values().value(); +// → [1, 2] (iteration order is not guaranteed) + +// _.valueIn +class TestValueIn { + public a = 1; + public b = 2; + public c: number; +} +TestValueIn.prototype.c = 3; +result = _.valuesIn(new TestValueIn()); +// → [1, 2, 3] +result = _(new TestValueIn()).valuesIn().value(); +// → [1, 2, 3] /********** * Utilities * diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f8728e77e..f02a4aa97 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6301,11 +6301,35 @@ declare module _ { //_.values interface LoDashStatic { /** - * Creates an array composed of the own enumerable property values of object. - * @param object The object to inspect. + * Creates an array of the own enumerable property values of object. + * @param object The object to query. * @return Returns an array of property values. **/ - values(object?: any): any[]; + values(object?: any): T[]; + } + + interface LoDashObjectWrapper { + /** + * @see _.values + **/ + values(): LoDashObjectWrapper; + } + + //_.valuesIn + interface LoDashStatic { + /** + * Creates an array of the own and inherited enumerable property values of object. + * @param object The object to query. + * @return Returns the array of property values. + **/ + valuesIn(object?: any): T[]; + } + + interface LoDashObjectWrapper { + /** + * @see _.valuesIn + **/ + valuesIn(): LoDashObjectWrapper; } /********** diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index 33869213d..f42307f2c 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -75,7 +75,8 @@ function test() { ]; } - function testPath() { + function testPath() { + makerjs.path.breakAtPoint(paths.arc, [0,0]).type; makerjs.path.intersection(paths.circle, paths.arc).intersectionPoints; makerjs.path.mirror(paths.arc, true, true); makerjs.path.moveRelative(paths.circle, [0,0]); diff --git a/maker.js/makerjs.d.ts b/maker.js/makerjs.d.ts index acea3405b..8e3eaf189 100644 --- a/maker.js/makerjs.d.ts +++ b/maker.js/makerjs.d.ts @@ -94,10 +94,6 @@ declare module MakerJs { * The main point of reference for this path. */ origin: IPoint; - /** - * Optional CSS style properties to be emitted into SVG. Useful for creating guidelines and debugging your model. - */ - cssStyle?: string; } /** * Test to see if an object implements the required properties of a path. @@ -425,6 +421,18 @@ declare module MakerJs.path { */ function scale(pathToScale: IPath, scaleValue: number): IPath; } +declare module MakerJs.path { + /** + * Breaks a path in two. The supplied path will end at the supplied pointOfBreak, + * a new path is returned which begins at the pointOfBreak and ends at the supplied path's initial end point. + * For Circle, the original path will be converted in place to an Arc, and null is returned. + * + * @param pathToBreak The path to break. + * @param pointOfBreak The point at which to break the path. + * @returns A new path of the same type, when path type is line or arc. Returns null for circle. + */ + function breakAtPoint(pathToBreak: IPath, pointOfBreak: IPoint): IPath; +} declare module MakerJs.paths { /** * Class for arc path. @@ -661,7 +669,7 @@ declare module MakerJs.path { * * @param path1 First path to find intersection. * @param path2 Second path to find intersection. - * @result IPathIntersection object, with points(s) of intersection (and angles, when a path is an arc or circle); or null if the paths did not intersect. + * @returns IPathIntersection object, with points(s) of intersection (and angles, when a path is an arc or circle); or null if the paths did not intersect. */ function intersection(path1: IPath, path2: IPath): IPathIntersection; } diff --git a/microsoft-ajax/microsoft.ajax-tests.ts b/microsoft-ajax/microsoft.ajax-tests.ts index 7544b1c9f..397fcc92c 100644 --- a/microsoft-ajax/microsoft.ajax-tests.ts +++ b/microsoft-ajax/microsoft.ajax-tests.ts @@ -54,14 +54,14 @@ function BaseClassExtensions_Error_Tests() { } else if (isNaN(input)) { var msg = "A number was not entered. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += (String).format("Please enter a number between {0} and {1}.", min, max); var err = (Error).create(msg); throw err; } else if (input < min || input > max) { msg = "The number entered was outside the acceptable range. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += (String).format("Please enter a number between {0} and {1}.", min, max); var err = (Error).create(msg); @@ -82,12 +82,12 @@ function BaseClassExtensions_Error_Tests() { function BaseClassExtensions_String_Tests() { - (String).format("Please enter a number between {0} and {1}.", 1, 2); - (String).endsWith("test"); - (String).localeFormat("Please enter a number between {0} and {1}", 1, 2); - (String).trim(); - (String).trimEnd(); - (String).trimStart(); + (String).format("Please enter a number between {0} and {1}.", 1, 2); + (String).endsWith("test"); + (String).localeFormat("Please enter a number between {0} and {1}", 1, 2); + (String).trim(); + (String).trimEnd(); + (String).trimStart(); } function BaseClassExtensions_Function_Tests() { @@ -150,7 +150,7 @@ function BaseClassExtensions_Date_Tests() { function BaseClassExtensions_Boolean_Tests() { - (Boolean).parse("false"); + (Boolean).parse("false"); } function BaseClassExtensions_Number_Tests() { diff --git a/mock-fs/mock-fs-tests.ts b/mock-fs/mock-fs-tests.ts index 3dd9f0121..d4c5eae4f 100644 --- a/mock-fs/mock-fs-tests.ts +++ b/mock-fs/mock-fs-tests.ts @@ -50,7 +50,7 @@ function d() { function e() { mock({ 'some/dir': mock.directory({ - mode: 0755, + mode: parseInt("0755", 8), items: { file1: 'file one content', file2: new Buffer([8, 6, 7, 5, 3, 0, 9]) diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index c5855c12c..b76752b11 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -196,10 +196,17 @@ moment.isMoment(); moment.isMoment(new Date()); moment.isMoment(moment()); +moment.isDate(new Date()); +moment.isDate(/regexp/); + moment.isDuration(); moment.isDuration(new Date()); moment.isDuration(moment.duration()); +moment().isBetween(moment(), moment()); +moment().isBetween(new Date(), new Date()); +moment().isBetween([1,1,2000], [1,1,2001], "year"); + moment.localeData('fr'); moment(1316116057189).fromNow(); diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index ba5fe85d1..fd0d59d68 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -69,6 +69,7 @@ declare module moment { subtract(d: Duration): Duration; toISOString(): string; + toJSON(): string; } @@ -215,11 +216,8 @@ declare module moment { dayOfYear(): number; dayOfYear(d: number): Moment; - from(f: Moment): string; - from(f: Moment, suffix: boolean): string; - from(d: Date): string; - from(s: string): string; - from(date: number[]): string; + from(f: Moment|string|number|Date|number[], suffix?: boolean): string; + to(f: Moment|string|number|Date|number[], suffix?: boolean): string; diff(b: Moment): number; diff(b: Moment, unitOfTime: string): number; @@ -242,39 +240,13 @@ declare module moment { isDST(): boolean; isBefore(): boolean; - isBefore(b: Moment): boolean; - isBefore(b: string): boolean; - isBefore(b: Number): boolean; - isBefore(b: Date): boolean; - isBefore(b: number[]): boolean; - isBefore(b: Moment, granularity: string): boolean; - isBefore(b: String, granularity: string): boolean; - isBefore(b: Number, granularity: string): boolean; - isBefore(b: Date, granularity: string): boolean; - isBefore(b: number[], granularity: string): boolean; + isBefore(b: Moment|string|number|Date|number[], granularity?: string): boolean; isAfter(): boolean; - isAfter(b: Moment): boolean; - isAfter(b: string): boolean; - isAfter(b: Number): boolean; - isAfter(b: Date): boolean; - isAfter(b: number[]): boolean; - isAfter(b: Moment, granularity: string): boolean; - isAfter(b: String, granularity: string): boolean; - isAfter(b: Number, granularity: string): boolean; - isAfter(b: Date, granularity: string): boolean; - isAfter(b: number[], granularity: string): boolean; + isAfter(b: Moment|string|number|Date|number[], granularity?: string): boolean; - isSame(b: Moment): boolean; - isSame(b: string): boolean; - isSame(b: Number): boolean; - isSame(b: Date): boolean; - isSame(b: number[]): boolean; - isSame(b: Moment, granularity: string): boolean; - isSame(b: String, granularity: string): boolean; - isSame(b: Number, granularity: string): boolean; - isSame(b: Date, granularity: string): boolean; - isSame(b: number[], granularity: string): boolean; + isSame(b: Moment|string|number|Date|number[], granularity?: string): boolean; + isBetween(a: Moment|string|number|Date|number[], b: Moment|string|number|Date|number[], granularity?: string): boolean; // Deprecated as of 2.8.0. lang(language: string): Moment; @@ -290,20 +262,12 @@ declare module moment { localeData(): MomentLanguage; // Deprecated as of 2.7.0. - max(date: Date): Moment; - max(date: number): Moment; - max(date: any[]): Moment; - max(date: string): Moment; + max(date: Moment|string|number|Date|any[]): Moment; max(date: string, format: string): Moment; - max(clone: Moment): Moment; // Deprecated as of 2.7.0. - min(date: Date): Moment; - min(date: number): Moment; - min(date: any[]): Moment; - min(date: string): Moment; + min(date: Moment|string|number|Date|any[]): Moment; min(date: string, format: string): Moment; - min(clone: Moment): Moment; get(unit: string): number; set(unit: string, value: number): Moment; @@ -412,6 +376,7 @@ declare module moment { invalid(parsingFlags?: Object): Moment; isMoment(): boolean; isMoment(m: any): boolean; + isDate(m: any): boolean; isDuration(): boolean; isDuration(d: any): boolean; diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 16490d2e1..04c075352 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -196,10 +196,17 @@ moment.isMoment(); moment.isMoment(new Date()); moment.isMoment(moment()); +moment.isDate(new Date()); +moment.isDate(/regexp/); + moment.isDuration(); moment.isDuration(new Date()); moment.isDuration(moment.duration()); +moment().isBetween(moment(), moment()); +moment().isBetween(new Date(), new Date()); +moment().isBetween([1,1,2000], [1,1,2001], "year"); + moment.localeData('fr'); moment(1316116057189).fromNow(); @@ -228,6 +235,8 @@ moment.duration(500).seconds(); moment.duration(500).asSeconds(); moment.duration().minutes(); moment.duration().asMinutes(); +moment.duration().toISOString(); +moment.duration().toJSON(); var adur = moment.duration(3, 'd'); var bdur = moment.duration(2, 'd'); diff --git a/multer/multer.d.ts b/multer/multer.d.ts index fdde44b54..06a9d4f7a 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -5,31 +5,34 @@ /// + declare module Express { export interface Request { files: { - [fieldname: string]: { - /** Field name specified in the form */ - fieldname: string; - /** Name of the file on the user's computer */ - originalname: string; - /** Renamed file name */ - name: string; - /** Encoding type of the file */ - encoding: string; - /** Mime type of the file */ - mimetype: string; - /** Location of the uploaded file */ - path: string; - /** Extension of the file */ - extension: string; - /** Size of the file in bytes */ - size: number; - /** If the file was truncated due to size limitation */ - truncated: boolean; - /** Raw data (is null unless the inMemory option is true) */ - buffer: Buffer; - } + [fieldname: string]: Multer.File + } + } + + module Multer { + export interface File { + /** Field name specified in the form */ + fieldname: string; + /** Name of the file on the user's computer */ + originalname: string; + /** Encoding type of the file */ + encoding: string; + /** Mime type of the file */ + mimetype: string; + /** Size of the file in bytes */ + size: number; + /** The folder to which the file has been saved (DiskStorage) */ + destination: string; + /** The name of the file within the destination (DiskStorage) */ + filename: string; + /** Location of the uploaded file (DiskStorage) */ + path: string; + /** A Buffer of the entire file (MemoryStorage) */ + buffer: Buffer; } } } @@ -40,6 +43,7 @@ declare module "multer" { function multer(options?: multer.Options): express.RequestHandler; module multer { + type Options = { /** The destination directory for the uploaded files. */ dest?: string; @@ -69,11 +73,11 @@ declare module "multer" { /** Function to rename the directory in which to place uploaded files. The dest parameter is the default value originally assigned or passed into multer. The req and res parameters are also passed into the function because they may contain information (eg session data) needed to create the path (eg get userid from the session). */ changeDest?: (dest: string, req: Express.Request, res: Express.Response) => string; /** Event handler triggered when a file starts to be uploaded. A file object, with the following properties, is available to this function: fieldname, originalname, name, encoding, mimetype, path, and extension. */ - onFileUploadStart?: (file: string, req: Express.Request, res: Express.Response) => void; + onFileUploadStart?: (file: Express.Multer.File, req: Express.Request, res: Express.Response) => void; /** Event handler triggered when a chunk of buffer is received. A buffer object along with a file object is available to the function. */ - onFileUploadData?: (file: string, data: Buffer, req: Express.Request, res: Express.Response) => void; + onFileUploadData?: (file: Express.Multer.File, data: Buffer, req: Express.Request, res: Express.Response) => void; /** Event handler trigger when a file is completely uploaded. A file object is available to the function. */ - onFileUploadComplete?: (file: string, req: Express.Request, res: Express.Response) => void; + onFileUploadComplete?: (file: Express.Multer.File, req: Express.Request, res: Express.Response) => void; /** Event handler triggered when the form parsing starts. */ onParseStart?: () => void; /** Event handler triggered when the form parsing completes. The request object and the next objects are are passed to the function. */ @@ -81,7 +85,7 @@ declare module "multer" { /** Event handler for any errors encountering while processing the form. The error object and the next object is available to the function. If you are handling errors yourself, make sure to terminate the request or call the next() function, else the request will be left hanging. */ onError?: () => void; /** Event handler triggered when a file size exceeds the specification in the limit object. No more files will be parsed after the limit is reached. */ - onFileSizeLimit?: (file: string) => void; + onFileSizeLimit?: (file: Express.Multer.File) => void; /** Event handler triggered when the number of files exceed the specification in the limit object. No more files will be parsed after the limit is reached. */ onFilesLimit?: () => void; /** Event handler triggered when the number of fields exceed the specification in the limit object. No more fields will be parsed after the limit is reached. */ diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index e0871a267..758e0e53f 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -1,117 +1,138 @@ /// -// History Manager -class LogHistoryManager extends Navigation.HashHistoryManager { - addHistory(state: Navigation.State, url: string) { - console.log('add history'); - super.addHistory(state, url); - } -} - -// State Router -class LogStateRouter extends Navigation.StateRouter { - getData(route: string): { state: Navigation.State; data: any } { - console.log('get data'); - return super.getData(route); - } -} - -// Settings -Navigation.settings.router = new LogStateRouter(); -Navigation.settings.historyManager = new LogHistoryManager(); -Navigation.settings.stateIdKey = 'state'; - -// Configuration -Navigation.StateInfoConfig.build([ - { key: 'home', initial: 'page', states: [ - { key: 'page', route: '' } - ]}, - { key: 'person', initial: 'list', states: [ - { key: 'list', route: 'people/{page}', transitions: [ - { key: 'select', to: 'details' } - ], defaults: { page: 1 }, trackCrumbTrail: false }, - { key: 'details', route: 'person/{id}', defaultTypes: { id: 'number' } } - ]} -]); - -// StateInfo -var dialogs = Navigation.StateInfoConfig.dialogs; -var home = dialogs['home']; -var homePage = home.states['page']; -var homeKey = home.key; -var homePageKey = homePage.key; -homePage = home.initial; -var person = dialogs['person']; -var personList = person.states['list']; -var personDetails = person.states['details']; -var personListSelect = personList.transitions['select']; -personList = personListSelect.parent; -personDetails = personListSelect.to; -var pageDefault = personList.defaults.page; -var idDefaultType = personDetails.defaultTypes.id; - -// StateNavigator -personList.dispose = () => {}; -personList.navigating = (data, url, navigate) => { - navigate(); -}; -personList.navigated = (data) => {}; - -// State Handler -class LogStateHandler extends Navigation.StateHandler { - getNavigationData(state: Navigation.State, url: string): any { - console.log('get navigation data'); - super.getNavigationData(state, url); - } -} -homePage.stateHandler = new LogStateHandler(); -personList.stateHandler = new LogStateHandler(); -personDetails.stateHandler = new LogStateHandler(); - -// Navigation Event -var navigationListener = -(oldState: Navigation.State, state: Navigation.State, data: any) => { - Navigation.StateController.offNavigate(navigationListener); -}; -Navigation.StateController.onNavigate(navigationListener); - -// Navigation -Navigation.start('home'); -Navigation.StateController.navigate('person'); -Navigation.StateController.refresh(); -Navigation.StateController.refresh({ page: 2 }); -Navigation.StateController.navigate('select', { id: 10 }); -var canGoBack: boolean = Navigation.StateController.canNavigateBack(1); -Navigation.StateController.navigateBack(1); - -// Navigation Link -var link = Navigation.StateController.getNavigationLink('person'); -link = Navigation.StateController.getRefreshLink(); -link = Navigation.StateController.getRefreshLink({ page: 2 }); -link = Navigation.StateController.getNavigationLink('select', { id: 10 }); -var nextDialog = Navigation.StateController.getNextState('select').parent; -person = nextDialog; -Navigation.StateController.navigateLink(link); -link = Navigation.StateController.getNavigationBackLink(1); -var crumb = Navigation.StateController.crumbs[0]; -link = crumb.navigationLink; - -// StateContext -Navigation.StateController.navigate('home'); -Navigation.StateController.navigate('person'); -home = Navigation.StateContext.previousDialog; -homePage = Navigation.StateContext.previousState; -person === Navigation.StateContext.dialog; -personList === Navigation.StateContext.state; -var url: string = Navigation.StateContext.url; -var page: number = Navigation.StateContext.data.page; - -// Navigation Data -Navigation.StateController.refresh({ page: 2 }); -var data = Navigation.StateContext.includeCurrentData({ sort: 'name' }, ['page']); -Navigation.StateController.refresh(data); -Navigation.StateContext.clear('sort'); -var data = Navigation.StateContext.includeCurrentData({ pageSize: 10 }); -Navigation.StateController.refresh(data); -Navigation.StateContext.clear(); -Navigation.StateController.refresh(); +module NavigationTests { + // History Manager + class LogHistoryManager extends Navigation.HashHistoryManager { + addHistory(state: Navigation.State, url: string) { + console.log('add history'); + super.addHistory(state, url); + } + } + + // Crumb Trail Persister + class LogCrumbTrailPersister extends Navigation.CrumbTrailPersister { + load(crumbTrail: string): string { + console.log('load'); + return crumbTrail; + } + + save(crumbTrail: string): string { + console.log('save'); + return crumbTrail; + } + } + + // State Router + class LogStateRouter extends Navigation.StateRouter { + getData(route: string): { state: Navigation.State; data: any } { + console.log('get data'); + return super.getData(route); + } + } + + // Settings + Navigation.settings.router = new LogStateRouter(); + Navigation.settings.historyManager = new LogHistoryManager(); + Navigation.settings.crumbTrailPersister = new LogCrumbTrailPersister(); + Navigation.settings.stateIdKey = 'state'; + + // Configuration + Navigation.StateInfoConfig.build([ + { key: 'home', initial: 'page', states: [ + { key: 'page', route: '' } + ]}, + { key: 'person', initial: 'list', states: [ + { key: 'list', route: ['people/{page}', 'people/{page}/sort/{sort}'], transitions: [ + { key: 'select', to: 'details' } + ], defaults: { page: 1 }, trackCrumbTrail: false }, + { key: 'details', route: 'person/{id}', trackTypes: false, defaultTypes: { id: 'number' } } + ]} + ]); + + // StateInfo + var dialogs = Navigation.StateInfoConfig.dialogs; + var home = dialogs['home']; + var homePage = home.states['page']; + var homeKey = home.key; + var homePageKey = homePage.key; + homePage = home.initial; + var person = dialogs['person']; + var personList = person.states['list']; + var personDetails = person.states['details']; + var personListSelect = personList.transitions['select']; + personList = personListSelect.parent; + personDetails = personListSelect.to; + var pageDefault = personList.defaults.page; + var idDefaultType = personDetails.defaultTypes.id; + + // StateNavigator + personList.dispose = () => {}; + personList.navigating = (data, url, navigate) => { + navigate([]); + }; + personList.navigated = (data, asyncData) => {}; + personDetails.navigating = (data, url, navigate) => { + navigate(); + }; + personDetails.navigated = (data) => {}; + + // State Handler + class LogStateHandler extends Navigation.StateHandler { + getNavigationData(state: Navigation.State, url: string): any { + console.log('get navigation data'); + super.getNavigationData(state, url); + } + } + homePage.stateHandler = new LogStateHandler(); + personList.stateHandler = new LogStateHandler(); + personDetails.stateHandler = new LogStateHandler(); + + // Navigation Event + var navigationListener = + (oldState: Navigation.State, state: Navigation.State, data: any) => { + Navigation.StateController.offNavigate(navigationListener); + }; + Navigation.StateController.onNavigate(navigationListener); + + // Navigation + Navigation.start('home'); + Navigation.StateController.navigate('person'); + Navigation.StateController.refresh(); + Navigation.StateController.refresh({ page: 2 }); + Navigation.StateController.navigate('select', { id: 10 }); + var canGoBack: boolean = Navigation.StateController.canNavigateBack(1); + Navigation.StateController.navigateBack(1); + + // Navigation Link + var link = Navigation.StateController.getNavigationLink('person'); + link = Navigation.StateController.getRefreshLink(); + link = Navigation.StateController.getRefreshLink({ page: 2 }); + link = Navigation.StateController.getNavigationLink('select', { id: 10 }); + var nextDialog = Navigation.StateController.getNextState('select').parent; + person = nextDialog; + Navigation.StateController.navigateLink(link); + link = Navigation.StateController.getNavigationBackLink(1); + var crumb = Navigation.StateController.crumbs[0]; + link = crumb.navigationLink; + Navigation.StateController.navigateLink(link, true); + + // StateContext + Navigation.StateController.navigate('home'); + Navigation.StateController.navigate('person'); + home = Navigation.StateContext.previousDialog; + homePage = Navigation.StateContext.previousState; + person === Navigation.StateContext.dialog; + personList === Navigation.StateContext.state; + var url: string = Navigation.StateContext.url; + var page: number = Navigation.StateContext.data.page; + + // Navigation Data + Navigation.StateController.refresh({ page: 2 }); + var data = Navigation.StateContext.includeCurrentData({ sort: 'name' }, ['page']); + Navigation.StateController.refresh(data); + Navigation.StateContext.clear('sort'); + var data = Navigation.StateContext.includeCurrentData({ pageSize: 10 }); + Navigation.StateController.refresh(data); + Navigation.StateContext.clear(); + Navigation.StateController.refresh(); +} \ No newline at end of file diff --git a/navigation/navigation.d.ts b/navigation/navigation.d.ts index 7cb830897..59af79ca2 100644 --- a/navigation/navigation.d.ts +++ b/navigation/navigation.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Navigation 1.0 +// Type definitions for Navigation 1.1.0 // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -61,15 +61,20 @@ declare module Navigation { */ title?: string; /** - * Gets the route Url pattern + * Gets the route Url patterns */ - route: string; + route: string | string[]; /** * Gets a value that indicates whether to maintain crumb trail * information e.g PreviousState. This can be used together with Route * to produce user friendly Urls */ trackCrumbTrail?: boolean; + /** + * Gets a value that indicates whether NavigationData Types are + * preserved when navigating + */ + trackTypes?: boolean; } /** @@ -175,20 +180,35 @@ declare module Navigation { */ title: string; /** - * Gets the route Url pattern + * Gets the route Url patterns */ - route: string; + route: string | string[]; /** * Gets a value that indicates whether to maintain crumb trail * information e.g PreviousState. This can be used together with Route * to produce user friendly Urls */ trackCrumbTrail: boolean; + /** + * Gets a value that indicates whether NavigationData Types are + * preserved when navigating + */ + trackTypes: boolean; /** * Gets or sets the IStateHandler responsible for building and parsing - * avigation links to this State + * navigation links to this State */ stateHandler: IStateHandler; + /** + * Called on the old State (this is not the same as the previous + * State) before navigating to a different State + * @param state The new State + * @param data The new NavigationData + * @param url The new target location + * @param unload The function to call to continue to navigate + * @param history A value indicating whether browser history was used + */ + unloading: (state: State, data: any, url: string, unload: () => void, history?: boolean) => void; /** * Called on the old State (this is not the same as the previous * State) after navigating to a different State @@ -197,15 +217,17 @@ declare module Navigation { /** * Called on the current State after navigating to it * @param data The current NavigationData + * @param asyncData The data passed asynchronously while navigating */ - navigated: (data: any) => void; + navigated: (data: any, asyncData?: any) => void; /** * Called on the new State before navigating to it * @param data The new NavigationData * @param url The new target location - * @param navigate The function to call to continue to navigate + * @param navigate The function to call to continue to navigate + * @param history A value indicating whether browser history was used */ - navigating: (data: any, url: string, navigate: () => void) => void; + navigating: (data: any, url: string, navigate: (asyncData?: any) => void, history?: boolean) => void; } /** @@ -366,6 +388,84 @@ declare module Navigation { */ getUrl(anchor: HTMLAnchorElement): string; } + + /** + * Provides the base functionality for crumb trail persistence mechanisms + */ + class CrumbTrailPersister { + /** + * Overridden by derived classes to return the persisted crumb trail + * @param crumbTrail The key, returned from the save function, to + * identify the persisted crumb trail + * @returns The crumb trail holding navigation and data information + */ + load(crumbTrail: string): string; + /** + * Overridden by derived classes to persist the crumb trail + * @param crumbTrail The crumb trail holding navigation and data + * information + * @returns The key to be passed to load function for crumb trail + * retrieval + */ + save(crumbTrail: string): string; + } + + /** + * Persists crumb trails, over a specified length, in localStorage. + * Prevents the creation of unmanageably long Urls. If used in a browser + * without localStorage or outside of a browser environment, then in memory + * storage is used + */ + class StorageCrumbTrailPersister extends CrumbTrailPersister { + /** + * Initializes a new instance of the StorageCrumbTrailPersister class + * with a maxLength of 500, historySize of 100 and localStorage as the + * storage mechanism + */ + constructor(); + /** + * Initializes a new instance of the StorageCrumbTrailPersister class + * with a historySize of 100 and localStorage as the storage mechanism + * @param maxLength The length above which any crumb trail will be + * stored in localStorage + */ + constructor(maxLength: number); + /** + * Initializes a new instance of the StorageCrumbTrailPersister class + * with localStorage as the storage mechanism + * @param maxLength The length above which any crumb trail will be + * stored in localStorage + * @param historySize The maximum number of crumb trails that will be + * held at any one time in localStorage + */ + constructor(maxLength: number, historySize: number); + /** + * Initializes a new instance of the StorageCrumbTrailPersister class + * @param maxLength The length above which any crumb trail will be + * stored in the storage + * @param historySize The maximum number of crumb trails that will be + * held at any one time in the storage + * @param storage The storage mechanism + */ + constructor(maxLength: number, historySize: number, storage: Storage); + /** + * Uses the crumbTrail parameter to determine whether to retrieve the + * crumb trail from storage. If retrieved from storage it may be null + * @param Key generated by the save function + * @returns Either the crumbTrail or the one retrieved value from + * storage; can be null if retrieved from storage + */ + load(crumbTrail: string): string; + /** + * If the crumbTrail is not over the maxLength it is returned. + * Otherwise the crumbTrail is stored in storage using a short key, + * unique within a given storage session. Also expunges old items from + * storage, if the historySize is breached when a new item is added + * @param crumbTrail The crumb trail to persist + * @returns crumbTrail or short, generated key pointing at crumbTrail + */ + save(crumbTrail: string): string; + } /** * Defines a contract a class must implement in order to build and parse @@ -434,6 +534,14 @@ declare module Navigation { navigationLink: string; /** * Initializes a new instance of the Crumb class + * @param data The Context Data held at the time of navigating away + * from this State + * @param state The configuration information associated with this + * navigation + * @param link The hyperlink navigation to return to the State and pass + * the associated Data + * @param last A value indicating whether the Crumb is the last in the + * crumb trail */ constructor(data: any, state: State, link: string, last: boolean); } @@ -442,8 +550,18 @@ declare module Navigation { * Provides access to the Navigation Settings configuration */ class NavigationSettings { + /** + * Gets or sets the builder and parser of State routes + */ router: IRouter; + /** + * Gets or sets the manager of the browser Url + */ historyManager: IHistoryManager; + /** + * Gets or sets the crumb trail persistence mechanism + */ + crumbTrailPersister: CrumbTrailPersister; /** * Gets or sets the key that identifies the StateId */ @@ -464,6 +582,11 @@ declare module Navigation { * Gets or sets the application path */ applicationPath: string; + /** + * Gets or sets a value indicating whether the PreviousStateId and + * ReturnData should be part of the CrumbTrail + */ + combineCrumbTrail: boolean; } /** @@ -650,6 +773,12 @@ declare module Navigation { * @param url The target location */ static navigateLink(url: string): void; + /** + * Navigates to the url + * @param url The target location + * @param history A value indicating whether browser history was used + */ + static navigateLink(url: string, history: boolean): void; /** * Gets the next State. Depending on the action will either return the * 'to' State of a Transition or the 'initial' State of a Dialog @@ -831,6 +960,11 @@ declare module Navigation { * @returns The matched route and data */ match(path: string): { route: Route; data: any; }; + /** + * Sorts the routes by the comparer + * @param compare The route comparer function + */ + sort(compare: (routeA: Route, routeB: Route) => number): void; } /** diff --git a/node/node.d.ts b/node/node.d.ts index 4eecc773c..e49d666ef 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -9,6 +9,14 @@ * * ************************************************/ +// compat for TypeScript 1.5.3 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.5.3. +interface MapConstructor {} +interface WeakMapConstructor {} +interface SetConstructor {} +interface WeakSetConstructor {} + /************************************************ * * * GLOBAL * @@ -271,7 +279,7 @@ declare module NodeJS { Int8Array: typeof Int8Array; Intl: typeof Intl; JSON: typeof JSON; - Map: typeof Map; + Map: MapConstructor; Math: typeof Math; NaN: typeof NaN; Number: typeof Number; @@ -280,7 +288,7 @@ declare module NodeJS { RangeError: typeof RangeError; ReferenceError: typeof ReferenceError; RegExp: typeof RegExp; - Set: typeof Set; + Set: SetConstructor; String: typeof String; Symbol: Function; SyntaxError: typeof SyntaxError; @@ -290,8 +298,8 @@ declare module NodeJS { Uint32Array: typeof Uint32Array; Uint8Array: typeof Uint8Array; Uint8ClampedArray: Function; - WeakMap: typeof WeakMap; - WeakSet: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; clearImmediate: (immediateId: any) => void; clearInterval: (intervalId: NodeJS.Timer) => void; clearTimeout: (timeoutId: NodeJS.Timer) => void; diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index 738ac2834..d332a49ef 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -8,39 +8,39 @@ "resolved": "https://registry.npmjs.org/definition-tester/-/definition-tester-0.2.0.tgz", "dependencies": { "bluebird": { - "version": "2.7.1", - "from": "bluebird@^2.5.3", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.7.1.tgz" + "version": "2.9.34", + "from": "bluebird@>=2.5.3 <3.0.0", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.34.tgz" }, "definition-header": { "version": "0.1.0", - "from": "definition-header@^0.1.0", + "from": "definition-header@>=0.1.0 <0.2.0", "resolved": "https://registry.npmjs.org/definition-header/-/definition-header-0.1.0.tgz", "dependencies": { "joi": { "version": "4.9.0", - "from": "joi@^4.0.0", + "from": "joi@>=4.0.0 <5.0.0", "resolved": "https://registry.npmjs.org/joi/-/joi-4.9.0.tgz", "dependencies": { "hoek": { - "version": "2.11.0", - "from": "hoek@^2.2.x", - "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.11.0.tgz" + "version": "2.14.0", + "from": "hoek@>=2.2.0 <3.0.0", + "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.14.0.tgz" }, "topo": { "version": "1.0.2", - "from": "topo@1.x.x", + "from": "topo@>=1.0.0 <2.0.0", "resolved": "https://registry.npmjs.org/topo/-/topo-1.0.2.tgz" }, "isemail": { "version": "1.1.1", - "from": "isemail@1.x.x", + "from": "isemail@>=1.0.0 <2.0.0", "resolved": "https://registry.npmjs.org/isemail/-/isemail-1.1.1.tgz" }, "moment": { - "version": "2.9.0", - "from": "moment@2.x.x", - "resolved": "https://registry.npmjs.org/moment/-/moment-2.9.0.tgz" + "version": "2.10.3", + "from": "moment@>=2.0.0 <3.0.0", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.10.3.tgz" } } }, @@ -50,76 +50,138 @@ "resolved": "https://registry.npmjs.org/joi-assert/-/joi-assert-0.0.3.tgz", "dependencies": { "assertion-error": { - "version": "1.0.0", - "from": "assertion-error@^1.0.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.0.0.tgz" + "version": "1.0.1", + "from": "assertion-error@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.0.1.tgz" } } }, "parsimmon": { "version": "0.5.1", - "from": "parsimmon@^0.5.0", + "from": "parsimmon@>=0.5.0 <0.6.0", "resolved": "https://registry.npmjs.org/parsimmon/-/parsimmon-0.5.1.tgz", "dependencies": { "pjs": { "version": "5.1.1", - "from": "pjs@5.x", + "from": "pjs@>=5.0.0 <6.0.0", "resolved": "https://registry.npmjs.org/pjs/-/pjs-5.1.1.tgz" } } }, "xregexp": { "version": "2.0.0", - "from": "xregexp@~2.0.0", + "from": "xregexp@>=2.0.0 <2.1.0", "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz" } } }, "findup-sync": { "version": "0.2.1", - "from": "findup-sync@~0.2.1", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.2.1.tgz" + "from": "findup-sync@>=0.2.1 <0.3.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.2.1.tgz", + "dependencies": { + "glob": { + "version": "4.3.5", + "from": "glob@>=4.3.0 <4.4.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-4.3.5.tgz", + "dependencies": { + "inflight": { + "version": "1.0.4", + "from": "inflight@>=1.0.4 <2.0.0", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.4.tgz", + "dependencies": { + "wrappy": { + "version": "1.0.1", + "from": "wrappy@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz" + } + } + }, + "inherits": { + "version": "2.0.1", + "from": "inherits@>=2.0.0 <3.0.0", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "minimatch": { + "version": "2.0.9", + "from": "minimatch@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.9.tgz", + "dependencies": { + "brace-expansion": { + "version": "1.1.0", + "from": "brace-expansion@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz", + "dependencies": { + "balanced-match": { + "version": "0.2.0", + "from": "balanced-match@>=0.2.0 <0.3.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.2.0.tgz" + }, + "concat-map": { + "version": "0.0.1", + "from": "concat-map@0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" + } + } + } + } + }, + "once": { + "version": "1.3.2", + "from": "once@>=1.3.0 <2.0.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.3.2.tgz", + "dependencies": { + "wrappy": { + "version": "1.0.1", + "from": "wrappy@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz" + } + } + } + } + } + } }, "git-wrapper": { "version": "0.1.1", - "from": "git-wrapper@~0.1.1", + "from": "git-wrapper@>=0.1.1 <0.2.0", "resolved": "https://registry.npmjs.org/git-wrapper/-/git-wrapper-0.1.1.tgz" }, "glob": { - "version": "4.3.5", - "from": "glob@^4.3.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-4.3.5.tgz", + "version": "4.5.3", + "from": "glob@>=4.3.2 <5.0.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-4.5.3.tgz", "dependencies": { "inflight": { "version": "1.0.4", - "from": "inflight@^1.0.4", + "from": "inflight@>=1.0.4 <2.0.0", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.4.tgz", "dependencies": { "wrappy": { "version": "1.0.1", - "from": "wrappy@1", + "from": "wrappy@>=1.0.0 <2.0.0", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz" } } }, "inherits": { "version": "2.0.1", - "from": "inherits@2", + "from": "inherits@>=2.0.0 <3.0.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "minimatch": { - "version": "2.0.1", - "from": "minimatch@^2.0.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.1.tgz", + "version": "2.0.9", + "from": "minimatch@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.9.tgz", "dependencies": { "brace-expansion": { "version": "1.1.0", - "from": "brace-expansion@^1.0.0", + "from": "brace-expansion@>=1.0.0 <2.0.0", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz", "dependencies": { "balanced-match": { "version": "0.2.0", - "from": "balanced-match@^0.2.0", + "from": "balanced-match@>=0.2.0 <0.3.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.2.0.tgz" }, "concat-map": { @@ -132,13 +194,13 @@ } }, "once": { - "version": "1.3.1", - "from": "once@^1.3.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.3.1.tgz", + "version": "1.3.2", + "from": "once@>=1.3.0 <2.0.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.3.2.tgz", "dependencies": { "wrappy": { "version": "1.0.1", - "from": "wrappy@1", + "from": "wrappy@>=1.0.0 <2.0.0", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz" } } @@ -147,17 +209,17 @@ }, "lazy.js": { "version": "0.4.0", - "from": "lazy.js@~0.4.0", + "from": "lazy.js@>=0.4.0 <0.5.0", "resolved": "https://registry.npmjs.org/lazy.js/-/lazy.js-0.4.0.tgz" }, "manticore": { "version": "0.2.4", - "from": "manticore@^0.2.4", + "from": "manticore@>=0.2.4 <0.3.0", "resolved": "https://registry.npmjs.org/manticore/-/manticore-0.2.4.tgz", "dependencies": { "JSONStream": { "version": "0.8.4", - "from": "JSONStream@^0.8.4", + "from": "JSONStream@>=0.8.4 <0.9.0", "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-0.8.4.tgz", "dependencies": { "jsonparse": { @@ -166,30 +228,30 @@ "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-0.0.5.tgz" }, "through": { - "version": "2.3.6", - "from": "through@>=2.2.7 <3", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.6.tgz" + "version": "2.3.8", + "from": "through@>=2.2.7 <3.0.0", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz" } } }, "bluebird": { "version": "1.2.4", - "from": "bluebird@^1.2.4", + "from": "bluebird@>=1.2.4 <2.0.0", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-1.2.4.tgz" }, "through2": { "version": "0.5.1", - "from": "through2@^0.5.1", + "from": "through2@>=0.5.1 <0.6.0", "resolved": "https://registry.npmjs.org/through2/-/through2-0.5.1.tgz", "dependencies": { "readable-stream": { "version": "1.0.33", - "from": "readable-stream@~1.0.17", + "from": "readable-stream@>=1.0.17 <1.1.0", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz", "dependencies": { "core-util-is": { "version": "1.0.1", - "from": "core-util-is@~1.0.0", + "from": "core-util-is@>=1.0.0 <1.1.0", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" }, "isarray": { @@ -199,43 +261,43 @@ }, "string_decoder": { "version": "0.10.31", - "from": "string_decoder@~0.10.x", + "from": "string_decoder@>=0.10.0 <0.11.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" }, "inherits": { "version": "2.0.1", - "from": "inherits@~2.0.1", + "from": "inherits@>=2.0.1 <2.1.0", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" } } }, "xtend": { "version": "3.0.0", - "from": "xtend@~3.0.0", + "from": "xtend@>=3.0.0 <3.1.0", "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz" } } }, "type-detect": { "version": "0.1.2", - "from": "type-detect@^0.1.2", + "from": "type-detect@>=0.1.2 <0.2.0", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-0.1.2.tgz" } } }, "optimist": { "version": "0.6.1", - "from": "optimist@~0.6.1", + "from": "optimist@>=0.6.1 <0.7.0", "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", "dependencies": { "wordwrap": { - "version": "0.0.2", - "from": "wordwrap@~0.0.2", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz" + "version": "0.0.3", + "from": "wordwrap@>=0.0.2 <0.1.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz" }, "minimist": { "version": "0.0.10", - "from": "minimist@~0.0.1", + "from": "minimist@>=0.0.1 <0.1.0", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz" } } @@ -243,9 +305,9 @@ } }, "typescript": { - "version": "1.4.1", - "from": "typescript@1.4.1", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.4.1.tgz" + "version": "1.5.3", + "from": "typescript@1.5.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.5.3.tgz" } } } diff --git a/package.json b/package.json index 10d5c872a..2c5b834ed 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,6 @@ }, "devDependencies": { "definition-tester": "0.2.0", - "typescript": "1.4.1" + "typescript": "1.5.3" } } diff --git a/passport-local/passport-local-tests.ts b/passport-local/passport-local-tests.ts index f462846b8..873dc609b 100644 --- a/passport-local/passport-local-tests.ts +++ b/passport-local/passport-local-tests.ts @@ -26,7 +26,7 @@ class User implements IUser { //#endregion // Sample from https://github.com/jaredhanson/passport-local#configure-strategy -passport.use(new local.Strategy(function (username, password, done) { +passport.use(new local.Strategy((username: any, password: any, done: any) => { User.findOne({ username: username }, function (err, user) { if (err) { return done(err); diff --git a/path-exists/path-exists-tests.ts b/path-exists/path-exists-tests.ts new file mode 100644 index 000000000..bb9bdc321 --- /dev/null +++ b/path-exists/path-exists-tests.ts @@ -0,0 +1,8 @@ +/// + +import pathExists = require("path-exists"); + +pathExists("test/path-exists.d.ts", (error, exists) => { + console.log(exists); +}); +console.log(pathExists.sync("test/__path-exists.d.ts")); diff --git a/path-exists/path-exists.d.ts b/path-exists/path-exists.d.ts new file mode 100644 index 000000000..266ab66e5 --- /dev/null +++ b/path-exists/path-exists.d.ts @@ -0,0 +1,14 @@ +// Type definitions for path-exists 1.0.0 +// Project: https://github.com/sindresorhus/path-exists +// Definitions by: Shogo Iwano +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "path-exists" { + interface PathExists { + (path: string, callback: (error: Error, exists: boolean) => void): void; + sync(path: string): boolean; + } + + var pathExists: PathExists; + export = pathExists; +} diff --git a/phonegap/phonegap-tests.ts b/phonegap/phonegap-tests.ts index 1eaff6040..aab0b3f7f 100644 --- a/phonegap/phonegap-tests.ts +++ b/phonegap/phonegap-tests.ts @@ -556,7 +556,7 @@ function test_globalization() { function test_inAppBrowser() { var ref = window.open('http://apache.org', '_blank', 'location=yes'); - ref.addEventListener('loadstart', function () { alert(event.url); }); + ref.addEventListener('loadstart', function () { alert(event); }); ref.removeEventListener('loadstart', null); ref.close(); } @@ -716,4 +716,4 @@ function test_storage() { var value = window.localStorage.getItem("key"); window.localStorage.removeItem("key"); window.localStorage.clear(); -} \ No newline at end of file +} diff --git a/photonui/photonui-tests.ts b/photonui/photonui-tests.ts new file mode 100644 index 000000000..3242d3a92 --- /dev/null +++ b/photonui/photonui-tests.ts @@ -0,0 +1,908 @@ +/// + +// All exemple scripts from PhotonUI documentation: + +// Accel Manager +// We add a field to test accels +var field = new photonui.TextField({ + value: "Text Field" +}); +photonui.domInsert(field, "demo"); + +// ... And a label to display things +var label = new photonui.Label({text: ""}); +photonui.domInsert(label, "demo"); + +// We create the accel +var accel = new photonui.AccelManager(); + +// "Ctrl+A" / "Command+A" accelerator that is disabled if +// a field is focused +accel.addAccel("accel1", "ctrl + a", function() { + label.text += "'Ctrl + A' accelerator\n"; +}); +accel.addAccel("accel1-mac", "command + a", function() { + label.text += "'Command + A' accelerator\n"; +}); + +// "Ctrl+R" accelerator that works even if the field is focused +accel.addAccel("accel3", "ctrl + r", function() { + label.text += "'Ctrl + R' accelerator\n"; +}, false); + +// A more complexe sequence (hold "Ctrl+X", and then press "C") +accel.addAccel("accel4", "ctrl + x > c", function() { + label.text += "'Ctrl + X > C' accelerator\n"; +}); + +// BoxLayout +var box = new photonui.BoxLayout({ + orientation: "vertical", // "vertical" or "horizontal" + spacing: 5, // spacing between widgets + children: [ + new photonui.Button(), + new photonui.Button(), + new photonui.Button() + ] +}); + +photonui.domInsert(box, "demo"); + +// Button +var btn = new photonui.Button({ + text: "My Button", + leftIcon: new photonui.FAIcon("fa-send"), + callbacks: { + click: function(widget: any, event: any) { + alert("Someone clicked on " + widget.text); + } + } +}); + +photonui.domInsert(btn, "demo"); + +// canvas +var canvas = new photonui.Canvas({ + width: 200, + height: 150 +}); + +photonui.domInsert(canvas, "demo"); + +var ctx = canvas.getContext("2d"); + +ctx.lineWidth = 3; +ctx.strokeStyle = "#DB624F"; + +ctx.beginPath(); +ctx.moveTo(10, 10); +ctx.lineTo(40, 140); +ctx.lineTo(50, 30); +ctx.lineTo(190, 100); +ctx.stroke(); + +// Checkbox +var check = new photonui.CheckBox({ + value: true +}); + +photonui.domInsert(check, "demo"); + +// Color +var color = new photonui.Color("red"); + +console.log(color.hexString); +// "#FF0000" +var color = new photonui.Color("red"); + +console.log(color.hexString); +// "#FF0000" + +console.log(color.rgbString); +// "rgb(255, 0, 0)" + +console.log(color.rgbaString); +// "rgb(255, 0, 0, 1)" + +console.log(color.getRGB()); +// Array [ 255, 0, 0 ] + +console.log(color.getRGBA()); +// Array [ 255, 0, 0, 255 ] + +console.log(color.red, color.green, color.blue); +// 255 0 0 + +console.log(color.hue, color.saturation, color.brightness); +// 0 100 100 + +color.brightness = 50; +console.log(color.hexString); +// "#7F0000" + +color.hue = 204; +console.log(color.hexString); +// #004C7F + +// ColorButton +var btn2 = new photonui.ColorButton({ + value: "#4EC8DB", + callbacks: { + "value-changed": function(widget: any, value: any) { + var header = document.getElementsByTagName("header")[0]; + header.style.backgroundColor = value; + } + } +}); + +photonui.domInsert(btn2, "demo"); + +// colorpalette +var palette = new photonui.ColorPalette({ + callbacks: { + "value-changed": function(widget: any, value: any) { + var header = document.getElementsByTagName("header")[0]; + header.style.backgroundColor = value; + } + } +}); + +photonui.domInsert(palette, "demo"); + +var palette = new photonui.ColorPalette({ + palette: [ + ["#D32F2F", "#F44336", "#E91E63", "#9C27B0", "#673AB7"], + ["#3F51B5", "#2196F3", "#03A9F4", "#00BCD4", "#009688"], + ["#4CAF50", "#8BC34A", "#CDDC39", "#FFEB3B", "#FFC107"], + ["#FF9800", "#FF5722", "#795548", "#9E9E9E", "#607D8B"] + ], + callbacks: { + "value-changed": function(widget: any, value: any) { + var header = document.getElementsByTagName("header")[0]; + header.style.backgroundColor = value; + } + } +}); + +photonui.domInsert(palette, "demo"); + +// ColorPicker +var colorPicker = new photonui.ColorPicker({ + value: "#4EC8DB", + callbacks: { + "value-changed": function(widget: any, value: any) { + var header = document.getElementsByTagName("header")[0]; + header.style.backgroundColor = value; + } + } +}); + +photonui.domInsert(colorPicker, "demo"); + +// ColorPickerDialog +var dlg = new photonui.ColorPickerDialog({ + value: "#4EC8DB", + callbacks: { + "value-changed": function(widget: any, value: any) { + var header = document.getElementsByTagName("header")[0]; + header.style.backgroundColor = value; + } + } +}); + +// Add a button to show up the dialog +var btn = new photonui.Button({ + text: "Display the dialog", + callbacks: { + click: dlg.show.bind(dlg) + } +}); + +photonui.domInsert(btn, "demo"); + +// Dialog +var pos = photonui.Helpers.getAbsolutePosition("demo"); + +new photonui.Dialog({ + title: "My Dialog", + visible: true, + x: pos.x, y: pos.y, + child: new photonui.Label("Hello, I'm a dialog"), + padding: 10, + buttons: [ + new photonui.Button() + ], + callbacks: { + "close-button-clicked": function(widget: any) { + widget.destroy(); + } + } +}); + +// FAIcon +var icon = new photonui.FAIcon({ + iconName: "fa-camera", + size: "fa-3x", // "", "fa-lg", "fa-2x", "fa-3x", "fa-4x", "fa5x" + color: "#DB624F" +}); + +photonui.domInsert(icon, "demo"); + +// FileManager +// File manager that accepts PNG, JPEG, BMP and SVG files +var fm = new photonui.FileManager({ + acceptedMimes: ["image/png", "image/jpeg"], + acceptedExts: ["bmp", "svg"], + dropZone: document, // Enable file d&d + multiselect: true, // Allow to select more than one file + callbacks: { + "file-open": function(widget: any, file: any, x: number, y: number) { + // x and y are defined only with d&d + if (x !== undefined) { + alert(file.name + " dropped at ("+x+", "+y+")"); + } + else { + alert(file.name + " opened"); + } + } + } +}); + +// Button to show the "file open" dialog +var btn = new photonui.Button({ + text: "Open", + callbacks: { + click: function(widget: any, event: any) { + fm.open(); + } + } +}); + +photonui.domInsert(btn, "demo"); + +// FluidLayout +var fl = new photonui.FluidLayout({ + children: [ + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button() + ] +}); + +photonui.domInsert(fl, "demo"); + +// FontSelect +var select = new photonui.FontSelect({ + value: "item1", + fonts: [ + "Arial", + "Arial Black", + "Cantarell", + "Courier New", + "Impact", + "Time New Roman", + "Titillium Web", + "Verdana" + ], + callbacks: { + "value-changed": function(widget: any, value: any) { + alert("Value changed: " + value); + } + } +}); + +photonui.domInsert(select, "demo"); + +// GridLayout +var grid = new photonui.GridLayout({ + horizontalPadding: 0, + verticalPadding: 0, + horizontalSpacing: 5, + verticalSpacing: 5, + children: [ + new photonui.Button({ + text: "Widget 1", + layoutOptions: { + x: 0, y: 0, + cols: 1, rows: 1 + } + }), + new photonui.Button({ + text: "Widget 2", + layoutOptions: { + x: 1, y: 0, + cols: 1, rows: 1 + } + }), + new photonui.Button({ + text: "Widget 3", + layoutOptions: { + x: 2, y: 0, + cols: 1, rows: 2 + } + }), + new photonui.Button({ + text: "Widget 4", + layoutOptions: { + x: 0, y: 1, + cols: 2, rows: 1 + } + }) + ] +}); + +photonui.domInsert(grid, "demo"); + +// Image +var img = new photonui.Image({ + url: "../../images/favicon.png" +}); + +photonui.domInsert(img, "demo"); + +// Label +var label = new photonui.Label({ + text: "My Label", + textAlign: "left" +}); + +photonui.domInsert(label, "demo"); + +// Menu +var menu = new photonui.Menu({ + iconVisible: true, + children: [ + new photonui.MenuItem({ + text: "Menu Item 1", + icon: new photonui.FAIcon("fa-paper-plane") + }), + new photonui.MenuItem({ + text: "Menu Item 2", + icon: new photonui.FAIcon("fa-gears") + }), + new photonui.MenuItem({ + text: "Menu Item 3", + icon: new photonui.FAIcon("fa-paw") + }) + ] +}); + +photonui.domInsert(menu, "demo"); + +// MenuItem +var menu = new photonui.Menu({ + iconVisible: true, + children: [ + new photonui.MenuItem({ + text: "Menu Item 1", + icon: new photonui.FAIcon("fa-paper-plane"), + callbacks: { + click: function(widget: any, event: any) { + alert("You clicked on me!"); + } + } + }), + new photonui.MenuItem({ + text: "Menu Item 2", + icon: new photonui.FAIcon("fa-gears") + }), + new photonui.MenuItem({ + text: "Menu Item 3", + icon: new photonui.FAIcon("fa-paw") + }) + ] +}); + +photonui.domInsert(menu, "demo"); + +// Mouse Manager +var img = new photonui.Image({ + url: "../../images/favicon.png" +}); + +var mouse = new photonui.MouseManager({ + element: img, + callbacks: { + "click": function(manager: any, mstate: any) { + alert("You clicked on the image at " + + mstate.x + ", " + mstate.y); + } + } +}); + +photonui.domInsert(img, "demo"); + +// Numeric Filed +var field2 = new photonui.NumericField({ + placeholder: "placeholder", + decimalDigits: 2, + min: -10, max: 10, + step: 0.5, // When scrolling over the field + decimalSymbol: ".", // "." or "," + value: 5.5 +}); + +photonui.domInsert(field2, "demo"); + +// PopupMenu +var pos = photonui.Helpers.getAbsolutePosition("demo"); + +var popup = new photonui.PopupMenu({ + children: [ + new photonui.MenuItem({ + text: "Menu Item 1", + icon: new photonui.FAIcon("fa-paper-plane"), + callbacks: { + click: function(widget: any, event: any) { + alert("You clicked on me!"); + } + } + }), + new photonui.MenuItem({ + text: "Menu Item 2", + icon: new photonui.FAIcon("fa-gears") + }), + new photonui.MenuItem({ + text: "Menu Item 3", + icon: new photonui.FAIcon("fa-paw") + }) + ] +}); + +popup.popupXY(pos.x, pos.y); + +// PopupWindow +var pos = photonui.Helpers.getAbsolutePosition("demo"); + +var popup = new photonui.PopupWindow({ + padding: 10, + width: 200, + height: 200, + child: new photonui.Label({ + text: "Click anywhere to close" + }) +}); + +popup.popupXY(pos.x, pos.y); + +// ProgressBar +var pb = new photonui.ProgressBar({ + textVisible: true, + value: 0.42 +}); + +photonui.domInsert(pb, "demo"); + +// Select +var select2 = new photonui.Select({ + value: "item1", + children: [ + new photonui.MenuItem({value: "item1", text: "Item 1"}), + new photonui.MenuItem({value: "item2", text: "Item 2"}), + new photonui.MenuItem({value: "item3", text: "Item 3"}) + ], + callbacks: { + "value-changed": function(widget: any, value: any) { + alert("Value changed: " + value); + } + } +}); + +photonui.domInsert(select2, "demo"); + +// Separator +var separator = new photonui.Separator(); + +photonui.domInsert(separator, "demo"); + +// Slider +var box = new photonui.BoxLayout({ + children: [ + new photonui.Slider({ + fieldVisible: false, + min: 0, max: 100, + step: 5, + value: 50 + }), + new photonui.Slider({ + fieldVisible: true, + min: -100, max: 100, + step: 10, + value: -50 + }), + new photonui.Slider({ + fieldVisible: true, + min: 0, max: 1, + decimalDigits: 2, + decimalSymbol: ".", + step: 0.05, + value: 0.5 + }) + ] +}); + +photonui.domInsert(box, "demo"); + +// SpriteIcon +// Create the spritesheet +var spriteSheet = new photonui.SpriteSheet({ + name: "default", + imageUrl: "./spritesheet.png", + size: 16, + icons: { + "remove": [ 0, 0], + "add": [16, 0], + "grayHeart": [32, 0], + "redHeart": [48, 0], + "battery1": [ 0, 16], + "battery2": [16, 16], + "battery3": [32, 16], + "battery4": [48, 16] + } +}); + +// Create an icon from the spritesheet +var icon2 = new photonui.SpriteIcon("default/redHeart"); + +photonui.domInsert(icon2, "demo"); + +// SubMenuItem +var menu = new photonui.Menu({ + iconVisible: true, + children: [ + new photonui.SubMenuItem({ + text: "Submenu Item", + menuName: "submenu1", + icon: new photonui.FAIcon("fa-paw") + }), + new photonui.Menu({ + visible: true, // false to hide it by default + name: "submenu1", + iconVisible: true, + children: [ + new photonui.MenuItem({ + text: "Submenu Item 1", + icon: new photonui.FAIcon("fa-gamepad") + }), + new photonui.MenuItem({ + text: "Sumbenu Item 2", + icon: new photonui.FAIcon("fa-flask") + }) + ] + }) + ] +}); + +photonui.domInsert(menu, "demo"); + +// Switch +var sw = new photonui.Switch({ + value: true +}); + +photonui.domInsert(sw, "demo"); + +// TabItem +var tabs = new photonui.TabLayout({ + tabsPosition: "top", // "top", "bottom", "left" or "right" + children: [ + new photonui.TabItem({ + title: "Tab 1", + child: new photonui.Label("Widget inside the first tab") + }), + new photonui.TabItem({ + title: "Tab 2", + child: new photonui.Button() + }), + new photonui.TabItem({ + title: "Tab 3" + }) + ] +}); + +photonui.domInsert(tabs, "demo"); +document.getElementById("demo") + .className += " photonui-container-expand-child"; + +// TabLayout +var tabs = new photonui.TabLayout({ + tabsPosition: "top", // "top", "bottom", "left" or "right" + children: [ + new photonui.TabItem({ + title: "Tab 1", + child: new photonui.Label("Widget inside the first tab") + }), + new photonui.TabItem({ + title: "Tab 2", + child: new photonui.Button() + }), + new photonui.TabItem({ + title: "Tab 3" + }) + ] +}); + +photonui.domInsert(tabs, "demo"); +document.getElementById("demo") + .className += " photonui-container-expand-child"; + +// Text +var text = new photonui.Text({ + rawHtml: "Lorem ipsum dolor sit amet..." +}); + +photonui.domInsert(text, "demo"); + +// TextAreaField +var field3 = new photonui.TextAreaField({ + placeholder: "placeholder", + value: "This is a\nTextArea" +}); + +photonui.domInsert(field3, "demo"); + +// TextField +var field = new photonui.TextField({ + placeholder: "placeholder", + value: "Text" +}); + +photonui.domInsert(field, "demo"); + +var grid = new photonui.GridLayout({ + verticalSpacing: 5, + horizontalSpacing: 5, + children: [ + new photonui.Label({ + text: "Username:", + forInputName: "username-field", + layoutOptions: { + gridX: 0, + gridY: 0 + } + }), + new photonui.TextField({ + name: "username-field", + placeholder: "Username", + value: "Anakin", + layoutOptions: { + gridX: 1, + gridY: 0 + } + }), + new photonui.Label({ + text: "Password:", + forInputName: "password-field", + layoutOptions: { + gridX: 0, + gridY: 1 + } + }), + new photonui.TextField({ + name: "password-field", + type: "password", + placeholder: "password", + value: "D4RK51D3", + layoutOptions: { + gridX: 1, + gridY: 1 + } + }), + new photonui.Button({ + text: "Login", + leftIcon: new photonui.FAIcon("fa-sign-in"), + callbacks: { + click: function(widget: any, event: any) { + var usernameField = photonui.getWidget("username-field"); + var passwordField = photonui.getWidget("password-field"); + alert( + "Username: " + (usernameField).value + + ", Password: " + (passwordField).value + ); + } + }, + layoutOptions: { + gridX: 0, + gridY: 2, + gridWidth: 2 + } + }) + ] +}); + +photonui.domInsert(grid, "demo"); + +// ToggleButton +var toggle = new photonui.ToggleButton({ + value: false, + text: "Toggle Button" +}); + +photonui.domInsert(toggle, "demo"); + +var toggle2 = new photonui.ToggleButton({ + value: false, + text: "Value: off", + buttonColor: "red", + callbacks: { + "value-changed": function(widget: any, value: any) { + widget.text = "Value: " + ((value) ? "on" : "off"); + widget.buttonColor = (value) ? "green" : "red"; + } + } +}); + +photonui.domInsert(toggle2, "demo"); + +// Translation +var translation = new photonui.Translation(); + +translation.addCatalogs({ + "fr": { + "messages": { + "Hello World": ["Bonjour le monde"] + } + } +}); + +translation.locale = "fr"; // Change the locale to test + +var label = new photonui.Label({ + text: _("Hello World"), + text2: translation.lazyGettext("Hello World") +}); + +photonui.domInsert(label, "demo"); + +var tr = new photonui.Translation(); +tr.addCatalogs({ + "fr": { + "plural-forms": "nplurals=2; plural=(n > 1);", + "messages": { + "Hello World": ["Bonjour le monde"], + 'Browser language is "{lang}".': ["La langue du navigateur est « {lang} »."], + "Close": ["Fermer"] + } + }, + "it": { + "plural-forms": "nplurals=2; plural=(n != 1);", + "messages": { + "Hello World": ["Buongiorno il mondo"], + 'Browser language is "{lang}".': ['La lingua del browser è "{lang}".'], + "Close": ["Chiudere"] + } + } +}); +tr.locale = tr.guessUserLanguage(); // Browser language + +// Language selector +var layout = new photonui.BoxLayout({ + orientation: "vertical", + children: [ + new photonui.Label({ + text: _('Browser language is "{lang}".', { + lang: tr.guessUserLanguage() + }) + }), + new photonui.Select({ + name: "lang", + placeholder: "Choose a language...", + value: tr.locale, + children: [ + new photonui.MenuItem({value: "en", text: "English"}), + new photonui.MenuItem({value: "fr", text: "Français"}), + new photonui.MenuItem({value: "it", text: "Italiano"}), + ], + callbacks: { + "value-changed": function(widget: any, value: any) { + tr.locale = value; + } + } + }) + ] +}); +photonui.domInsert(layout, "demo"); + +// A window +var pos = photonui.Helpers.getAbsolutePosition("demo"); +var win = new photonui.Window({ + visible: true, + title: _("Hello World"), + x: pos.x, y: pos.y + 100, + width: 250, + padding: 20, + child: new photonui.Button({ + text: _("Close"), + callbacks: { + "click": function() { win.hide(); } + } + }), + callbacks: { + "close-button-clicked": function(widget: any) { widget.hide(); } + } +}); + +// Viewport +var viewport = new photonui.Viewport({ + width: 300, + height: 200, + padding: 5, + horizontalScrollbar: false, // true, false or null (= auto) + verticalScrollbar: null, // true, false or null (= auto) + child: new photonui.BoxLayout({ + children: [ + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button(), + new photonui.Button() + ] + }) +}); + +photonui.domInsert(viewport, "demo"); + +// Window +var pos = photonui.Helpers.getAbsolutePosition("demo"); + +new photonui.Window({ + title: "My Window", + visible: true, + x: pos.x, y: pos.y, + width: 300, height: 100, + callbacks: { + "close-button-clicked": function(widget: any) { + widget.destroy(); + }, + "position-changed": function(widget: any, x: number, y: number) { + widget.title = "My Window (x: " + x + ", y: " + y + ")"; + } + } +}); + +// Get the position of the #demo area to display windows +// in the right place +var pos = photonui.Helpers.getAbsolutePosition("demo"); + +// Create a window with a button to center it (x axis) on the page +var win1 = new photonui.Window({ + title: "Window 1", + visible: true, + padding: 10, + x: pos.x + 20, y: pos.y + 50, + child: new photonui.Button({ + text: "Center Me", + callbacks: { + click: function(widget: any, event: any) { + win1.center(); + win1.y = pos.y; + } + } + }), + callbacks: { + "close-button-clicked": function(widget: any) { + widget.destroy(); + } + } +}); + +// Create a second window without "close" button +var win2 = new photonui.Window({ + title: "Window 2", + visible: true, + height: 100, + closeButtonVisible: false, + x: pos.x, y: pos.y +}); + +// Focus the first window +win1.show(); diff --git a/photonui/photonui.d.ts b/photonui/photonui.d.ts new file mode 100644 index 000000000..973b241bd --- /dev/null +++ b/photonui/photonui.d.ts @@ -0,0 +1,435 @@ +// Type definitions for PhotonUI v1.0.0 +// Project: https://github.com/wanadev/PhotonUI +// Definitions by: Florent Poujol +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module photonui { + // Base + module Helpers { + function escapeHtml(string: string): void; + function uuid4(): string; + function cleanNode(node: HTMLElement): void; + function getAbsolutePosition(element: HTMLElement|string): { x: number; y: number }; + function numberToCssSize(value: number, defaultValue?: number, nullValue?: string): string; + } + + class Base { + constructor(params?: { [key: string]: any }); + destroy(): void; + registerCallback(id: string, wEvent: string, callback: Function, thisArg: any): void; + removeCallback(id: string): void; + } + + class Widget extends Base { + absolutePosition: { x: number; y: number; }; // readonly + contextMenu: PopupWindow; + contextMenuName: string; + html: HTMLElement; // readonly + layoutOptions: { [key: string]: any }; + name: string; + offsetWidth: number; // readonly + offsetHeight: number; // readonly + parent: Widget; + parentName: string; + tooltip: string; + visible: boolean; + + show(): void; + hide(): void; + unparent(): void; + addClass(className: string): void; + removeClass(className: string): void; + + static getWidget(name: string): Widget; + static domInsert(widget: Widget, element?: HTMLElement|string): void; + } + + // Methods + function domInsert(widget: Widget, element?: HTMLElement|string): void; + function getWidget(name: string): Widget; + + //Widgets + class FileManager extends Base { + acceptedExts: string[]; + acceptedMimes: string[]; + dropZone: HTMLElement; + multiselect: boolean; + + open(): void; + } + + class Translation extends Base { + locale: string; + + addCatalogs(catalogs: { [key: string]: any }): void; + guessUserLanguage(): string; + gettext(string: string, replacements?: { [key: string]: string }): string; + lazyGettext(string: string, replacements?: { [key: string]: string }): string; + enableDomScan(enable: boolean): void; + updateDomTranslation(): void; + } + + class AccelManager extends Base { + addAccel(id: string, keys: string, callback: Function, safe?: boolean): void; + removeAccel(id: string): void; + } + + class MouseManager extends Base { + constructor(params?: { [key: string]: any }); + constructor(element?: Widget|HTMLElement, params?: { [key: string]: any }); + + element: HTMLElement; + threshold: number; + + action: string; // readonly + btnLeft: boolean; // readonly + btnMiddle: boolean; // readonly + btnRight: boolean; // readonly + button: string; // readonly + pageX: number; // readonly + pageY: number; // readonly + x: number; // readonly + y: number; // readonly + deltaX: number; // readonly + deltaY: number; // readonly + } + + // ----------------------------------- + + class BaseIcon extends Widget {} + + class FAIcon extends BaseIcon { + constructor(params?: { [key: string]: any }); + constructor(name: string, params?: { [key: string]: any }); + + color: string; + iconName: string; + size: string; + } + + class SpriteIcon extends BaseIcon { + constructor(params?: { [key: string]: any }); + constructor(name: string, params?: { [key: string]: any }); + + icon: string; + iconName: string; + spriteSheetName: string; + } + + // ----------------------------------- + + class Image extends Widget { + width: number; + height: number; + url: string; + } + + class SpriteSheet extends Base { + name: string; + imageUrl: string; + size: string; + icons: { [iconName: string]: number[] }; + + addIcon(iconName: string, x: number, y: number): void; + removeIcon(iconName: string): void; + getIconPosition(iconName: string): { x: number; y: number; }; + getIconCSS(iconName: string): string; + + static getSpriteSheet(name: string): SpriteSheet; + } + + class Canvas extends Widget { + canvas: HTMLElement; + interactiveMode: HTMLElement; + width: number; + height: number; + getContext(contextId: string): any; + setContext(contextId: string): void; + supportsContext(contextId: string): boolean; + toBlod(imageFormat: string): any; // returns Blob + toBlodHD(imageFormat: string): any; // returns Blob + toDataUrl(imageFormat: string): string; + toDataUrlHD(imageFormat: string): string; + transferControlToProxy(): void; + } + + class Label extends Widget { + constructor(params?: { [key: string]: any }); + constructor(name: string, params?: { [key: string]: any }); + + forInput: Field|CheckBox; + forInputName: string; + text: string; + textAlign: string; + } + + class Text extends Widget { + rawHtml: string; + text: string; + } + + class ProgressBar extends Widget { + orientation: string; + pulsate: boolean; + textVisible: boolean; + value: number; + } + + class Separator extends Widget { + orientation: string; + } + + class Button extends Widget { + appearance: string; // normal | flat + buttonColor: string; + + leftIconName: string; + leftIcon: BaseIcon; + leftIconVisible: boolean; + + rightIconName: string; + rightIcon: BaseIcon; + rightIconVisible: boolean; + + text: string; + textVisible: boolean; + } + + class ColorButton extends Widget { + color: Color; + dialogOnly: boolean; + value: string; + } + + class CheckBox extends Widget { + value: boolean; + } + class Switch extends CheckBox {} + class ToggleButton extends CheckBox {} + + // ----------------------------------- + + class Color extends Base { + constructor(color: string); + constructor(params?: { [key: string]: any }); + + hexString: string; + rgbString: string; // readonly + rgbaString: string; // readonly + + red: number; + green: number; + blue: number; + alpha: number; + + hue: number; + saturation: number; + brightness: number; + + setRGB(red: number, green: number, blue: number): void; + getRGB(): number[]; + setRGBA(red: number, green: number, blue: number, alpha: number): void; + getRGBA(): number[]; + setHSB(hue: number, saturation: number, brightness: number): void; + } + + class ColorPalette extends Widget { + color: Color; + palette: Array; + value: string; + + static palette: Array; + } + + class ColorPicker extends Widget { + color: Color; + value: string; + } + + // ----------------------------------- + + class Field extends Widget { + placeholder: string; + value: boolean; + } + + class NumericField extends Field { + min: number; + max: number; + step: number; + decimalDigits: number; + decimalSymbol: string; + } + + class Slider extends NumericField { + fieldVisible: boolean; + } + + class TextAreaField extends Field { + cols: number; + rows: number; + } + + class TextField extends Field { + type: string; // text, password, email, search, tel, url + } + + // ----------------------------------- + + class Select extends Widget { + children: Widget[]; + childrenNames: string[]; + iconVisible: boolean; + placeholder: string; + popupWidth: number; + popupHeight: number; + popupMaxWidth: number; + popupMinWidth: number; + popupMaxHeight: number; + popupMinHeight: number; + popupOffsetWidth: number; // readonly + popupOffsetHeight: number; // readonly + popupPadding: number; + value: any; // string (maybe) + + addChild(widget: Widget, layoutOptions?: any): void; + } + + class FontSelect extends Select { + fonts: string[]; + + addFont(fontName: string): void; + } + + // ----------------------------------- + + class Container extends Widget { + child: Widget; + childName: string; + containerNode: HTMLElement; // readonly + horizontalChildExpansion: boolean; + verticalChildExpansion: boolean; + + removeChild(widget: Widget): void; + } + + class Layout extends Container { + children: Widget[]; + childrenNames: string[]; + + addChild(widget: Widget, layoutOptions?: { [key: string]: any }): void; + empty(): void; + } + + class BoxLayout extends Layout { + horizontalPadding: number; + verticalPadding: number; + orientation: string; + spacing: number; + } + + class FluidLayout extends Layout { + horizontalPadding: number; + verticalPadding: number; + } + + class GridLayout extends Layout { + horizontalPadding: number; + verticalPadding: number; + horizontalSpacing: number; + verticalSpacing: number; + } + + class Menu extends Layout { + iconVisible: boolean; + } + + class MenuItem extends Menu { + active: boolean; + icon: BaseIcon; + iconName: string; + text: string; + value: any; // string (maybe) + } + + class SubMenuItem extends MenuItem { + menu: Menu; + menuName: string; + } + + // ----------------------------------- + + class Viewport extends Container { + width: number; + minWidth: number; + maxWidth: number; + height: number; + minHeight: number; + maxHeight: number; + padding: number; + horizontalScrollbar: boolean; + verticalScrollbar: boolean; + } + + // ----------------------------------- + + class BaseWindow extends Container { + width: number; + minWidth: number; + maxWidth: number; + height: number; + minHeight: number; + maxHeight: number; + padding: number; + position: { x: number; y: number }; + x: number; + y: number; + + center(): void; + } + + class PopupWindow extends BaseWindow { + popupXY(x: number, y: number): void; + popupWidget(widget: Widget): void; + } + + class PopupMenu extends PopupWindow {} + + class Window extends BaseWindow { + closeButtonVisible: boolean; + modal: boolean; + movable: boolean; + title: string; + + moveToFront(): void; + moveToBack(): void; + } + + class Dialog extends Window { + buttons: Widget[]; + buttonNames: string[]; + + addButton(widget: Widget, layoutOptions: any): void; + removeButton(widget: Widget): void; + } + + class ColorPickerDialog extends Dialog { + color: Color; + } + + // ----------------------------------- + + class TabItem extends Container { + tabHtml: HTMLElement; // readonly + title: string; + } + + class TabLayout extends Layout { + activeTab: Widget; + activeTabName: string; + padding: number; + tabsPosition: string; // top, bottom, left, right + } +} + +declare function _(string: string, replacements?: { [key: string]: string }): string; // alias of Translation.lazyGettext() diff --git a/power-assert/power-assert-tests.ts b/power-assert/power-assert-tests.ts index f7be7059f..d21076b97 100644 --- a/power-assert/power-assert-tests.ts +++ b/power-assert/power-assert-tests.ts @@ -69,9 +69,9 @@ var customizedAssert2 = assert.customize({ circular: '#@Circular#', lineSeparator: '\n', ambiguousEastAsianCharWidth: 2, - widthOf: () => null, - stringify: () => null, - diff: () => null, + widthOf: () => false, + stringify: () => false, + diff: () => false, writerClass: null, renderers: [ './built-in/file', diff --git a/react-router/legacy/react-router-0.12-test.d.ts b/react-router/legacy/react-router-0.12-test.d.ts deleted file mode 100644 index bf6e2e272..000000000 --- a/react-router/legacy/react-router-0.12-test.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// - -declare module 'react-0.12' { - var exports: React.Exports; - export = exports; -} diff --git a/react-router/legacy/react-router-0.12-test.ts b/react-router/legacy/react-router-0.12-test.ts deleted file mode 100644 index e896c80f7..000000000 --- a/react-router/legacy/react-router-0.12-test.ts +++ /dev/null @@ -1,347 +0,0 @@ -/// -/// -"use strict"; - -import React = require('react-0.12'); -import Router = ReactRouter; - -// Mixin -class NavigationTest { - v: T; - - makePath() { - var v1: string = this.v.makePath('to'); - var v2: string = this.v.makePath('to', {id: 1}); - var v3: string = this.v.makePath('to', {id: 1}, {type: 'json'}); - } - makeHref() { - var v1: string = this.v.makeHref('to'); - var v2: string = this.v.makeHref('to', {id: 1}); - var v3: string = this.v.makeHref('to', {id: 1}, {type: 'json'}); - } - transitionTo() { - var v1: void = this.v.transitionTo('to'); - var v2: void = this.v.transitionTo('to', {id: 1}); - var v3: void = this.v.transitionTo('to', {id: 1}, {type: 'json'}); - } - replaceWith() { - var v1: void = this.v.replaceWith('to'); - var v2: void = this.v.replaceWith('to', {id: 1}); - var v3: void = this.v.replaceWith('to', {id: 1}, {type: 'json'}); - } - goBack() { - var v1: void = this.v.goBack(); - } -} - -class StateTest { - v: T; - - getPath() { - var v1: string = this.v.getPath(); - } - - getRoutes() { - var v1: Router.Route[] = this.v.getRoutes(); - } - - getPathname() { - var v1: string = this.v.getPathname(); - } - - getParams() { - var v1: {} = this.v.getParams(); - } - - getQuery() { - var v1: {} = this.v.getQuery(); - } - - isActive() { - var v1: boolean = this.v.isActive('to'); - var v2: boolean = this.v.isActive('to', {id: 1}); - var v3: boolean = this.v.isActive('to', {id: 1}, {type: 'json'}); - } -} - -class RouteHandlerMixinTest { - v: T; - - getRouteDepth() { - var v1: number = this.v.getRouteDepth(); - } - - createChildRouteHandler() { - var v1: Router.RouteHandler = this.v.createChildRouteHandler({ref: 'hoge'}); - } -} - - -// Location -class LocationTest { - v: T; - - push() { - var v1: void = this.v.push('path/to/hoge'); - } - - replace() { - var v1: void = this.v.replace('path/to/hoge'); - } - - pop() { - var v1: void = this.v.pop(); - } - - getCurrentPath() { - var v1: void = this.v.getCurrentPath(); - } -} -new LocationTest(); -new LocationTest(); -new LocationTest(); - -class LocationListenerTest { - v: T; - - addChangeListener() { - var v1: void = this.v.addChangeListener(() => console.log(1)); - } - - removeChangeListener() { - var v1: void = this.v.removeChangeListener(() => console.log(1)); - } -} -new LocationListenerTest(); -new LocationListenerTest(); - - -// Behavior -class ScrollBehaviorTest { - v: T; - - updateScrollPosition() { - var v1: void = this.v.updateScrollPosition({x: 33, y: 102}, 'scrollTop'); - } -} -new ScrollBehaviorTest(); -new ScrollBehaviorTest(); - - -// Component -class DefaultRouteTest { - v: Router.DefaultRoute; - - props() { - var name: string = this.v.props.name; - var handler: React.ComponentClass = this.v.props.handler; - } - - createElement() { - var Handler: React.ComponentClass; - React.createElement(Router.DefaultRoute, null); - React.createElement(Router.DefaultRoute, {name: 'name', handler: Handler}); - } -} - -class LinkTest { - v: Router.Link; - - constructor() { - new NavigationTest(); - new StateTest(); - } - - props() { - var activeClassName: string = this.v.props.activeClassName; - var to: string = this.v.props.to; - var params: {} = this.v.props.params; - var query: {} = this.v.props.query; - var onClick: Function = this.v.props.onClick; - } - - getHref() { - var v1: string = this.v.getHref(); - } - - getClassName() { - var v1: string = this.v.getClassName(); - } - - createElement() { - React.createElement(Router.Link, null); - React.createElement(Router.Link, {to: 'home'}); - React.createElement(Router.Link, { - activeClassName: 'name', - to: 'home', - params: {}, - query: {}, - onClick: () => console.log(1) - }); - } -} - -class NotFoundRouteTest { - v: Router.NotFoundRoute; - - props() { - var name: string = this.v.props.name; - var handler: React.ComponentClass = this.v.props.handler; - } - - createElement() { - var Handler: React.ComponentClass; - React.createElement(Router.NotFoundRoute, null); - React.createElement(Router.NotFoundRoute, {handler: Handler}); - React.createElement(Router.NotFoundRoute, {handler: Handler, name: "home"}); - } -} - -class RedirectTest { - v: Router.Redirect; - - props() { - var path: string = this.v.props.path; - var from: string = this.v.props.from; - var to: string = this.v.props.to; - } - - createElement() { - React.createElement(Router.Redirect, null); - React.createElement(Router.Redirect, {}); - React.createElement(Router.Redirect, {path: 'a', from: 'a', to: 'b'}); - } -} - -class RouteTest { - v: Router.Route; - - props() { - var name: string = this.v.props.name; - var path: string = this.v.props.path; - var handler: React.ComponentClass = this.v.props.handler; - var ignoreScrollBehavior: boolean = this.v.props.ignoreScrollBehavior; - } - - createElement() { - var Handler: React.ComponentClass; - React.createElement(Router.Route, null); - React.createElement(Router.Route, {}); - React.createElement(Router.Route, {name: "home", path: "/", handler: Handler, ignoreScrollBehavior: true}); - } -} - -class RouteHandlerTest { - v: Router.RouteHandler; - - constructor() { - new RouteHandlerMixinTest(); - } - - createElement() { - React.createElement(Router.RouteHandler, null); - React.createElement(Router.RouteHandler, {}); - } -} - - -// History -class HistoryTest { - v: Router.History; - - length() { - var v1: number = this.v.length; - } - - back() { - var v1: void = this.v.back(); - } -} - - -// Router -class CreateTest { - v: Router.Router; - - constructor() { - // React.createElement() version - this.v = Router.create({ - routes: React.createElement(Router.Route, null) - }); - this.v = Router.create({ - routes: React.createElement(Router.Route, null), - location: Router.HistoryLocation, - scrollBehavior: Router.ImitateBrowserBehavior - }); - - // React.createFactory() version - this.v = Router.create({ - routes: React.createFactory(Router.Route)() - }); - this.v = Router.create({ - routes: React.createFactory(Router.Route)(), - location: Router.HistoryLocation, - scrollBehavior: Router.ImitateBrowserBehavior - }); - } - - run() { - this.v.run((Handler) => console.log(Handler)); - this.v.run((Handler, state) => console.log(Handler, state)); - } -} - -class RunTest { - constructor() { - // React.createElement() version - var v1: Router.Router = Router.run(React.createElement(Router.Route, null), (Handler) => { - React.render(React.createElement(Handler, null), document.body); - }); - var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { - React.render(React.createElement(Handler, null), document.body); - }); - - // React.createFactory() version - var v3: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { - React.render(React.createElement(Handler, null), document.body); - }); - var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { - React.render(React.createElement(Handler, null), document.body); - }); - } -} - - -// Transition -class TransitionTest { - constructor() { - var v1: Router.TransitionStaticLifecycle = { - willTransitionTo: (transition, params, query, callback) => { - transition.abort(); - transition.redirect('to'); - transition.redirect('to', {id: 1}); - transition.redirect('to', {id: 1}, {type: 'json'}); - transition.retry(); - }, - willTransitionFrom: (transition, component, callback) => {} - }; - var v2: Router.TransitionStaticLifecycle = { - willTransitionTo: (transition, params, query) => {}, - willTransitionFrom: (transition, component) => {} - }; - var v3: Router.TransitionStaticLifecycle = { - willTransitionTo: (transition, params) => {}, - willTransitionFrom: (transition) => {} - }; - var v4: Router.TransitionStaticLifecycle = { - willTransitionTo: (transition) => {}, - willTransitionFrom: () => {} - }; - var v5: Router.TransitionStaticLifecycle = { - willTransitionTo: () => {} - }; - var v6: Router.TransitionStaticLifecycle = { - willTransitionFrom: () => {} - }; - } -} diff --git a/react-router/legacy/react-router-0.12.d.ts b/react-router/legacy/react-router-0.12.d.ts deleted file mode 100644 index 79763db11..000000000 --- a/react-router/legacy/react-router-0.12.d.ts +++ /dev/null @@ -1,277 +0,0 @@ -// Type definitions for React Router 0.12.0 -// Project: https://github.com/rackt/react-router -// Definitions by: Yuichi Murata -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module ReactRouter { - // - // Mixin - // ---------------------------------------------------------------------- - interface Navigation { - makePath(to: string, params?: {}, query?: {}): string; - makeHref(to: string, params?: {}, query?: {}): string; - transitionTo(to: string, params?: {}, query?: {}): void; - replaceWith(to: string, params?: {}, query?: {}): void; - goBack(): void; - } - - interface RouteHandlerMixin { - getRouteDepth(): number; - createChildRouteHandler(props: {}): RouteHandler; - } - - interface State { - getPath(): string; - getRoutes(): Route[]; - getPathname(): string; - getParams(): {}; - getQuery(): {}; - isActive(to: string, params?: {}, query?: {}): boolean; - } - - var Navigation: Navigation; - var State: State; - var RouteHandlerMixin: RouteHandlerMixin; - - - // - // Component - // ---------------------------------------------------------------------- - // DefaultRoute - interface DefaultRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface DefaultRoute extends React.ReactElement { - __react_router_default_route__: any; // dummy - } - interface DefaultRouteClass extends React.ComponentClass { - __react_router_default_route__: any; // dummy - } - - // Link - interface LinkProp { - activeClassName?: string; - to: string; - params?: {}; - query?: {}; - onClick?: Function; - } - interface Link extends React.ReactElement, Navigation, State { - __react_router_link__: any; // dummy - - getHref(): string; - getClassName(): string; - } - interface LinkClass extends React.ComponentClass { - __react_router_link__: any; // dummy - } - - // NotFoundRoute - interface NotFoundRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface NotFoundRoute extends React.ReactElement { - __react_router_not_found_route__: any; // dummy - } - interface NotFoundRouteClass extends React.ComponentClass { - __react_router_not_found_route__: any; // dummy - } - - // Redirect - interface RedirectProp { - path?: string; - from?: string; - to?: string; - } - interface Redirect extends React.ReactElement { - __react_router_redirect__: any; // dummy - } - interface RedirectClass extends React.ComponentClass { - __react_router_redirect__: any; // dummy - } - - // Route - interface RouteProp { - name?: string; - path?: string; - handler?: React.ComponentClass; - ignoreScrollBehavior?: boolean; - } - interface Route extends React.ReactElement { - __react_router_route__: any; // dummy - } - interface RouteClass extends React.ComponentClass { - __react_router_route__: any; // dummy - } - - // RouteHandler - interface RouteHandlerProp {} - interface RouteHandler extends React.ReactElement, RouteHandlerMixin { - __react_router_route_handler__: any; // dummy - } - interface RouteHandlerClass extends React.ReactElement { - __react_router_route_handler__: any; // dummy - } - - var DefaultRoute: DefaultRouteClass; - var Link: LinkClass; - var NotFoundRoute: NotFoundRouteClass; - var Redirect: RedirectClass; - var Route: RouteClass; - var RouteHandler: RouteHandlerClass; - - - // - // Location - // ---------------------------------------------------------------------- - interface LocationBase { - push(path: string): void; - replace(path: string): void; - pop(): void; - getCurrentPath(): void; - } - - interface LocationListener { - addChangeListener(listener: Function): void; - removeChangeListener(listener: Function): void; - } - - interface HashLocation extends LocationBase, LocationListener {} - interface HistoryLocation extends LocationBase, LocationListener {} - interface RefreshLocation extends LocationBase {} - - var HashLocation: HashLocation; - var HistoryLocation: HistoryLocation; - var RefreshLocation: RefreshLocation; - - - // - // Behavior - // ---------------------------------------------------------------------- - interface ScrollBehaviorBase { - updateScrollPosition(position: {x: number; y: number;}, actionType: string): void; - } - interface ImitateBrowserBehavior extends ScrollBehaviorBase {} - interface ScrollToTopBehavior extends ScrollBehaviorBase {} - - var ImitateBrowserBehavior: ImitateBrowserBehavior; - var ScrollToTopBehavior: ScrollToTopBehavior; - - - // - // Router - // ---------------------------------------------------------------------- - interface Router extends React.ReactElement { - run(callback: RouterRunCallback): void; - } - - interface RouterState { - path: string; - action: string; - pathname: string; - params: {}; - query: {}; - routes : Route[]; - } - - interface RouterCreateOption { - routes: React.ReactElement; - location?: LocationBase; - scrollBehavior?: ScrollBehaviorBase; - } - - type RouterRunCallback = (Handler: Router, state: RouterState) => void; - - function create(options: RouterCreateOption): Router; - function run(routes: React.ReactElement, callback: RouterRunCallback): Router; - function run(routes: React.ReactElement, location: LocationBase, callback: RouterRunCallback): Router; - - - // - // History - // ---------------------------------------------------------------------- - interface History { - back(): void; - length: number; - } - var History: History; - - - // - // Transition - // ---------------------------------------------------------------------- - interface Transition { - abort(): void; - redirect(to: string, params?: {}, query?: {}): void; - retry(): void; - } - - interface TransitionStaticLifecycle { - willTransitionTo?( - transition: Transition, - params: {}, - query: {}, - callback: Function - ): void; - - willTransitionFrom?( - transition: Transition, - component: React.ReactElement, - callback: Function - ): void; - } -} - -declare module 'react-router' { - export = ReactRouter; -} - -declare module React { - interface TopLevelAPI { - // for DefaultRoute - createElement( - type: ReactRouter.DefaultRouteClass, - props: ReactRouter.DefaultRouteProp, - ...children: ReactNode[] - ): ReactRouter.DefaultRoute; - - // for Link - createElement( - type: ReactRouter.LinkClass, - props: ReactRouter.LinkProp, - ...children: ReactNode[] - ): ReactRouter.Link; - - // for NotFoundRoute - createElement( - type: ReactRouter.NotFoundRouteClass, - props: ReactRouter.NotFoundRouteProp, - ...children: ReactNode[] - ): ReactRouter.NotFoundRoute; - - // for Redirect - createElement( - type: ReactRouter.RedirectClass, - props: ReactRouter.RedirectProp, - ...children: ReactNode[] - ): ReactRouter.Redirect; - - // for Route - createElement( - type: ReactRouter.RouteClass, - props: ReactRouter.RouteProp, - ...children: ReactNode[] - ): ReactRouter.Route; - - // for RouteHandler - createElement( - type: ReactRouter.RouteHandlerClass, - props: ReactRouter.RouteHandlerProp, - ...children: ReactNode[] - ): ReactRouter.RouteHandler; - } -} diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 9d0f63b96..d8dd12c97 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -7,6 +7,8 @@ /// declare module ReactRouter { + import React = __React; + // // Transition // ---------------------------------------------------------------------- @@ -276,42 +278,43 @@ declare module "react-router" { export = ReactRouter; } -declare module React { +declare module __React { + // for DefaultRoute function createElement( type: ReactRouter.DefaultRouteClass, props: ReactRouter.DefaultRouteProp, - ...children: React.ReactNode[]): ReactRouter.DefaultRoute; + ...children: __React.ReactNode[]): ReactRouter.DefaultRoute; // for Link function createElement( type: ReactRouter.LinkClass, props: ReactRouter.LinkProp, - ...children: React.ReactNode[]): ReactRouter.Link; + ...children: __React.ReactNode[]): ReactRouter.Link; // for NotFoundRoute function createElement( type: ReactRouter.NotFoundRouteClass, props: ReactRouter.NotFoundRouteProp, - ...children: React.ReactNode[]): ReactRouter.NotFoundRoute; + ...children: __React.ReactNode[]): ReactRouter.NotFoundRoute; // for Redirect function createElement( type: ReactRouter.RedirectClass, props: ReactRouter.RedirectProp, - ...children: React.ReactNode[]): ReactRouter.Redirect; + ...children: __React.ReactNode[]): ReactRouter.Redirect; // for Route function createElement( type: ReactRouter.RouteClass, props: ReactRouter.RouteProp, - ...children: React.ReactNode[]): ReactRouter.Route; + ...children: __React.ReactNode[]): ReactRouter.Route; // for RouteHandler function createElement( type: ReactRouter.RouteHandlerClass, props: ReactRouter.RouteHandlerProp, - ...children: React.ReactNode[]): ReactRouter.RouteHandler; + ...children: __React.ReactNode[]): ReactRouter.RouteHandler; } declare module "react/addons" { @@ -319,35 +322,35 @@ declare module "react/addons" { function createElement( type: ReactRouter.DefaultRouteClass, props: ReactRouter.DefaultRouteProp, - ...children: React.ReactNode[]): ReactRouter.DefaultRoute; + ...children: __React.ReactNode[]): ReactRouter.DefaultRoute; // for Link function createElement( type: ReactRouter.LinkClass, props: ReactRouter.LinkProp, - ...children: React.ReactNode[]): ReactRouter.Link; + ...children: __React.ReactNode[]): ReactRouter.Link; // for NotFoundRoute function createElement( type: ReactRouter.NotFoundRouteClass, props: ReactRouter.NotFoundRouteProp, - ...children: React.ReactNode[]): ReactRouter.NotFoundRoute; + ...children: __React.ReactNode[]): ReactRouter.NotFoundRoute; // for Redirect function createElement( type: ReactRouter.RedirectClass, props: ReactRouter.RedirectProp, - ...children: React.ReactNode[]): ReactRouter.Redirect; + ...children: __React.ReactNode[]): ReactRouter.Redirect; // for Route function createElement( type: ReactRouter.RouteClass, props: ReactRouter.RouteProp, - ...children: React.ReactNode[]): ReactRouter.Route; + ...children: __React.ReactNode[]): ReactRouter.Route; // for RouteHandler function createElement( type: ReactRouter.RouteHandlerClass, props: ReactRouter.RouteHandlerProp, - ...children: React.ReactNode[]): ReactRouter.RouteHandler; + ...children: __React.ReactNode[]): ReactRouter.RouteHandler; } diff --git a/react/legacy/react-0.11-tests.ts b/react/legacy/react-0.11-tests.ts deleted file mode 100644 index 83029993b..000000000 --- a/react/legacy/react-0.11-tests.ts +++ /dev/null @@ -1,108 +0,0 @@ -/// -import React = require("react-0.11"); - -var PropTypesSpecification: React.Specification = { - propTypes: { - // You can declare that a prop is a specific JS primitive. By default, these - // are all optional. - optionalArray: React.PropTypes.array, - optionalBool: React.PropTypes.bool, - optionalFunc: React.PropTypes.func, - optionalNumber: React.PropTypes.number, - optionalObject: React.PropTypes.object, - optionalString: React.PropTypes.string, - - // Anything that can be rendered: numbers, strings, components or an array - // containing these types. - optionalRenderable: React.PropTypes.renderable, - - // A React component. - optionalComponent: React.PropTypes.component, - - // You can also declare that a prop is an instance of a class. This uses - // JS's instanceof operator. - optionalMessage: React.PropTypes.instanceOf(Date), - - // You can ensure that your prop is limited to specific values by treating - // it as an enum. - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']), - - // An object that could be one of many types - optionalUnion: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.number, - React.PropTypes.instanceOf(Date) - ]), - - // An array of a certain type - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), - - // An object with property values of a certain type - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), - - // An object taking on a particular shape - optionalObjectWithShape: React.PropTypes.shape({ - color: React.PropTypes.string, - fontSize: React.PropTypes.number - }), - - // You can chain any of the above with `isRequired` to make sure a warning - // is shown if the prop isn't provided. - requiredFunc: React.PropTypes.func.isRequired, - - // A value of any data type - requiredAny: React.PropTypes.any.isRequired, - - // You can also specify a custom validator. It should return an Error - // object if the validation fails. Don't `console.warn` or throw, as this - // won't work inside `oneOfType`. - customProp: function(props, propName, componentName) { - if (!/matchme/.test(props[propName])) { - return new Error('Validation failed!'); - } - return null; - } - }, - - render: (): React.Descriptor => { - return null; - } -}; - -React.createClass(PropTypesSpecification); - -var mountNode: Element; - -var HelloMessage = React.createClass({displayName: 'HelloMessage', - render: function() { - return React.DOM.div(null, "Hello ", (>this).props.name); - } -}); - -React.renderComponent(HelloMessage({name: "John"}), mountNode); - -var Timer = React.createClass({displayName: 'Timer', - getInitialState: function() { - return {secondsElapsed: 0}; - }, - tick: function() { - (>this).setState({ - secondsElapsed: (>this).state.secondsElapsed + 1 - }); - }, - componentDidMount: function() { - this.interval = setInterval(this.tick, 1000); - }, - componentWillUnmount: function() { - clearInterval(this.interval); - }, - render: function() { - return React.DOM.div( - null, - "Seconds Elapsed: ", - (>this).state.secondsElapsed - ); - } -}); - -React.renderComponent(Timer(null), mountNode); \ No newline at end of file diff --git a/react/legacy/react-0.11.d.ts b/react/legacy/react-0.11.d.ts deleted file mode 100644 index 468dabe8b..000000000 --- a/react/legacy/react-0.11.d.ts +++ /dev/null @@ -1,553 +0,0 @@ -// Type definitions for React 0.11.2 -// Project: http://facebook.github.io/react/ -// Definitions by: Asana -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "react-0.11" { - export = React; -} - -declare module React { - export function createClass(specification: Specification): Factory

; - - export function renderComponent

(component: Descriptor

, container: Element, callback?: () => void): Descriptor

; - - export function unmountComponentAtNode(container: Element): boolean; - - export function renderComponentToString(component: Descriptor): string; - - export function renderComponentToStaticMarkup(component: Descriptor): string; - - export function isValidClass(factory: Factory): boolean; - - export function isValidComponent(component: Descriptor): boolean; - - export function initializeTouchEvents(shouldUseTouch: boolean): void; - - export interface Descriptor

{ - props: P; - } - - export interface Factory

{ - (properties?: P, ...children: any[]): Descriptor

; - } - - export interface Mixin { - componentWillMount?(): void; - componentDidMount?(): void; - componentWillReceiveProps?(nextProps: P): void; - shouldComponentUpdate?(nextProps: P, nextState: S): boolean; - componentWillUpdate?(nextProps: P, nextState: S): void; - componentDidUpdate?(prevProps: P, prevState: S): void; - componentWillUnmount?(): void; - } - - export interface Specification extends Mixin { - displayName?: string; - mixins?: Mixin[]; - statics?: { - [key: string]: Function; - }; - propTypes?: ValidationMap

; - getDefaultProps?(): P; - getInitialState?(): S; - render(): Descriptor; - } - - export interface DomReferencer { - getDOMNode(): Element; - } - - export interface Component extends DomReferencer { - refs: { - [key: string]: DomReferencer - }; - props: P; - state: S; - setState(nextState: S, callback?: () => void): void; - replaceState(nextState: S, callback?: () => void): void; - forceUpdate(callback?: () => void): void; - isMounted(): boolean; - transferPropsTo(target: Factory

): Descriptor

; - setProps(nextProps: P, callback?: () => void): void; - replaceProps(nextProps: P, callback?: () => void): void; - } - - export interface Constructable { - new(): any; - } - - export interface Validator

{ - (props: P, propName: string, componentName: string): Error; - } - - export interface Requireable

extends Validator

{ - isRequired: Validator

; - } - - export interface ValidationMap

{ - [key: string]: Validator

; - } - - export var PropTypes: { - any: Requireable; - array: Requireable; - bool: Requireable; - func: Requireable; - number: Requireable; - object: Requireable; - string: Requireable; - renderable: Requireable; - component: Requireable; - instanceOf: (clazz: Constructable) => Requireable; - oneOf: (types: any[]) => Requireable - oneOfType: (types: Validator[]) => Requireable; - arrayOf: (type: Validator) => Requireable; - objectOf: (type: Validator) => Requireable; - shape: (type: ValidationMap) => Requireable; - }; - - export var Children: { - map(children: any[], fn: (child: any) => any): any[]; - forEach(children: any[], fn: (child: any) => any): void; - count(children: any[]): number; - only(children: any[]): any; - }; - - // Browser Interfaces - // Taken from https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts - export interface AbstractView { - styleMedia: StyleMedia; - document: Document; - } - - export interface Touch { - identifier: number; - target: EventTarget; - screenX: number; - screenY: number; - clientX: number; - clientY: number; - pageX: number; - pageY: number; - } - - export interface TouchList { - [index: number]: Touch; - length: number; - item(index: number): Touch; - identifiedTouch(identifier: number): Touch; - } - - // Events - export interface SyntheticEvent { - bubbles: boolean; - cancelable: boolean; - currentTarget: EventTarget; - defaultPrevented: boolean; - eventPhase: number; - nativeEvent: Event; - preventDefault(): void; - stopPropagation(): void; - target: EventTarget; - timeStamp: Date; - type: string; - } - - export interface ClipboardEvent extends SyntheticEvent { - clipboardData: DataTransfer; - } - - export interface KeyboardEvent extends SyntheticEvent { - altKey: boolean; - charCode: number; - ctrlKey: boolean; - getModifierState(key: string): boolean; - key: string; - keyCode: number; - locale: string; - location: number; - metaKey: boolean; - repeat: boolean; - shiftKey: boolean; - which: number; - } - - export interface FocusEvent extends SyntheticEvent { - relatedTarget: EventTarget; - } - - export interface MouseEvent extends SyntheticEvent { - altKey: boolean; - button: number; - buttons: number; - clientX: number; - clientY: number; - ctrlKey: boolean; - getModifierState(key: string): boolean; - metaKey: boolean; - pageX: number; - pageY: number; - relatedTarget: EventTarget; - screenX: number; - screenY: number; - shiftKey: boolean; - } - - export interface TouchEvent extends SyntheticEvent { - altKey: boolean; - changedTouches: TouchList; - ctrlKey: boolean; - getModifierState(key: string): boolean; - metaKey: boolean; - shiftKey: boolean; - targetTouches: TouchList; - touches: TouchList; - } - - export interface UiEvent extends SyntheticEvent { - detail: number; - view: AbstractView; - } - - export interface WheelEvent extends SyntheticEvent { - deltaMode: number; - deltaX: number; - deltaY: number; - deltaZ: number; - } - - // Attributes - export interface EventAttributes { - onCopy?: (event: ClipboardEvent) => void; - onCut?: (event: ClipboardEvent) => void; - onPaste?: (event: ClipboardEvent) => void; - onKeyDown?: (event: KeyboardEvent) => void; - onKeyPress?: (event: KeyboardEvent) => void; - onKeyUp?: (event: KeyboardEvent) => void; - onFocus?: (event: FocusEvent) => void; - onBlur?: (event: FocusEvent) => void; - onChange?: (event: SyntheticEvent) => void; - onInput?: (event: SyntheticEvent) => void; - onSubmit?: (event: SyntheticEvent) => void; - onClick?: (event: MouseEvent) => void; - onDoubleClick?: (event: MouseEvent) => void; - onDrag?: (event: MouseEvent) => void; - onDragEnd?: (event: MouseEvent) => void; - onDragEnter?: (event: MouseEvent) => void; - onDragExit?: (event: MouseEvent) => void; - onDragLeave?: (event: MouseEvent) => void; - onDragOver?: (event: MouseEvent) => void; - onDragStart?: (event: MouseEvent) => void; - onDrop?: (event: MouseEvent) => void; - onMouseDown?: (event: MouseEvent) => void; - onMouseEnter?: (event: MouseEvent) => void; - onMouseLeave?: (event: MouseEvent) => void; - onMouseMove?: (event: MouseEvent) => void; - onMouseOut?: (event: MouseEvent) => void; - onMouseOver?: (event: MouseEvent) => void; - onMouseUp?: (event: MouseEvent) => void; - onTouchCancel?: (event: TouchEvent) => void; - onTouchEnd?: (event: TouchEvent) => void; - onTouchMove?: (event: TouchEvent) => void; - onTouchStart?: (event: TouchEvent) => void; - onScroll?: (event: UiEvent) => void; - onWheel?: (event: WheelEvent) => void; - } - - export interface ReactAttributes { - dangerouslySetInnerHTML?: { - __html: string; - }; - children?: any[]; - key?: string; - ref?: string; - } - - export interface DomAttributes extends EventAttributes, ReactAttributes { - // HTML Attributes - accept?: any; - accessKey?: any; - action?: any; - allowFullScreen?: any; - allowTransparency?: any; - alt?: any; - async?: any; - autoCapitalize?: any; - autoComplete?: any; - autoCorrect?: any; - autoFocus?: any; - autoPlay?: any; - cellPadding?: any; - cellSpacing?: any; - charSet?: any; - checked?: any; - className?: any; - cols?: any; - colSpan?: any; - content?: any; - contentEditable?: any; - contextMenu?: any; - controls?: any; - coords?: any; - crossOrigin?: any; - data?: any; - dateTime?: any; - defer?: any; - dir?: any; - disabled?: any; - download?: any; - draggable?: any; - encType?: any; - form?: any; - formNoValidate?: any; - frameBorder?: any; - height?: any; - hidden?: any; - href?: any; - hrefLang?: any; - htmlFor?: any; - httpEquiv?: any; - icon?: any; - id?: any; - itemProp?: any; - itemScope?: any; - itemType?: any; - label?: any; - lang?: any; - list?: any; - loop?: any; - max?: any; - maxLength?: any; - mediaGroup?: any; - method?: any; - min?: any; - multiple?: any; - muted?: any; - name?: any; - noValidate?: any; - open?: any; - pattern?: any; - placeholder?: any; - poster?: any; - preload?: any; - property?: any; - radioGroup?: any; - readOnly?: any; - rel?: any; - required?: any; - role?: any; - rows?: any; - rowSpan?: any; - sandbox?: any; - scope?: any; - scrollLeft?: any; - scrolling?: any; - scrollTop?: any; - seamless?: any; - selected?: any; - shape?: any; - size?: any; - span?: any; - spellCheck?: any; - src?: any; - srcDoc?: any; - srcSet?: any; - start?: any; - step?: any; - style?: any; - tabIndex?: any; - target?: any; - title?: any; - type?: any; - useMap?: any; - value?: any; - width?: any; - wmode?: any; - } - - export interface SvgAttributes extends EventAttributes, ReactAttributes { - cx?: any; - cy?: any; - d?: any; - dx?: any; - dy?: any; - fill?: any; - fillOpacity?: any; - fontFamily?: any; - fontSize?: any; - fx?: any; - fy?: any; - gradientTransform?: any; - gradientUnits?: any; - markerEnd?: any; - markerMid?: any; - markerStart?: any; - offset?: any; - opacity?: any; - patternContentUnits?: any; - patternUnits?: any; - points?: any; - preserveAspectRatio?: any; - r?: any; - rx?: any; - ry?: any; - spreadMethod?: any; - stopColor?: any; - stopOpacity?: any; - stroke?: any; - strokeDasharray?: any; - strokeLinecap?: any; - strokeOpacity?: any; - strokeWidth?: any; - textAnchor?: any; - transform?: any; - version?: any; - viewBox?: any; - x1?: any; - x2?: any; - x?: any; - y1?: any; - y2?: any; - y?: any; - } - - export interface DomElement extends Factory { - } - - export interface SvgElement extends Factory { - } - - export var DOM: { - // HTML - a: DomElement; - abbr: DomElement; - address: DomElement; - area: DomElement; - article: DomElement; - aside: DomElement; - audio: DomElement; - b: DomElement; - base: DomElement; - bdi: DomElement; - bdo: DomElement; - big: DomElement; - blockquote: DomElement; - body: DomElement; - br: DomElement; - button: DomElement; - canvas: DomElement; - caption: DomElement; - cite: DomElement; - code: DomElement; - col: DomElement; - colgroup: DomElement; - data: DomElement; - datalist: DomElement; - dd: DomElement; - del: DomElement; - details: DomElement; - dfn: DomElement; - dialog: DomElement; - div: DomElement; - dl: DomElement; - dt: DomElement; - em: DomElement; - embed: DomElement; - fieldset: DomElement; - figcaption: DomElement; - figure: DomElement; - footer: DomElement; - form: DomElement; - h1: DomElement; - h2: DomElement; - h3: DomElement; - h4: DomElement; - h5: DomElement; - h6: DomElement; - head: DomElement; - header: DomElement; - hr: DomElement; - html: DomElement; - i: DomElement; - iframe: DomElement; - img: DomElement; - input: DomElement; - ins: DomElement; - kbd: DomElement; - keygen: DomElement; - label: DomElement; - legend: DomElement; - li: DomElement; - link: DomElement; - main: DomElement; - map: DomElement; - mark: DomElement; - menu: DomElement; - menuitem: DomElement; - meta: DomElement; - meter: DomElement; - nav: DomElement; - noscript: DomElement; - object: DomElement; - ol: DomElement; - optgroup: DomElement; - option: DomElement; - output: DomElement; - p: DomElement; - param: DomElement; - pre: DomElement; - progress: DomElement; - q: DomElement; - rp: DomElement; - rt: DomElement; - ruby: DomElement; - s: DomElement; - samp: DomElement; - script: DomElement; - section: DomElement; - select: DomElement; - small: DomElement; - source: DomElement; - span: DomElement; - strong: DomElement; - style: DomElement; - sub: DomElement; - summary: DomElement; - sup: DomElement; - table: DomElement; - tbody: DomElement; - td: DomElement; - textarea: DomElement; - tfoot: DomElement; - th: DomElement; - thead: DomElement; - time: DomElement; - title: DomElement; - tr: DomElement; - track: DomElement; - u: DomElement; - ul: DomElement; - "var": DomElement; - video: DomElement; - wbr: DomElement; - // SVG - circle: SvgElement; - defs: SvgElement; - ellipse: SvgElement; - g: SvgElement; - line: SvgElement; - linearGradient: SvgElement; - mask: SvgElement; - path: SvgElement; - pattern: SvgElement; - polygon: SvgElement; - polyline: SvgElement; - radialGradient: SvgElement; - rect: SvgElement; - stop: SvgElement; - svg: SvgElement; - text: SvgElement; - tspan: SvgElement; - }; -} \ No newline at end of file diff --git a/react/legacy/react-0.12-tests.ts b/react/legacy/react-0.12-tests.ts deleted file mode 100644 index 27eae4c64..000000000 --- a/react/legacy/react-0.12-tests.ts +++ /dev/null @@ -1,235 +0,0 @@ -/// -import React = require("react"); - -interface Props { - hello: string; - world?: string; - foo: number; - bar: boolean; -} - -interface State { - inputValue?: string; - seconds?: number; -} - -interface MyComponent extends React.CompositeComponent { - reset(): void; -} - -var props: Props = { - key: 42, - ref: "myComponent42", - hello: "world", - foo: 42, - bar: true -}; - -var container: Element; -var INPUT_REF: string = "input"; - -// -// Top-Level API -// -------------------------------------------------------------------------- - -var reactClass: React.ComponentClass = React.createClass({ - getDefaultProps: () => { - return { - hello: undefined, - world: "peace", - foo: undefined, - bar: undefined - }; - }, - getInitialState: () => { - return { - inputValue: "React.js", - seconds: 0 - }; - }, - reset: () => { - this.replaceState(this.getInitialState()); - }, - render: () => { - return React.DOM.div(null, - React.DOM.input({ - ref: INPUT_REF, - value: this.state.inputValue - })); - } -}); - -var reactElement: React.ReactElement = - React.createElement(reactClass, props); - -var reactFactory: React.ComponentFactory = - React.createFactory(reactClass); - -var component: React.Component = - React.render(reactElement, container); - -var unmounted: boolean = React.unmountComponentAtNode(container); -var str: string = React.renderToString(reactElement); -var markup: string = React.renderToStaticMarkup(reactElement); -var notValid: boolean = React.isValidElement(props); // false -var isValid = React.isValidElement(reactElement); // true -React.initializeTouchEvents(true); - -// -// React Elements -// -------------------------------------------------------------------------- - -var type = reactElement.type; -var elementProps: Props = reactElement.props; -var key = reactElement.key; -var ref: string = reactElement.ref; -var factoryElement: React.ReactElement = reactFactory(elementProps); - -// -// React Components -// -------------------------------------------------------------------------- - -var displayName: string = reactClass.displayName; -var defaultProps: Props = reactClass.getDefaultProps(); -var propTypes: React.ValidationMap = reactClass.propTypes; - -// -// Component API -// -------------------------------------------------------------------------- - -var htmlElement: Element = component.getDOMNode(); -var divElement: HTMLDivElement = component.getDOMNode(); -var isMounted: boolean = component.isMounted(); -component.setProps(elementProps); -component.replaceProps(props); - -var compComponent: React.CompositeComponent = - >component; -var initialState: State = compComponent.state; -compComponent.setState({ inputValue: "!!!" }); -compComponent.replaceState({ inputValue: "???", seconds: 60 }); -compComponent.forceUpdate(); - -var inputRef: React.HTMLComponent = - compComponent.refs[INPUT_REF]; -var value: string = inputRef.getDOMNode().value; - -var myComponent = compComponent; -myComponent.reset(); - -// -// Attributes -// -------------------------------------------------------------------------- - -var children = ["Hello world", [null], React.DOM.span(null)]; -var divStyle = { // CSSProperties - flex: "1 1 main-size", - backgroundImage: "url('hello.png')" -}; -var htmlAttr: React.HTMLAttributes = { - key: 36, - ref: "htmlComponent", - children: children, - className: "test-attr", - style: divStyle, - onClick: (event: React.MouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - }, - dangerouslySetInnerHTML: { - __html: "STRONG" - } -}; -React.DOM.div(htmlAttr); -React.DOM.span(htmlAttr); -React.DOM.input(htmlAttr); - -// -// React.PropTypes -// -------------------------------------------------------------------------- - -var PropTypesSpecification: React.ComponentSpec = { - propTypes: { - optionalArray: React.PropTypes.array, - optionalBool: React.PropTypes.bool, - optionalFunc: React.PropTypes.func, - optionalNumber: React.PropTypes.number, - optionalObject: React.PropTypes.object, - optionalString: React.PropTypes.string, - optionalNode: React.PropTypes.node, - optionalElement: React.PropTypes.element, - optionalMessage: React.PropTypes.instanceOf(Date), - optionalEnum: React.PropTypes.oneOf(["News", "Photos"]), - optionalUnion: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.number, - React.PropTypes.instanceOf(Date) - ]), - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), - optionalObjectWithShape: React.PropTypes.shape({ - color: React.PropTypes.string, - fontSize: React.PropTypes.number - }), - requiredFunc: React.PropTypes.func.isRequired, - requiredAny: React.PropTypes.any.isRequired, - customProp: function(props: any, propName: string, componentName: string) { - if (!/matchme/.test(props[propName])) { - return new Error("Validation failed!"); - } - return null; - } - }, - render: (): React.ReactHTMLElement => { - return null; - } -}; - -// -// React.Children -// -------------------------------------------------------------------------- - -var childMap: { [key: string]: number } = - React.Children.map(children, (child) => { return 42; }); -React.Children.forEach(children, (child) => {}); -var nChildren: number = React.Children.count(children); -var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]); - -// -// Example from http://facebook.github.io/react/ -// -------------------------------------------------------------------------- - -interface TimerState { - secondsElapsed: number; -} -interface Timer extends React.CompositeComponent<{}, TimerState> { -} -var Timer = React.createClass({ - displayName: "Timer", - getInitialState: () => { - return { secondsElapsed: 0 }; - }, - tick: () => { - var me = this; - me.setState({ - secondsElapsed: me.state.secondsElapsed + 1 - }); - }, - componentDidMount: () => { - this.interval = setInterval(this.tick, 1000); - }, - componentWillUnmount: () => { - clearInterval(this.interval); - }, - render: () => { - var me = this; - return React.DOM.div( - null, - "Seconds Elapsed: ", - me.state.secondsElapsed - ); - } -}); -var mountNode: Element; -React.render(React.createElement(Timer, null), mountNode); - diff --git a/react/legacy/react-0.12.d.ts b/react/legacy/react-0.12.d.ts deleted file mode 100644 index f2786cbc8..000000000 --- a/react/legacy/react-0.12.d.ts +++ /dev/null @@ -1,934 +0,0 @@ -// Type definitions for React 0.12.1 -// Project: http://facebook.github.io/react/ -// Definitions by: Asana -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module React { - // - // React Elements - // ---------------------------------------------------------------------- - - type ReactType = ComponentClass | string; - - interface ReactElement

{ - type: ComponentClass

| string; - props: P; - key: number | string; - ref: string; - } - - interface ReactHTMLElement extends ReactElement {} - interface ReactSVGElement extends ReactElement {} - - // - // React Nodes - // http://facebook.github.io/react/docs/glossary.html - // ---------------------------------------------------------------------- - - type ReactText = string | number; - type ReactChild = ReactElement | ReactText; - - // Should be Array but type aliases cannot be recursive - type ReactFragment = Array; - type ReactNode = ReactChild | ReactFragment | boolean; - - // - // React Components - // ---------------------------------------------------------------------- - - interface ComponentStatics

{ - displayName?: string; - getDefaultProps?(): P; - propTypes?: ValidationMap

; - } - - interface ComponentClass

extends ComponentStatics

{ - // Deprecated in 0.12. See http://fb.me/react-legacyfactory - // new(props: P): ReactElement

; - // (props: P): ReactElement

; - } - - // - // ReactElement Factories - // ---------------------------------------------------------------------- - - interface ComponentFactory

{ - (props?: P, ...children: ReactNode[]): ReactElement

; - } - - interface HTMLFactory extends ComponentFactory {} - interface SVGFactory extends ComponentFactory {} - - // - // Top-Level API - // ---------------------------------------------------------------------- - - interface TopLevelAPI { - createClass

(spec: ComponentSpec): ComponentClass

; - createElement

(type: ComponentClass

| string, props: P, ...children: ReactNode[]): ReactElement

; - createFactory

(componentClass: ComponentClass

): ComponentFactory

; - render

(element: ReactElement

, container: Element, callback?: () => any): Component

; - unmountComponentAtNode(container: Element): boolean; - renderToString(element: ReactElement): string; - renderToStaticMarkup(element: ReactElement): string; - isValidElement(object: {}): boolean; - initializeTouchEvents(shouldUseTouch: boolean): void; - } - - // - // Component API - // ---------------------------------------------------------------------- - - interface Component

{ - // Use this overload to cast the returned element to a more specific type. - // Eg: var name = this.refs['name'].getDOMNode().value; - getDOMNode(): TElement; - getDOMNode(): Element; - isMounted(): boolean; - - props: P; - setProps(nextProps: P, callback?: () => any): void; - replaceProps(nextProps: P, callback?: () => any): void; - } - - interface DOMComponent

extends Component

{ - tagName: string; - } - - interface HTMLComponent extends DOMComponent {} - interface SVGComponent extends DOMComponent {} - - interface CompositeComponent extends Component

, ComponentSpec { - state: S; - setState(nextState: S, callback?: () => any): void; - replaceState(nextState: S, callback?: () => any): void; - forceUpdate(callback?: () => any): void; - refs: { - [key: string]: Component - }; - } - - // - // Component Specs and Lifecycle - // ---------------------------------------------------------------------- - - interface Mixin extends ComponentStatics

{ - mixins?: Mixin; - statics?: { - [key: string]: any; - }; - - // Definition methods - getInitialState?(): S; - - // Delegate methods - componentWillMount?(): void; - componentDidMount?(): void; - componentWillReceiveProps?(nextProps: P): void; - shouldComponentUpdate?(nextProps: P, nextState: S): boolean; - componentWillUpdate?(nextProps: P, nextState: S): void; - componentDidUpdate?(prevProps: P, prevState: S): void; - componentWillUnmount?(): void; - } - - interface ComponentSpec extends Mixin { - render(): ReactElement; - } - - // - // Event System - // ---------------------------------------------------------------------- - - interface SyntheticEvent { - bubbles: boolean; - cancelable: boolean; - currentTarget: EventTarget; - defaultPrevented: boolean; - eventPhase: number; - isTrusted: boolean; - nativeEvent: Event; - preventDefault(): void; - stopPropagation(): void; - target: EventTarget; - timeStamp: Date; - type: string; - } - - interface ClipboardEvent extends SyntheticEvent { - clipboardData: DataTransfer; - } - - interface KeyboardEvent extends SyntheticEvent { - altKey: boolean; - charCode: number; - ctrlKey: boolean; - getModifierState(key: string): boolean; - key: string; - keyCode: number; - locale: string; - location: number; - metaKey: boolean; - repeat: boolean; - shiftKey: boolean; - which: number; - } - - interface FocusEvent extends SyntheticEvent { - relatedTarget: EventTarget; - } - - interface FormEvent extends SyntheticEvent { - } - - interface MouseEvent extends SyntheticEvent { - altKey: boolean; - button: number; - buttons: number; - clientX: number; - clientY: number; - ctrlKey: boolean; - getModifierState(key: string): boolean; - metaKey: boolean; - pageX: number; - pageY: number; - relatedTarget: EventTarget; - screenX: number; - screenY: number; - shiftKey: boolean; - } - - interface TouchEvent extends SyntheticEvent { - altKey: boolean; - changedTouches: TouchList; - ctrlKey: boolean; - getModifierState(key: string): boolean; - metaKey: boolean; - shiftKey: boolean; - targetTouches: TouchList; - touches: TouchList; - } - - interface UIEvent extends SyntheticEvent { - detail: number; - view: AbstractView; - } - - interface WheelEvent extends SyntheticEvent { - deltaMode: number; - deltaX: number; - deltaY: number; - deltaZ: number; - } - - // - // Event Handler Types - // ---------------------------------------------------------------------- - - interface EventHandler { - (event: E): void; - } - - interface ClipboardEventHandler extends EventHandler {} - interface KeyboardEventHandler extends EventHandler {} - interface FocusEventHandler extends EventHandler {} - interface FormEventHandler extends EventHandler {} - interface MouseEventHandler extends EventHandler {} - interface TouchEventHandler extends EventHandler {} - interface UIEventHandler extends EventHandler {} - interface WheelEventHandler extends EventHandler {} - - // - // Attributes - // ---------------------------------------------------------------------- - - export interface ReactAttributes { - children?: ReactNode; - key?: number | string; - ref?: string; - - // Event Attributes - onCopy?: ClipboardEventHandler; - onCut?: ClipboardEventHandler; - onPaste?: ClipboardEventHandler; - onKeyDown?: KeyboardEventHandler; - onKeyPress?: KeyboardEventHandler; - onKeyUp?: KeyboardEventHandler; - onFocus?: FocusEventHandler; - onBlur?: FocusEventHandler; - onChange?: FormEventHandler; - onInput?: FormEventHandler; - onSubmit?: FormEventHandler; - onClick?: MouseEventHandler; - onDoubleClick?: MouseEventHandler; - onDrag?: MouseEventHandler; - onDragEnd?: MouseEventHandler; - onDragEnter?: MouseEventHandler; - onDragExit?: MouseEventHandler; - onDragLeave?: MouseEventHandler; - onDragOver?: MouseEventHandler; - onDragStart?: MouseEventHandler; - onDrop?: MouseEventHandler; - onMouseDown?: MouseEventHandler; - onMouseEnter?: MouseEventHandler; - onMouseLeave?: MouseEventHandler; - onMouseMove?: MouseEventHandler; - onMouseOut?: MouseEventHandler; - onMouseOver?: MouseEventHandler; - onMouseUp?: MouseEventHandler; - onTouchCancel?: TouchEventHandler; - onTouchEnd?: TouchEventHandler; - onTouchMove?: TouchEventHandler; - onTouchStart?: TouchEventHandler; - onScroll?: UIEventHandler; - onWheel?: WheelEventHandler; - - dangerouslySetInnerHTML?: { - __html: string; - }; - } - - interface CSSProperties { - columnCount?: number; - flex?: number | string; - flexGrow?: number; - flexShrink?: number; - fontWeight?: number; - lineClamp?: number; - lineHeight?: number; - opacity?: number; - order?: number; - orphans?: number; - widows?: number; - zIndex?: number; - zoom?: number; - - // SVG-related properties - fillOpacity?: number; - strokeOpacity?: number; - } - - interface HTMLAttributes extends ReactAttributes { - accept?: string; - acceptCharset?: string; - accessKey?: string; - action?: string; - allowFullScreen?: boolean; - allowTransparency?: boolean; - alt?: string; - async?: boolean; - autoComplete?: boolean; - autoFocus?: boolean; - autoPlay?: boolean; - cellPadding?: number | string; - cellSpacing?: number | string; - charSet?: string; - checked?: boolean; - classID?: string; - className?: string; - cols?: number; - colSpan?: number; - content?: string; - contentEditable?: boolean; - contextMenu?: string; - controls?: any; - coords?: string; - crossOrigin?: string; - data?: string; - dateTime?: string; - defer?: boolean; - dir?: string; - disabled?: boolean; - download?: any; - draggable?: boolean; - encType?: string; - form?: string; - formNoValidate?: boolean; - frameBorder?: number | string; - height?: number | string; - hidden?: boolean; - href?: string; - hrefLang?: string; - htmlFor?: string; - httpEquiv?: string; - icon?: string; - id?: string; - label?: string; - lang?: string; - list?: string; - loop?: boolean; - manifest?: string; - max?: number | string; - maxLength?: number; - media?: string; - mediaGroup?: string; - method?: string; - min?: number | string; - multiple?: boolean; - muted?: boolean; - name?: string; - noValidate?: boolean; - open?: boolean; - pattern?: string; - placeholder?: string; - poster?: string; - preload?: string; - radioGroup?: string; - readOnly?: boolean; - rel?: string; - required?: boolean; - role?: string; - rows?: number; - rowSpan?: number; - sandbox?: string; - scope?: string; - scrollLeft?: number; - scrolling?: string; - scrollTop?: number; - seamless?: boolean; - selected?: boolean; - shape?: string; - size?: number; - sizes?: string; - span?: number; - spellCheck?: boolean; - src?: string; - srcDoc?: string; - srcSet?: string; - start?: number; - step?: number | string; - style?: CSSProperties; - tabIndex?: number; - target?: string; - title?: string; - type?: string; - useMap?: string; - value?: string; - width?: number | string; - wmode?: string; - - // Non-standard Attributes - autoCapitalize?: boolean; - autoCorrect?: boolean; - property?: string; - itemProp?: string; - itemScope?: boolean; - itemType?: string; - } - - interface SVGAttributes extends ReactAttributes { - cx?: SVGLength | SVGAnimatedLength; - cy?: any; - d?: string; - dx?: SVGLength | SVGAnimatedLength; - dy?: SVGLength | SVGAnimatedLength; - fill?: any; // SVGPaint | string - fillOpacity?: number | string; - fontFamily?: string; - fontSize?: number | string; - fx?: SVGLength | SVGAnimatedLength; - fy?: SVGLength | SVGAnimatedLength; - gradientTransform?: SVGTransformList | SVGAnimatedTransformList; - gradientUnits?: string; - markerEnd?: string; - markerMid?: string; - markerStart?: string; - offset?: number | string; - opacity?: number | string; - patternContentUnits?: string; - patternUnits?: string; - points?: string; - preserveAspectRatio?: string; - r?: SVGLength | SVGAnimatedLength; - rx?: SVGLength | SVGAnimatedLength; - ry?: SVGLength | SVGAnimatedLength; - spreadMethod?: string; - stopColor?: any; // SVGColor | string - stopOpacity?: number | string; - stroke?: any; // SVGPaint - strokeDasharray?: string; - strokeLinecap?: string; - strokeOpacity?: number | string; - strokeWidth?: SVGLength | SVGAnimatedLength; - textAnchor?: string; - transform?: SVGTransformList | SVGAnimatedTransformList; - version?: string; - viewBox?: string; - x1?: SVGLength | SVGAnimatedLength; - x2?: SVGLength | SVGAnimatedLength; - x?: SVGLength | SVGAnimatedLength; - y1?: SVGLength | SVGAnimatedLength; - y2?: SVGLength | SVGAnimatedLength - y?: SVGLength | SVGAnimatedLength; - } - - // - // React.DOM - // ---------------------------------------------------------------------- - - interface ReactDOM { - // HTML - a: HTMLFactory; - abbr: HTMLFactory; - address: HTMLFactory; - area: HTMLFactory; - article: HTMLFactory; - aside: HTMLFactory; - audio: HTMLFactory; - b: HTMLFactory; - base: HTMLFactory; - bdi: HTMLFactory; - bdo: HTMLFactory; - big: HTMLFactory; - blockquote: HTMLFactory; - body: HTMLFactory; - br: HTMLFactory; - button: HTMLFactory; - canvas: HTMLFactory; - caption: HTMLFactory; - cite: HTMLFactory; - code: HTMLFactory; - col: HTMLFactory; - colgroup: HTMLFactory; - data: HTMLFactory; - datalist: HTMLFactory; - dd: HTMLFactory; - del: HTMLFactory; - details: HTMLFactory; - dfn: HTMLFactory; - dialog: HTMLFactory; - div: HTMLFactory; - dl: HTMLFactory; - dt: HTMLFactory; - em: HTMLFactory; - embed: HTMLFactory; - fieldset: HTMLFactory; - figcaption: HTMLFactory; - figure: HTMLFactory; - footer: HTMLFactory; - form: HTMLFactory; - h1: HTMLFactory; - h2: HTMLFactory; - h3: HTMLFactory; - h4: HTMLFactory; - h5: HTMLFactory; - h6: HTMLFactory; - head: HTMLFactory; - header: HTMLFactory; - hr: HTMLFactory; - html: HTMLFactory; - i: HTMLFactory; - iframe: HTMLFactory; - img: HTMLFactory; - input: HTMLFactory; - ins: HTMLFactory; - kbd: HTMLFactory; - keygen: HTMLFactory; - label: HTMLFactory; - legend: HTMLFactory; - li: HTMLFactory; - link: HTMLFactory; - main: HTMLFactory; - map: HTMLFactory; - mark: HTMLFactory; - menu: HTMLFactory; - menuitem: HTMLFactory; - meta: HTMLFactory; - meter: HTMLFactory; - nav: HTMLFactory; - noscript: HTMLFactory; - object: HTMLFactory; - ol: HTMLFactory; - optgroup: HTMLFactory; - option: HTMLFactory; - output: HTMLFactory; - p: HTMLFactory; - param: HTMLFactory; - picture: HTMLFactory; - pre: HTMLFactory; - progress: HTMLFactory; - q: HTMLFactory; - rp: HTMLFactory; - rt: HTMLFactory; - ruby: HTMLFactory; - s: HTMLFactory; - samp: HTMLFactory; - script: HTMLFactory; - section: HTMLFactory; - select: HTMLFactory; - small: HTMLFactory; - source: HTMLFactory; - span: HTMLFactory; - strong: HTMLFactory; - style: HTMLFactory; - sub: HTMLFactory; - summary: HTMLFactory; - sup: HTMLFactory; - table: HTMLFactory; - tbody: HTMLFactory; - td: HTMLFactory; - textarea: HTMLFactory; - tfoot: HTMLFactory; - th: HTMLFactory; - thead: HTMLFactory; - time: HTMLFactory; - title: HTMLFactory; - tr: HTMLFactory; - track: HTMLFactory; - u: HTMLFactory; - ul: HTMLFactory; - "var": HTMLFactory; - video: HTMLFactory; - wbr: HTMLFactory; - - // SVG - circle: SVGFactory; - defs: SVGFactory; - ellipse: SVGFactory; - g: SVGFactory; - line: SVGFactory; - linearGradient: SVGFactory; - mask: SVGFactory; - path: SVGFactory; - pattern: SVGFactory; - polygon: SVGFactory; - polyline: SVGFactory; - radialGradient: SVGFactory; - rect: SVGFactory; - stop: SVGFactory; - svg: SVGFactory; - text: SVGFactory; - tspan: SVGFactory; - } - - // - // React.PropTypes - // ---------------------------------------------------------------------- - - interface Validator { - (object: T, key: string, componentName: string): Error; - } - - interface Requireable extends Validator { - isRequired: Validator; - } - - interface ValidationMap { - [key: string]: Validator; - } - - interface ReactPropTypes { - any: Requireable; - array: Requireable; - bool: Requireable; - func: Requireable; - number: Requireable; - object: Requireable; - string: Requireable; - node: Requireable; - element: Requireable; - instanceOf(expectedClass: {}): Requireable; - oneOf(types: any[]): Requireable; - oneOfType(types: Validator[]): Requireable; - arrayOf(type: Validator): Requireable; - objectOf(type: Validator): Requireable; - shape(type: ValidationMap): Requireable; - } - - // - // React.Children - // ---------------------------------------------------------------------- - - interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; - count(children: ReactNode): number; - only(children: ReactNode): ReactChild; - } - - // - // React.addons - // ---------------------------------------------------------------------- - - interface ClassSet { - [key: string]: boolean; - } - - // - // React.addons (Transitions) - // ---------------------------------------------------------------------- - - interface TransitionGroupProps { - component?: ReactType; - childFactory?: (child: ReactElement) => ReactElement; - } - - interface CSSTransitionGroupProps extends TransitionGroupProps { - transitionName: string; - transitionAppear?: boolean; - transitionEnter?: boolean; - transitionLeave?: boolean; - } - - interface CSSTransitionGroup extends ComponentClass {} - interface TransitionGroup extends ComponentClass {} - - // - // React.addons (Mixins) - // ---------------------------------------------------------------------- - - interface ReactLink { - value: T; - requestChange(newValue: T): void; - } - - interface LinkedStateMixin extends Mixin { - linkState(key: string): ReactLink; - } - - interface PureRenderMixin extends Mixin { - } - - // - // Reat.addons.update - // ---------------------------------------------------------------------- - - interface UpdateSpec { - $set: any; - $merge: {}; - $apply(value: any): any; - // [key: string]: UpdateSpec; - } - - interface UpdateArraySpec extends UpdateSpec { - $push?: any[]; - $unshift?: any[]; - $splice?: any[][]; - } - - // - // React.addons.Perf - // ---------------------------------------------------------------------- - - interface ComponentPerfContext { - current: string; - owner: string; - } - - interface NumericPerfContext { - [key: string]: number; - } - - interface Measurements { - exclusive: NumericPerfContext; - inclusive: NumericPerfContext; - render: NumericPerfContext; - counts: NumericPerfContext; - writes: NumericPerfContext; - displayNames: { - [key: string]: ComponentPerfContext; - }; - totalTime: number; - } - - interface ReactPerf { - start(): void; - stop(): void; - printInclusive(measurements: Measurements[]): void; - printExclusive(measurements: Measurements[]): void; - printWasted(measurements: Measurements[]): void; - printDOM(measurements: Measurements[]): void; - getLastMeasurements(): Measurements[]; - } - - // - // React.addons.TestUtils - // ---------------------------------------------------------------------- - - interface MockedComponentClass { - new(): any; - } - - interface ReactTestUtils { - Simulate: Simulate; - - renderIntoDocument

(element: ReactElement

): Component

; - renderIntoDocument>(element: ReactElement): C; - - mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils; - - isElementOfType(element: ReactElement, type: ReactType): boolean; - isDOMComponent(instance: Component): boolean; - isCompositeComponent(instance: Component): boolean; - isCompositeComponentWithType(instance: Component, type: ComponentClass): boolean; - isTextComponent(instance: Component): boolean; - - findAllInRenderedTree(tree: Component, fn: (i: Component) => boolean): Component; - - scryRenderedDOMComponentsWithClass(tree: Component, className: string): DOMComponent[]; - findRenderedDOMComponentWithClass(tree: Component, className: string): DOMComponent; - - scryRenderedDOMComponentsWithTag(tree: Component, tagName: string): DOMComponent[]; - findRenderedDOMComponentWithTag(tree: Component, tagName: string): DOMComponent; - - scryRenderedComponentsWithType( - tree: Component, type: ComponentClass

): CompositeComponent[]; - scryRenderedComponentsWithType>( - tree: Component, type: ComponentClass): C[]; - - findRenderedComponentWithType( - tree: Component, type: ComponentClass

(element: ReactElement

, props: P): ReactElement

; - - update(value: any[], spec: UpdateArraySpec): any[]; - update(value: {}, spec: UpdateSpec): any; - - // Development tools - Perf: ReactPerf; - TestUtils: ReactTestUtils; - }; - } - - // - // Browser Interfaces - // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts - // ---------------------------------------------------------------------- - - interface AbstractView { - styleMedia: StyleMedia; - document: Document; - } - - interface Touch { - identifier: number; - target: EventTarget; - screenX: number; - screenY: number; - clientX: number; - clientY: number; - pageX: number; - pageY: number; - } - - interface TouchList { - [index: number]: Touch; - length: number; - item(index: number): Touch; - identifiedTouch(identifier: number): Touch; - } -} - -declare module "react" { - var exports: React.Exports; - export = exports; -} - -declare module "react/addons" { - var exports: React.AddonsExports; - export = exports; -} - diff --git a/react/legacy/react-addons-0.11-tests.ts b/react/legacy/react-addons-0.11-tests.ts deleted file mode 100644 index e34e42fbc..000000000 --- a/react/legacy/react-addons-0.11-tests.ts +++ /dev/null @@ -1,133 +0,0 @@ -/// -import React = require("react/addons-0.11"); - -var PropTypesSpecification: React.Specification = { - propTypes: { - // You can declare that a prop is a specific JS primitive. By default, these - // are all optional. - optionalArray: React.PropTypes.array, - optionalBool: React.PropTypes.bool, - optionalFunc: React.PropTypes.func, - optionalNumber: React.PropTypes.number, - optionalObject: React.PropTypes.object, - optionalString: React.PropTypes.string, - - // Anything that can be rendered: numbers, strings, components or an array - // containing these types. - optionalRenderable: React.PropTypes.renderable, - - // A React component. - optionalComponent: React.PropTypes.component, - - // You can also declare that a prop is an instance of a class. This uses - // JS's instanceof operator. - optionalMessage: React.PropTypes.instanceOf(Date), - - // You can ensure that your prop is limited to specific values by treating - // it as an enum. - optionalEnum: React.PropTypes.oneOf(['News', 'Photos']), - - // An object that could be one of many types - optionalUnion: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.number, - React.PropTypes.instanceOf(Date) - ]), - - // An array of a certain type - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), - - // An object with property values of a certain type - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), - - // An object taking on a particular shape - optionalObjectWithShape: React.PropTypes.shape({ - color: React.PropTypes.string, - fontSize: React.PropTypes.number - }), - - // You can chain any of the above with `isRequired` to make sure a warning - // is shown if the prop isn't provided. - requiredFunc: React.PropTypes.func.isRequired, - - // A value of any data type - requiredAny: React.PropTypes.any.isRequired, - - // You can also specify a custom validator. It should return an Error - // object if the validation fails. Don't `console.warn` or throw, as this - // won't work inside `oneOfType`. - customProp: function(props, propName, componentName) { - if (!/matchme/.test(props[propName])) { - return new Error('Validation failed!'); - } - return null; - } - }, - render: (): React.Descriptor => { - return null; - } -}; - -React.createClass(PropTypesSpecification); - -var mountNode: Element; - -var HelloMessage = React.createClass({displayName: 'HelloMessage', - render: function() { - return React.DOM.div(null, "Hello ", (>this).props.name); - } -}); - -React.renderComponent(HelloMessage({name: "John"}), mountNode); - -var Timer = React.createClass({displayName: 'Timer', - getInitialState: function() { - return {secondsElapsed: 0}; - }, - tick: function() { - (>this).setState({ - secondsElapsed: (>this).state.secondsElapsed + 1 - }); - }, - componentDidMount: function() { - this.interval = setInterval(this.tick, 1000); - }, - componentWillUnmount: function() { - clearInterval(this.interval); - }, - render: function() { - return React.DOM.div( - null, - "Seconds Elapsed: ", - (>this).state.secondsElapsed - ); - } -}); - -React.renderComponent(Timer(null), mountNode); - -// TestUtils -var that: React.Component; -var node = that.refs['input'].getDOMNode(); -React.addons.TestUtils.Simulate.click(node); -React.addons.TestUtils.Simulate.change(node); -React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"}); - -var GoodbyeMessage = React.createClass({displayName: 'GoodbyeMessage', - render: function() { - return React.DOM.div(null, "Goodbye ", (>this).props.name); - } -}); -React.addons.TestUtils.renderIntoDocument(GoodbyeMessage({name: "John"})); - -var isImportant: boolean; -var isRead: boolean; -var cx = React.addons.classSet; -var classes = cx({ - 'message': true, - 'message-important': isImportant, - 'message-read': isRead -}); - - - diff --git a/react/legacy/react-addons-0.11.d.ts b/react/legacy/react-addons-0.11.d.ts deleted file mode 100644 index d02740246..000000000 --- a/react/legacy/react-addons-0.11.d.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Type definitions for React with Addons 0.11.2 -// Project: http://facebook.github.io/react/ -// Definitions by: Asana -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "react/addons-0.11" { - export = React; -} - -declare module React { - export var addons: { - classSet: (classes: {[key: string]: boolean}) => string; - cloneWithProps: CloneWithProps; - CSSTransitionGroup: Factory; - LinkedStateMixin: LinkedStateMixin; - Perf: Perf; - PureRenderMixin: Mixin; - TestUtils: TestUtils; - TransitionGroup: Factory; - update(object: Object, changes: Object): Object; - }; - - export interface CloneWithProps

{ - (instance: Descriptor

, extraProps?: P): Descriptor

; - } - - export interface ReactLink { - value: T; - requestChange(newValue: T): void; - } - - export interface LinkedStateMixin extends Mixin { - linkState(key: string): ReactLink; - } - - export interface ComponentPerfContext { - current: string; - owner: string; - } - - export interface CSSTransitionGroupProps { - transitionName: string; - } - - export interface TransitionsSpecification extends Specification { - componentWillEnter?(callback: () => void): void; - componentDidEnter?(): void; - componentWillLeave?(callback: () => void): void; - componentDidLeave?(): void; - } - - export interface NumericPerfContext { - [key: string]: number; - } - - export interface Measurements { - exclusive: NumericPerfContext; - inclusive: NumericPerfContext; - render: NumericPerfContext; - counts: NumericPerfContext; - writes: NumericPerfContext; - displayNames: { - [key: string]: ComponentPerfContext; - }; - totalTime: number; - } - - export interface Perf { - start(): void; - stop(): void; - printInclusive(measurements: Measurements[]): void; - printExclusive(measurements: Measurements[]): void; - printWasted(measurements: Measurements[]): void; - printDOM(measurements: Measurements[]): void; - getLastMeasurements(): Measurements[]; - } - - export interface TestUtils { - Simulate: Simulate; - renderIntoDocument(instance: Descriptor): Descriptor; - mockComponent(componentClass: Factory, mockTagName?: string): TestUtils; - isDescriptorOfType(descriptor: Descriptor, componentClass: Factory): boolean; - isDOMComponent(instance: Descriptor): boolean; - isCompositeComponent(instance: Descriptor): boolean; - isCompositeComponentWithType(instance: Descriptor, componentClass: Function): boolean; - isTextComponent(instance: Descriptor): boolean; - findAllInRenderedTree(tree: Descriptor, test: Function): Descriptor[]; - scryRenderedDOMComponentsWithClass(tree: Descriptor, className: string): Descriptor[]; - findRenderedDOMComponentWithClass(tree: Descriptor, className: string): Descriptor; - scryRenderedDOMComponentsWithTag(tree: Descriptor, className: string): Descriptor[]; - findRenderedDOMComponentWithTag(tree: Descriptor, tagName: string): Descriptor; - scryFindRenderedComponentsWithTag(tree: Descriptor, componentClass: Function): Descriptor[]; - findRenderedComponentWithType(tree: Descriptor, componentClass: Function): Descriptor; - } - - export interface SyntheticEventData { - altKey?: boolean; - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - changedTouches?: TouchList; - charCode?: boolean; - clipboardData?: DataTransfer; - ctrlKey?: boolean; - deltaMode?: number; - deltaX?: number; - deltaY?: number; - deltaZ?: number; - detail?: number; - getModifierState?(key: string): boolean; - key?: string; - keyCode?: number; - locale?: string; - location?: number; - metaKey?: boolean; - pageX?: number; - pageY?: number; - relatedTarget?: EventTarget; - repeat?: boolean; - screenX?: number; - screenY?: number; - shiftKey?: boolean; - targetTouches?: TouchList; - touches?: TouchList; - view?: AbstractView; - which?: number; - } - - export interface EventSimulator { - (element: Element, eventData?: SyntheticEventData): void; - (descriptor: Descriptor, eventData?: SyntheticEventData): void; - } - - export interface Simulate { - blur: EventSimulator; - change: EventSimulator; - click: EventSimulator; - cut: EventSimulator; - doubleClick: EventSimulator; - drag: EventSimulator; - dragEnd: EventSimulator; - dragEnter: EventSimulator; - dragExit: EventSimulator; - dragLeave: EventSimulator; - dragOver: EventSimulator; - dragStart: EventSimulator; - drop: EventSimulator; - focus: EventSimulator; - input: EventSimulator; - keyDown: EventSimulator; - keyPress: EventSimulator; - keyUp: EventSimulator; - mouseDown: EventSimulator; - mouseEnter: EventSimulator; - mouseLeave: EventSimulator; - mouseMove: EventSimulator; - mouseOut: EventSimulator; - mouseOver: EventSimulator; - mouseUp: EventSimulator; - paste: EventSimulator; - scroll: EventSimulator; - submit: EventSimulator; - touchCancel: EventSimulator; - touchEnd: EventSimulator; - touchMove: EventSimulator; - touchStart: EventSimulator; - wheel: EventSimulator; - } -} diff --git a/react/legacy/react-addons-0.12-tests.ts b/react/legacy/react-addons-0.12-tests.ts deleted file mode 100644 index ca05c00ca..000000000 --- a/react/legacy/react-addons-0.12-tests.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// -import React = require("react/addons"); - -var isImportant: boolean; -var isRead: boolean; -var classSet: React.ClassSet = { - "message": true, - "message-important": isImportant, - "message-read": isRead -}; -var cx = React.addons.classSet; -var classes: string = cx(classSet); - -// -// React.addons (Transitions) -// -------------------------------------------------------------------------- - -React.createFactory(React.addons.TransitionGroup)({ component: "div" }); -React.createFactory(React.addons.CSSTransitionGroup)({ - component: React.createClass({ - render: (): React.ReactElement => null - }), - childFactory: (c) => c, - transitionName: "transition", - transitionAppear: false, - transitionEnter: true, - transitionLeave: true -}); - -// -// React.addons.TestUtils -// -------------------------------------------------------------------------- - -var that: React.CompositeComponent; -var node = that.refs["input"].getDOMNode(); -React.addons.TestUtils.Simulate.click(node); -React.addons.TestUtils.Simulate.change(node); -React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"}); - -interface GreetingProps { - name: string; -} -interface GreetingState { - morning: boolean; -} -interface Greeting extends React.CompositeComponent { -} -var Greeting = React.createClass({ - displayName: "Greeting", - getInitialState: function() { - return {morning: true}; - }, - render: function() { - var me = this; - return React.DOM.div( - null, - me.state.morning ? "Hello " : "Goodbye ", - me.props.name); - } -}); - -var root = React.addons.TestUtils.renderIntoDocument( - React.createElement(Greeting, {name: "John"})); -var greeting = React.addons.TestUtils - .findRenderedComponentWithType(root, Greeting); -greeting.setState({ - morning: false -}); diff --git a/react/react-addons-tests.ts b/react/react-addons-tests.ts index b07b7fd58..492fe4d81 100644 --- a/react/react-addons-tests.ts +++ b/react/react-addons-tests.ts @@ -203,7 +203,7 @@ myComponent.reset(); // Attributes // -------------------------------------------------------------------------- -var children = ["Hello world", [null], React.DOM.span(null)]; +var children: any[] = ["Hello world", [null], React.DOM.span(null)]; var divStyle = { // CSSProperties flex: "1 1 main-size", backgroundImage: "url('hello.png')" diff --git a/react/react-tests.ts b/react/react-tests.ts index 2802a34cd..1fd2670de 100644 --- a/react/react-tests.ts +++ b/react/react-tests.ts @@ -201,7 +201,7 @@ myComponent.reset(); // Attributes // -------------------------------------------------------------------------- -var children = ["Hello world", [null], React.DOM.span(null)]; +var children: any[] = ["Hello world", [null], React.DOM.span(null)]; var divStyle = { // CSSProperties flex: "1 1 main-size", backgroundImage: "url('hello.png')" diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts index 3ea8c6ed8..84f991449 100644 --- a/rx/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -150,6 +150,7 @@ declare module Rx { immediate: IScheduler; currentThread: ICurrentThreadScheduler; + default: IScheduler; // alias for Scheduler.timeout timeout: IScheduler; } diff --git a/serve-static/serve-static.d.ts b/serve-static/serve-static.d.ts index f7d7e502f..cbf9406d7 100644 --- a/serve-static/serve-static.d.ts +++ b/serve-static/serve-static.d.ts @@ -49,7 +49,7 @@ declare module "serve-static" { * By default this module will send "index.html" files in response to a request on a directory. * To disable this set false or to supply a new index pass a string or an array in preferred order. */ - index?: boolean; + index?: boolean|string|string[]; /** * Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. @@ -59,7 +59,7 @@ declare module "serve-static" { /** * Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module. */ - maxAge?: number; + maxAge?: number|string; /** * Redirect to trailing "/" when the pathname is a dir. Defaults to true. diff --git a/to-title-case-gouch/to-title-case-gouch-tests.ts b/to-title-case-gouch/to-title-case-gouch-tests.ts new file mode 100644 index 000000000..68e0a616b --- /dev/null +++ b/to-title-case-gouch/to-title-case-gouch-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +import fs = require('fs'); + +fs.readFile('to-title-case.js', 'utf-8', function(err: any, code: string) { + eval(code); + var lowerCase: string = 'this title is in lowercase and will be title case'; + console.log(lowerCase.toTitleCase()); // Now in title case. +}); diff --git a/to-title-case-gouch/to-title-case-gouch.d.ts b/to-title-case-gouch/to-title-case-gouch.d.ts new file mode 100644 index 000000000..2faa2d8d0 --- /dev/null +++ b/to-title-case-gouch/to-title-case-gouch.d.ts @@ -0,0 +1,8 @@ +// Type definitions for to-title-case +// Project: https://github.com/gouch/to-title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + toTitleCase(): string; +} diff --git a/touch-events/touch-events.d.ts b/touch-events/touch-events.d.ts index dcb4dec7d..b99a0441c 100644 --- a/touch-events/touch-events.d.ts +++ b/touch-events/touch-events.d.ts @@ -3,29 +3,4 @@ // Definitions by: Kevin Barabash // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface TouchEvent extends UIEvent { - touches: TouchList; - targetTouches: TouchList; - changedTouches: TouchList; - altKey: boolean; - metaKey: boolean; - ctrlKey: boolean; - shiftKey: boolean; -} - -interface TouchList { - length: number; - item: (index: number) => Touch; - [index: number]: Touch; -} - -interface Touch { - identifier: number; - target: EventTarget; - screenX: number; - screenY: number; - clientX: number; - clientY: number; - pageX: number; - pageY: number; -} +// DEPRECATED: use TypeScript 1.5.3 diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts index 25f174b43..dfa2c633d 100644 --- a/typescript-services/typescriptServices.d.ts +++ b/typescript-services/typescriptServices.d.ts @@ -592,12 +592,6 @@ declare module TypeScript.Collections { function createHashTable(capacity?: number, hash?: (k: TKey) => number): HashTable; function identityHashCode(value: any): number; } -declare class Enumerator { - public atEnd(): boolean; - public moveNext(): boolean; - public item(): any; - constructor(o: any); -} declare module TypeScript { var nodeMakeDirectoryTime: number; var nodeCreateBufferTime: number; diff --git a/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts index f78bf146f..9fbc45faf 100644 --- a/vinyl-fs/vinyl-fs-tests.ts +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -534,7 +534,7 @@ describe('dest stream', function () { -// This test is from +// This test is from var chmodSpy = spies.chmodSpy; @@ -909,4 +909,4 @@ describe('symlink stream', function () { stream.end(); }); }); -}); \ No newline at end of file +}); diff --git a/webaudioapi/waa-20120802.d.ts b/webaudioapi/waa-20120802.d.ts deleted file mode 100644 index a2039bf61..000000000 --- a/webaudioapi/waa-20120802.d.ts +++ /dev/null @@ -1,250 +0,0 @@ -// Type definitions for Web Audio API -// Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ -// Definitions by: Baruch Berger -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification -// Currently only implemented in WebKit browsers - -interface webkitAudioContext { - destination: AudioDestinationNode; - sampleRate: number; - currentTime: number; - listener: AudioListener; - activeSourceCount: number; - - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - createBuffer(buffer: ArrayBuffer, mixToMono: boolean): AudioBuffer; - - decodeAudioData(audioData: ArrayBuffer, successCallback: any, errorCallback?: any): void; - - createBufferSource(): AudioBufferSourceNode; - - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - - createMediaStreamSource(mediaStream: any): MediaStreamAudioSourceNode; - - createAnalyser(): RealtimeAnalyserNode; - createGainNode(): AudioGainNode; - createDelayNode(maxDelayTime?: number): DelayNode; - createBiquadFilter(): BiquadFilterNode; - createPanner():AudioPannerNode; - createConvolver(): ConvolverNode; - - createChannelSplitter(numberOfOutputs?: number):AudioChannelSplitter; - createChannelMerger(numberOfInputs?: number): AudioChannelMerger; - - createDynamicsCompressor(): DynamicsCompressorNode; - - createOscillator(): Oscillator; - createWaveTable(real: any,imag: any): WaveTable; -} - -declare var webkitAudioContext: { - - new (): webkitAudioContext; - -} - -interface Oscillator extends AudioSourceNode { - - type: number; - playbackState: number; - frequency: AudioParam; - detune: AudioParam; - noteOn(when: number): void; - noteOff(when: number): void; - setWaveTable(waveTable: WaveTable): void; - -} - -interface AudioDestinationNode extends AudioNode { - - maxNumberOfChannels: number; - numberOfChannels: number; - -} - -interface AudioNode { - - connect(destination: AudioNode, output?: number, input?: number): void; - connect(destination: AudioParam, output?: number): void; - disconnect(output?: number): void; - context: webkitAudioContext; - numberOfInputs: number; - numberOfOutputs: number; - -} - -interface AudioSourceNode extends AudioNode { - -} - - - -interface AudioParam { - - value: number; - minValue: number; - maxValue: number; - defaultValue: number; - setValueAtTime(value: number, time: number): void; - linearRampToValueAtTime(value: number, time: number): void; - exponentialRampToValueAtTime(value: number, time: number): void; - setTargetValueAtTime(targetValue: number,time: number, timeConstant: number): void; - setValueCurveAtTime(values: number[], time: number, duration: number): void; - cancelScheduledValues(startTime: number): void; - -} - -interface AudioGain extends AudioParam { - -} - -interface AudioGainNode extends AudioNode { - - gain: AudioGain; - -} - -interface DelayNode extends AudioNode { - - delayTime: AudioParam; - -} - -interface AudioBuffer { - - sampleRate: number; - length: number; - duration: number; - numberOfChannels: number; - getChannelData(channel: number): any; - -} - -interface AudioBufferSourceNode extends AudioSourceNode { - - playbackState: number; - buffer: AudioBuffer; - playbackRate: AudioParam; - loop: boolean; - noteOn(when: number): void; - noteGrainOn(when: number, grainOffset: number, grainDuration: number): void; - noteOff(when: number): void; - -} - -interface MediaElementAudioSourceNode extends AudioSourceNode { - -} - -interface JavaScriptAudioNode extends AudioNode { - - onaudioprocess: EventListener; - bufferSize: number; - -} - -interface AudioProcessingEvent extends Event { - - node: JavaScriptAudioNode; - playbackTime: number; - inputBuffer: AudioBuffer; - outputBuffer: AudioBuffer; - -} - -interface AudioPannerNode extends AudioNode { - - panningModel: number; - setPosition(x: number, y: number, z: number): void; - setOrientation(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; - distanceModel: number; - refDistance: number; - maxDistance: number; - rolloffFactor: number; - coneInnerAngle: number; - coneOuterAngle: number; - coneOuterGain: number; - distanceGain: AudioGain; - coneGain: AudioGain; - -} - -interface AudioListener { - - dopplerFactor: number; - speedOfSound: number; - setPosition(x: number, y: number, z: number): void; - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - setVelocity(x: number, y: number, z: number): void; - -} - -interface RealtimeAnalyserNode extends AudioNode { - - getFloatFrequencyData(array: any): void; - getByteFrequencyData(array: any): void; - getByteTimeDomainData(array: any): void; - fftSize: number; - frequencyBinCount: number; - minDecibels: number; - maxDecibels: number; - smoothingTimeConstant: number; - -} - -interface AudioChannelSplitter extends AudioNode { - -} - -interface AudioChannelMerger extends AudioNode { - -} - -interface DynamicsCompressorNode extends AudioNode { - - threshold: AudioParam; - knee: AudioParam; - ratio: AudioParam; - reduction: AudioParam; - attack: AudioParam; - release: AudioParam; - -} - -interface BiquadFilterNode extends AudioNode { - - type: number; - frequency: AudioParam; - Q: AudioParam; - gain: AudioParam; - - getFrequencyResponse(frequencyHz: any, magResponse: any, phaseResponse: any): void; - -} - -interface WaveShaperNode extends AudioNode { - - curve: any; - -} - -interface MediaStreamAudioSourceNode extends AudioSourceNode { - - - -} - -interface ConvolverNode extends AudioNode { - - buffer: AudioBuffer; - normalize: boolean; - -} - -interface WaveTable { - -} diff --git a/webaudioapi/waa-nightly.d.ts b/webaudioapi/waa-nightly.d.ts deleted file mode 100644 index 0d83c2533..000000000 --- a/webaudioapi/waa-nightly.d.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Type definitions for Web Audio API (nightly) -// Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ -// Definitions by: Baruch Berger -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification -// Currently only implemented in WebKit browsers (nightly builds) - -interface webkitAudioContext { - - destination: AudioDestinationNode; - sampleRate: number; - currentTime: number; - listener: AudioListener; - activeSourceCount: number; - - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - - createBuffer(buffer: ArrayBuffer, mixToMono: boolean): AudioBuffer; - - decodeAudioData(audioData: ArrayBuffer, successCallback: any, errorCallback?: any): void; - createBufferSource(): AudioBufferSourceNode; - - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; - createScriptProcessor(bufferSize: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; - createAnalyser(): AnalyserNode; - createGain(): GainNode; - createDelay(maxDelayTime?: number): DelayNode; - createBiquadFilter(): BiquadFilterNode; - createWaveShaper(): WaveShaperNode; - createPanner(): PannerNode; - createConvolver(): ConvolverNode; - createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; - createChannelMerger(numberOfInputs?: number): ChannelMergerNode; - createDynamicsCompressor(): DynamicsCompressorNode; - createOscillator(): OscillatorNode; - createWaveTable(real: any, imag: any): WaveTable; - -} - - -declare var webkitAudioContext: { - - new (value?: any): webkitAudioContext; - -} - - -interface AudioNode { - - connect(destination: AudioNode, output?: number, input?: number): void; - connect(destination: AudioParam, output?: number): void; - disconnect(output?: number): void; - context: webkitAudioContext; - numberOfInputs: number; - numberOfOutputs: number; - -} - - -interface AudioSourceNode extends AudioNode { - -} - -interface AudioDestinationNode extends AudioNode { - - maxNumberOfChannels: number; - numberOfChannels: number; - -} - -interface AudioParam { - - value: number; - computedValue: number; - minValue: number; - maxValue: number; - defaultValue: number; - setValueAtTime(value: number, startTime: number): void; - linearRampToValueAtTime(value: number, endTime: number): void; - exponentialRampToValueAtTime(value: number, endTime: number): void; - setTargetAtTime(target: number, startTime: number, timeConstant: number): void; - setValueCurveAtTime(values: any, startTime: number, duration: number): void; - cancelScheduledValues(startTime: number): void; - -} - -interface GainNode extends AudioNode { - - gain: AudioParam; - -} - -interface DelayNode extends AudioNode { - - delayTime: AudioParam; - -} - -interface AudioBuffer { - - sampleRate: number; - length: number; - duration: number; - numberOfChannels: number; - getChannelData(channel): any; - -} - -interface AudioBufferSourceNode extends AudioSourceNode { - //actually enum - playbackState: number; - - buffer: AudioBuffer; - playbackRate: AudioParam; - loop: boolean; - loopStart: number; - loopEnd: number; - start(when: number, offset?: number, duration?: number): void; - stop(when: number): void; - -} - -interface MediaElementAudioSourceNode extends AudioSourceNode { - -} - -interface ScriptProcessorNode extends AudioNode { - - onaudioproces: EventListener; - bufferSize: number; - -} - -interface AudioProcessingEvent extends Event { - - node: ScriptProcessorNode; - playbackTime: number; - inputBuffer: AudioBuffer; - outputBuffer: AudioBuffer; - -} - -interface PannerNode extends AudioNode { - //actually enum - panningModel: number; - distanceModel: number; - - setPosition(x: number, y: number, z: number): void; - setOrientation(x: number, y: number, z: number): void; - setVelocity(x: number, y: number, z: number): void; - refDistance: number; - maxDistance: number; - rolloffFactor: number; - coneInnerAngle: number; - coneOuterAngle: number; - coneOuterGain: number; - -} - -interface AudioListener { - - dopplerFactor: number; - speedOfSound: number; - setPosition(x: number, y: number, z: number): void; - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - setVelocity(x: number, y: number, z: number): void; - -} - -interface ConvolverNode extends AudioNode { - - buffer: AudioBuffer; - normalize: boolean; - -} - -interface AnalyserNode extends AudioNode { - - getFloatFrequencyData(array: any): void; - getByteFrequencyData(array: any): void; - getByteTimeDomainData(array: any): void; - fftSize: number; - frequencyBinCount: number; - minDecibels: number; - maxDecibels: number; - smoothingTimeConstant: number; - -} - -interface ChannelSplitterNode extends AudioNode { - -} - -interface ChannelMergerNode extends AudioNode { - -} - -interface DynamicsCompressorNode extends AudioNode { - - threshold: AudioParam; - knee: AudioParam; - ratio: AudioParam; - reduction: AudioParam; - attack: AudioParam; - release: AudioParam; - -} - -interface BiquadFilterNode extends AudioNode { - - //actually enum - type: number; - - frequency: AudioParam; - Q: AudioParam; - gain: AudioParam; - getFrequencyResponse(frequencyHz: any, magResponse: any, phaseResponse: any): void; - -} - -interface WaveShaperNode extends AudioNode { - - curve: any; - -} - -interface OscillatorNode extends AudioSourceNode { - - //actually enums - type: number; - playbackState: number; - - frequency: AudioParam; - detune: AudioParam; - start(when: number): void; - stop(when: number): void; - setWaveTable(waveTable: WaveTable): void; - -} - -interface WaveTable { - -} - -interface MediaStreamAudioSourceNode extends AudioSourceNode { - -} - -interface MediaStream { - -} diff --git a/webaudioapi/waa-nightly.d.ts.tscparams b/webaudioapi/waa-nightly.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/webaudioapi/waa-nightly.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index 59fab23ce..3ccc78b78 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -5,201 +5,18 @@ // // This file refers to the latest published working draft (currently from 10 october 2013) http://www.w3.org/TR/2013/WD-webaudio-20131010/, not to be confused with the latest editor's draft http://webaudio.github.io/web-audio-api/ +// DEPRECATED: use TypeScript 1.5.3 + /// -/** - * This interface represents a set of AudioNode objects and their connections. It allows for arbitrary routing of signals to the AudioDestinationNode (what the user ultimately hears). Nodes are created from the context and are then connected together. In most use cases, only a single AudioContext is used per document. An AudioContext is constructed as follows: - * - * var context = new AudioContext(); - */ -interface AudioContext extends EventTarget { - /** - * An AudioDestinationNode with a single input representing the final destination for all audio (to be rendered to the audio hardware). All AudioNodes actively rendering audio will directly or indirectly connect to destination. - */ - destination: AudioDestinationNode; - - /** - * The sample rate (in sample-frames per second) at which the AudioContext handles audio. It is assumed that all AudioNodes in the context run at this rate. In making this assumption, sample-rate converters or "varispeed" processors are not supported in real-time processing. - */ - sampleRate: number; - - /** - * This is a time in seconds which starts at zero when the context is created and increases in real-time. All scheduled times are relative to it. This is not a "transport" time which can be started, paused, and re-positioned. It is always moving forward. A GarageBand-like timeline transport system can be very easily built on top of this (in JavaScript). This time corresponds to an ever-increasing hardware timestamp. - */ - currentTime: number; - - /** - * An AudioListener which is used for 3D spatialization. - */ - listener: AudioListener; - - /** - * Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized (silent). An exception will be thrown if the numberOfChannels or sampleRate are out-of-bounds. - * @param numberOfChannels how many channels the buffer will have. An implementation must support at least 32 channels. - * @param length the size of the buffer in sample-frames. - * @param sampleRate the sample-rate of the linear PCM audio data in the buffer in sample-frames per second. An implementation must support sample-rates in at least the range 22050 to 96000. - */ - createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; - - /** - * Creates an AudioBuffer given the audio file data contained in the ArrayBuffer. The ArrayBuffer can, for example, be loaded from an XMLHttpRequest's response attribute after setting the responseType to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. - * The following steps must be performed: - * 1. Decode the encoded buffer from the AudioBuffer into linear PCM. If a decoding error is encountered due to the audio format not being recognized or supported, or because of corrupted/unexpected/inconsistent data then return NULL (and these steps will be terminated). - * 2. If mixToMono is true, then mixdown the decoded linear PCM data to mono. - * 3. Take the decoded (possibly mixed-down) linear PCM audio data, and resample it to the sample-rate of the AudioContext if it is different from the sample-rate of buffer. The final result will be stored in an AudioBuffer and returned as the result of this method. - * @param buffer the audio file data (for example from a .wav file). - * @param mixToMono if a mixdown to mono will be performed. Normally, this would not be set. - */ - createBuffer(buffer: ArrayBuffer, mixToMono: boolean): AudioBuffer; - - /** - * Asynchronously decodes the audio file data contained in the ArrayBuffer. The ArrayBuffer can, for example, be loaded from an XMLHttpRequest's response attribute after setting the responseType to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. - * The decodeAudioData() method is preferred over the createBuffer() from ArrayBuffer method because it is asynchronous and does not block the main JavaScript thread. - * - * The following steps must be performed: - * 1. Temporarily neuter the audioData ArrayBuffer in such a way that JavaScript code may not access or modify the data. - * 2. Queue a decoding operation to be performed on another thread. - * 3. The decoding thread will attempt to decode the encoded audioData into linear PCM. If a decoding error is encountered due to the audio format not being recognized or supported, or because of corrupted/unexpected/inconsistent data then the audioData neutered state will be restored to normal and the errorCallback will be scheduled to run on the main thread's event loop and these steps will be terminated. - * 4. The decoding thread will take the result, representing the decoded linear PCM audio data, and resample it to the sample-rate of the AudioContext if it is different from the sample-rate of audioData. The final result (after possibly sample-rate converting) will be stored in an AudioBuffer. - * 5. The audioData neutered state will be restored to normal - * 6. The successCallback function will be scheduled to run on the main thread's event loop given the AudioBuffer from step (4) as an argument. - * - * @param audioData an ArrayBuffer containing audio file data. - * @param successCallback callback function which will be invoked when the decoding is finished. The single argument to this callback is an AudioBuffer representing the decoded PCM audio data. - * @param errorCallback callback function which will be invoked if there is an error decoding the audio file data. - */ - decodeAudioData(audioData: ArrayBuffer, successCallback: (decodedData: AudioBuffer) => any, errorCallback?: Function): void; - - /** - * Creates an AudioBufferSourceNode. - */ - createBufferSource(): AudioBufferSourceNode; - - /** - * Creates a MediaElementAudioSourceNode given an HTMLMediaElement. As a consequence of calling this method, audio playback from the HTMLMediaElement will be re-routed into the processing graph of the AudioContext. - */ - createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; - - /** - * Creates a MediaStreamAudioSourceNode given a MediaStream. As a consequence of calling this method, audio playback from the MediaStream will be re-routed into the processing graph of the AudioContext. - */ - createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode; - - /** - * Creates a MediaStreamAudioDestinationNode. - */ - createMediaStreamDestination(): MediaStreamAudioDestinationNode; - - /** - * Creates a ScriptProcessorNode for direct audio processing using JavaScript. An exception will be thrown if bufferSize or numberOfInputChannels or numberOfOutputChannels are outside the valid range. - * It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. - * @param bufferSize the buffer size in units of sample-frames. It must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls how frequently the onaudioprocess event handler is called and how many sample-frames need to be processed each call. Lower values for bufferSize will result in a lower (better) latency. Higher values will be necessary to avoid audio breakup and glitches. The value chosen must carefully balance between latency and audio quality. - * @param numberOfInputChannels (defaults to 2) the number of channels for this node's input. Values of up to 32 must be supported. - * @param numberOfOutputChannels (defaults to 2) the number of channels for this node's output. Values of up to 32 must be supported. - */ - createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; - - /** - * Creates a AnalyserNode. - */ - createAnalyser(): AnalyserNode; - - /** - * Creates a GainNode. - */ - createGain(): GainNode; - - /** - * Creates a DelayNode representing a variable delay line. The initial default delay time will be 0 seconds. - * @param maxDelayTime the maximum delay time in seconds allowed for the delay line. If specified, this value must be greater than zero and less than three minutes or a NOT_SUPPORTED_ERR exception will be thrown. - */ - createDelay(maxDelayTime?: number): DelayNode; - - /** - * Creates a BiquadFilterNode representing a second order filter which can be configured as one of several common filter types. - */ - createBiquadFilter(): BiquadFilterNode; - - /** - * Creates a WaveShaperNode representing a non-linear distortion. - */ - createWaveShaper(): WaveShaperNode; - - /** - * Creates an PannerNode. - */ - createPanner(): PannerNode; - - /** - * Creates a ConvolverNode. - */ - createConvolver(): ConvolverNode; - - /** - * Creates an ChannelSplitterNode representing a channel splitter. An exception will be thrown for invalid parameter values. - * @param numberOfOutputs the number of outputs. Values of up to 32 must be supported. If not specified, then 6 will be used. - */ - createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; - - /** - * Creates an ChannelMergerNode representing a channel merger. An exception will be thrown for invalid parameter values. - * @param numberOfInputs the number of inputs. Values of up to 32 must be supported. If not specified, then 6 will be used. - */ - createChannelMerger(numberOfInputs?: number): ChannelMergerNode; - - /** - * Creates a DynamicsCompressorNode. - */ - createDynamicsCompressor(): DynamicsCompressorNode; - - /** - * Creates an OscillatorNode. - */ - createOscillator(): OscillatorNode; - - /** - * Creates a PeriodicWave representing a waveform containing arbitrary harmonic content. The real and imag parameters must be of type Float32Array (described in [TYPED-ARRAYS]) of equal lengths greater than zero and less than or equal to 4096 or an IndexSizeError exception must be thrown. These parameters specify the Fourier coefficients of a Fourier series representing the partials of a periodic waveform. The created PeriodicWave will be used with an OscillatorNode and will represent a normalized time-domain waveform having maximum absolute peak value of 1. Another way of saying this is that the generated waveform of an OscillatorNode will have maximum peak value at 0dBFS. Conveniently, this corresponds to the full-range of the signal values used by the Web Audio API. Because the PeriodicWave will be normalized on creation, the real and imag parameters represent relative values. - * As PeriodicWave objects maintain their own representation, any modification of the arrays uses as the real and imag parameters after the call to createPeriodicWave() will have no effect on the PeriodicWave object. - * @param real an array of cosine terms (traditionally the A terms). In audio terminology, the first element (index 0) is the DC-offset of the periodic waveform and is usually set to zero. The second element (index 1) represents the fundamental frequency. The third element represents the first overtone, and so on. - * @param imag an array of sine terms (traditionally the B terms). The first element (index 0) should be set to zero (and will be ignored) since this term does not exist in the Fourier series. The second element (index 1) represents the fundamental frequency. The third element represents the first overtone, and so on. - */ - createPeriodicWave(real: Float32Array, imag: Float32Array): PeriodicWave; -} - -declare var AudioContext: { - new (): AudioContext; -} - declare var webkitAudioContext: { new (): AudioContext; } -/** - * OfflineAudioContext is a particular type of AudioContext for rendering/mixing-down (potentially) faster than real-time. It does not render to the audio hardware, but instead renders as quickly as possible, calling a render callback function upon completion with the result provided as an AudioBuffer. It is constructed by specifying the numberOfChannels, length, and sampleRate as follows: - * - * var offlineContext = new OfflineAudioContext(unsigned long numberOfChannels, unsigned long length, float sampleRate); - */ -interface OfflineAudioContext extends AudioContext{ - startRendering(): void; - oncomplete: EventHandler; -} - -declare var OfflineAudioContext: { - new (numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} - declare var webkitOfflineAudioContext: { new (numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; } -interface OfflineAudioCompletionEvent extends Event { - /** - * An AudioBuffer containing the rendered audio data once an OfflineAudioContext has finished rendering. It will have a number of channels equal to the numberOfChannels parameter of the OfflineAudioContext constructor. - */ - renderedBuffer: AudioBuffer; -} - - declare enum ChannelCountMode { 'max', 'clamped-max', @@ -211,446 +28,6 @@ declare enum ChannelInterpretation { discrete } -/** - * AudioNodes are the building blocks of an AudioContext. This interface represents audio sources, the audio destination, and intermediate processing modules. These modules can be connected together to form processing graphs for rendering audio to the audio hardware. Each node can have inputs and/or outputs. An AudioSourceNode has no inputs and a single output. An AudioDestinationNode has one input and no outputs and represents the final destination to the audio hardware. Most processing nodes such as filters will have one input and one output. Each type of AudioNode differs in the details of how it processes or synthesizes audio. But, in general, AudioNodes will process its inputs (if it has any), and generate audio for its outputs (if it has any). - * - * An output may connect to one or more AudioNode inputs, thus fanout is supported. An input may be connected from one or more AudioNode outputs, thus fanin is supported. - * - * In order to handle this fanin, any AudioNode with inputs performs an up-mixing of all connections for each input: - * - * 1. Calculate N: the maximum number of channels of all the connections to the input. For example, if an input has a mono connection and a stereo connection then this number will be 2. - * 2. For each connection to the input, up-mix to N channels. - * 3. Mix together all the up-mixed streams from (2). This is a straight-forward mixing together of each of the corresponding channels from each connection. - * - * Please see Mixer Gain Structure for more informative details. - * - * For performance reasons, practical implementations will need to use block processing, with each AudioNode processing a fixed number of sample-frames of size block-size. In order to get uniform behavior across implementations, we will define this value explicitly. block-size is defined to be 128 sample-frames which corresponds to roughly 3ms at a sample-rate of 44.1KHz. - */ -interface AudioNode extends EventTarget { - /** - * Connects the AudioNode to another AudioNode. - * - * It is possible to connect an AudioNode output to more than one input with multiple calls to connect(). Thus, "fanout" is supported. - * - * It is possible to connect an AudioNode to another AudioNode which creates a cycle. In other words, an AudioNode may connect to another AudioNode, which in turn connects back to the first AudioNode. This is allowed only if there is at least one DelayNode in the cycle or an exception will be thrown. - * - * There can only be one connection between a given output of one specific node and a given input of another specific node. Multiple connections with the same termini are ignored. For example: - * - * nodeA.connect(nodeB); - * nodeA.connect(nodeB); - * - * will have the same effect as - * - * nodeA.connect(nodeB); - * - * @param destination the AudioNode to connect to. - * @param output an index describing which output of the AudioNode from which to connect. An out-of-bound value throws an exception. - * @param input an index describing which input of the destination AudioNode to connect to. An out-of-bound value throws an exception. - */ - connect(destination: AudioNode, output?: number, input?: number): void; - - /** - * Connects the AudioNode to an AudioParam, controlling the parameter value with an audio-rate signal. - * - * It is possible to connect an AudioNode output to more than one AudioParam with multiple calls to connect(). Thus, "fanout" is supported. - * - * It is possible to connect more than one AudioNode output to a single AudioParam with multiple calls to connect(). Thus, "fanin" is supported. - * - * An AudioParam will take the rendered audio data from any AudioNode output connected to it and convert it to mono by down-mixing if it is not already mono, then mix it together with other such outputs and finally will mix with the intrinsic parameter value (the value the AudioParam would normally have without any audio connections), including any timeline changes scheduled for the parameter. - * - * There can only be one connection between a given output of one specific node and a specific AudioParam. Multiple connections with the same termini are ignored. For example: - * - * nodeA.connect(param); - * nodeA.connect(param); - * - * will have the same effect as - * - * nodeA.connect(param); - * - * @param destination the AudioParam to connect to. - * @param output an index describing which output of the AudioNode from which to connect. An out-of-bound value throws an exception. - */ - connect(destination: AudioParam, output?: number): void; - - /** - * Disconnects an AudioNode's output. - * @param output an index describing which output of the AudioNode to disconnect. An out-of-bound value throws an exception. - */ - disconnect(output?: number): void; - - /** - * The AudioContext which owns this AudioNode. - */ - context: AudioContext; - - /** - * The number of inputs feeding into the AudioNode. This will be 0 for an AudioSourceNode. - */ - numberOfInputs: number; - - /** - * The number of outputs coming out of the AudioNode. This will be 0 for an AudioDestinationNode. - */ - numberOfOutputs: number; - - /** - * The number of channels used when up-mixing and down-mixing connections to any inputs to the node. The default value is 2 except for specific nodes where its value is specially determined. This attribute has no effect for nodes with no inputs. If this value is set to zero, the implementation MUST throw a NOT_SUPPORTED_ERR exception. - */ - channelCount: number; - - /** - * Determines how channels will be counted when up-mixing and down-mixing connections to any inputs to the node . This attribute has no effect for nodes with no inputs. - * - * See the Channel up-mixing and down-mixing section for more information on this attribute. - */ - channelCountMode: ChannelCountMode; - - /** - * Determines how individual channels will be treated when up-mixing and down-mixing connections to any inputs to the node. This attribute has no effect for nodes with no inputs. - * - * See the Channel up-mixing and down-mixing section for more information on this attribute. - */ - channelInterpretation: ChannelInterpretation; -} - - -/** - * This is an abstract interface representing an audio source, an AudioNode which has no inputs and a single output: - * - * numberOfInputs : 0 - * numberOfOutputs : 1 - * - * Subclasses of AudioSourceNode will implement specific types of audio sources. - */ -interface AudioSourceNode extends AudioNode { - -} - -/** - * This is an AudioNode representing the final audio destination and is what the user will ultimately hear. It can be considered as an audio output device which is connected to speakers. All rendered audio to be heard will be routed to this node, a "terminal" node in the AudioContext's routing graph. There is only a single AudioDestinationNode per AudioContext, provided through the destination attribute of AudioContext. - * - * numberOfInputs : 1 - * numberOfOutputs : 0 - */ -interface AudioDestinationNode extends AudioNode { - /** - * The maximum number of channels that the numberOfChannels attribute can be set to. An AudioDestinationNode representing the audio hardware end-point (the normal case) can potentially output more than 2 channels of audio if the audio hardware is multi-channel. maxNumberOfChannels is the maximum number of channels that this hardware is capable of supporting. If this value is 0, then this indicates that maxNumberOfChannels may not be changed. This will be the case for an AudioDestinationNode in an OfflineAudioContext. - * @readonly - */ - maxNumberOfChannels: number; - - /** - * The number of channels of the destination's input. This value will default to 2, and may be set to any non-zero value less than or equal to maxNumberOfChannels. An exception will be thrown if this value is not within the valid range. Giving a concrete example, if the audio hardware supports 8-channel output, then we may set numberOfChannels to 8, and render 8-channels of output. - */ - numberOfChannels: number; -} - -/** - * AudioParam controls an individual aspect of an AudioNode's functioning, such as volume. The parameter can be set immediately to a particular value using the "value" attribute. Or, value changes can be scheduled to happen at very precise times (in the coordinate system of AudioContext.currentTime), for envelopes, volume fades, LFOs, filter sweeps, grain windows, etc. In this way, arbitrary timeline-based automation curves can be set on any AudioParam. Additionally, audio signals from the outputs of AudioNodes can be connected to an AudioParam, summing with the intrinsic parameter value. - * - * Some synthesis and processing AudioNodes have AudioParams as attributes whose values must be taken into account on a per-audio-sample basis. For other AudioParams, sample-accuracy is not important and the value changes can be sampled more coarsely. Each individual AudioParam will specify that it is either an a-rate parameter which means that its values must be taken into account on a per-audio-sample basis, or it is a k-rate parameter. - * - * Implementations must use block processing, with each AudioNode processing 128 sample-frames in each block. - * - * For each 128 sample-frame block, the value of a k-rate parameter must be sampled at the time of the very first sample-frame, and that value must be used for the entire block. a-rate parameters must be sampled for each sample-frame of the block. - */ -interface AudioParam { - /** - * The parameter's floating-point value. This attribute is initialized to the defaultValue. If a value is set outside the allowable range described by minValue and maxValue no exception is thrown, because these limits are just nominal and may be exceeded. If a value is set during a time when there are any automation events scheduled then it will be ignored and no exception will be thrown. - */ - value: number; - - /** - * Nominal minimum value. This attribute is informational and value may be set lower than this value. - */ - minValue: number; - - /** - * Nominal maximum value. This attribute is informational and value may be set higher than this value. - */ - maxValue: number; - - /** - * Initial value for the value attribute - */ - defaultValue: number; - - /** - * Schedules a parameter value change at the given time. - * - * If there are no more events after this SetValue event, then for t >= startTime, v(t) = value. In other words, the value will remain constant. - * - * If the next event (having time T1) after this SetValue event is not of type LinearRampToValue or ExponentialRampToValue, then, for t: startTime <= t < T1, v(t) = value. In other words, the value will remain constant during this time interval, allowing the creation of "step" functions. - * - * If the next event after this SetValue event is of type LinearRampToValue or ExponentialRampToValue then please see details below. - * - * @param value the value the parameter will change to at the given time - * @param startTime parameter is the time in the same time coordinate system as AudioContext.currentTime. - */ - setValueAtTime(value: number, startTime: number): void; - - /** - * Schedules a linear continuous change in parameter value from the previous scheduled parameter value to the given value. - * - * The value during the time interval T0 <= t < T1 (where T0 is the time of the previous event and T1 is the endTime parameter passed into this method) will be calculated as: - * - * v(t) = V0 + (V1 - V0) * ((t - T0) / (T1 - T0)) - * - * Where V0 is the value at the time T0 and V1 is the value parameter passed into this method. - * - * If there are no more events after this LinearRampToValue event then for t >= T1, v(t) = V1 - * - * @param value the value the parameter will linearly ramp to at the given time. - * @param endTime the time in the same time coordinate system as AudioContext.currentTime. - */ - linearRampToValueAtTime(value: number, endTime: number): void; - - /** - * Schedules an exponential continuous change in parameter value from the previous scheduled parameter value to the given value. Parameters representing filter frequencies and playback rate are best changed exponentially because of the way humans perceive sound. - * - * The value during the time interval T0 <= t < T1 (where T0 is the time of the previous event and T1 is the endTime parameter passed into this method) will be calculated as: - * - * v(t) = V0 * (V1 / V0) ^ ((t - T0) / (T1 - T0)) - * - * Where V0 is the value at the time T0 and V1 is the value parameter passed into this method. - * - * If there are no more events after this ExponentialRampToValue event then for t >= T1, v(t) = V1 - * - * @param value the value the parameter will exponentially ramp to at the given time. An exception will be thrown if this value is less than or equal to 0, or if the value at the time of the previous event is less than or equal to 0. - * @param endTime the time in the same time coordinate system as AudioContext.currentTime. - */ - exponentialRampToValueAtTime(value: number, endTime: number): void; - - /** - * Start exponentially approaching the target value at the given time with a rate having the given time constant. Among other uses, this is useful for implementing the "decay" and "release" portions of an ADSR envelope. Please note that the parameter value does not immediately change to the target value at the given time, but instead gradually changes to the target value. - * - * More precisely, timeConstant is the time it takes a first-order linear continuous time-invariant system to reach the value 1 - 1/e (around 63.2%) given a step input response (transition from 0 to 1 value). - * - * During the time interval: T0 <= t < T1, where T0 is the startTime parameter and T1 represents the time of the event following this event (or infinity if there are no following events): - * - * v(t) = V1 + (V0 - V1) * exp(-(t - T0) / timeConstant) - * - * Where V0 is the initial value (the .value attribute) at T0 (the startTime parameter) and V1 is equal to the target parameter. - * - * @param target the value the parameter will start changing to at the given time. - * @param startTime the time in the same time coordinate system as AudioContext.currentTime. - * @param timeConstant the time-constant value of first-order filter (exponential) approach to the target value. The larger this value is, the slower the transition will be. - */ - setTargetValueAtTime(target: number, startTime: number, timeConstant: number): void; - - /** - * Sets an array of arbitrary parameter values starting at the given time for the given duration. The number of values will be scaled to fit into the desired duration. - * - * During the time interval: startTime <= t < startTime + duration, values will be calculated: - * - * v(t) = values[N * (t - startTime) / duration], where N is the length of the values array. - * - * After the end of the curve time interval (t >= startTime + duration), the value will remain constant at the final curve value, until there is another automation event (if any). - * - * @param values a Float32Array representing a parameter value curve. These values will apply starting at the given time and lasting for the given duration. - * @param startTime the time in the same time coordinate system as AudioContext.currentTime. - * @param duration the amount of time in seconds (after the time parameter) where values will be calculated according to the values parameter.. - * - */ - setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; - - /** - * Cancels all scheduled parameter changes with times greater than or equal to startTime. - * - * @param startTime the starting time at and after which any previously scheduled parameter changes will be cancelled. It is a time in the same time coordinate system as AudioContext.currentTime. - */ - cancelScheduledValues(startTime: number): void; -} - -/** - * Changing the gain of an audio signal is a fundamental operation in audio applications. The GainNode is one of the building blocks for creating mixers. This interface is an AudioNode with a single input and single output: - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - * - * which multiplies the input audio signal by the (possibly time-varying) gain attribute, copying the result to the output. By default, it will take the input and pass it through to the output unchanged, which represents a constant gain change of 1. - * - * As with other AudioParams, the gain parameter represents a mapping from time (in the coordinate system of AudioContext.currentTime) to floating-point value. Every PCM audio sample in the input is multiplied by the gain parameter's value for the specific time corresponding to that audio sample. This multiplied value represents the PCM audio sample for the output. - * - * The number of channels of the output will always equal the number of channels of the input, with each channel of the input being multiplied by the gain values and being copied into the corresponding channel of the output. - * - * The implementation must make gain changes to the audio stream smoothly, without introducing noticeable clicks or glitches. This process is called "de-zippering". - */ -interface GainNode extends AudioNode { - /** - * Represents the amount of gain to apply. Its default value is 1 (no gain change). The nominal minValue is 0, but may be set negative for phase inversion. The nominal maxValue is 1, but higher values are allowed (no exception thrown).This parameter is a-rate - */ - gain: AudioParam; -} - -/** - * A delay-line is a fundamental building block in audio applications. This interface is an AudioNode with a single input and single output: - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - * - * which delays the incoming audio signal by a certain amount. The default amount is 0 seconds (no delay). When the delay time is changed, the implementation must make the transition smoothly, without introducing noticeable clicks or glitches to the audio stream. - */ -interface DelayNode extends AudioNode { - /** - * An AudioParam object representing the amount of delay (in seconds) to apply. The default value (delayTime.value) is 0 (no delay). The minimum value is 0 and the maximum value is determined by the maxDelayTime argument to the AudioContext method createDelay. This parameter is k-rate - */ - delayTime: AudioParam; -} - -/** - * This interface represents a memory-resident audio asset (for one-shot sounds and other short audio clips). Its format is non-interleaved IEEE 32-bit linear PCM with a nominal range of -1 -> +1. It can contain one or more channels. It is analogous to a WebGL texture. Typically, it would be expected that the length of the PCM data would be fairly short (usually somewhat less than a minute). For longer sounds, such as music soundtracks, streaming should be used with the audio element and MediaElementAudioSourceNode. - * - * An AudioBuffer may be used by one or more AudioContexts. - */ -interface AudioBuffer { - /** - * The sample-rate for the PCM audio data in samples per second. - * @readonly - */ - sampleRate: number; - - /** - * Length of the PCM audio data in sample-frames. - * @readonly - */ - length: number; - - /** - * Duration of the PCM audio data in seconds. - * @readonly - */ - duration: number; - - /** - * The number of discrete audio channels. - * @readonly - */ - numberOfChannels: number; - - /** - * Returns the Float32Array representing the PCM audio data for the specific channel. - * - * The channel parameter is an index representing the particular channel to get data for. An index value of 0 represents the first channel. This index value MUST be less than numberOfChannels or an exception will be thrown. - */ - getChannelData(channel: number): Float32Array; - -} - -/** - * This interface represents an audio source from an in-memory audio asset in an AudioBuffer. It is useful for playing short audio assets which require a high degree of scheduling flexibility (can playback in rhythmically perfect ways). The start() method is used to schedule when sound playback will happen. The playback will stop automatically when the buffer's audio data has been completely played (if the loop attribute is false), or when the stop() method has been called and the specified time has been reached. Please see more details in the start() and stop() description. start() and stop() may not be issued multiple times for a given AudioBufferSourceNode. - * - * numberOfInputs : 0 - * numberOfOutputs : 1 - */ -interface AudioBufferSourceNode extends AudioNode { - - /** - * Represents the audio asset to be played. - */ - buffer: AudioBuffer; - - /** - * The speed at which to render the audio stream. The default playbackRate.value is 1. This parameter is a-rate - */ - playbackRate: AudioParam; - - /** - * Indicates if the audio data should play in a loop. The default value is false. - */ - loop: boolean; - - /** - * An optional value in seconds where looping should begin if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. - */ - loopStart: number; - - /** - * An optional value in seconds where looping should end if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. - */ - loopEnd: number; - - /** - * A property used to set the EventHandler for the ended event that is dispatched to AudioBufferSourceNode node types. When the playback of the buffer for an AudioBufferSourceNode is finished, an event of type Event will be dispatched to the event handler. - */ - onended: EventHandler; - - /** - * Schedules a sound to playback at an exact time. - * - * @param when time (in seconds) the sound should start playing. It is in the same time coordinate system as AudioContext.currentTime. If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing immediately. start may only be called one time and must be called before stop is called or an exception will be thrown. - * @param offset the offset time in the buffer (in seconds) where playback will begin. This parameter is optional with a default value of 0 (playing back from the beginning of the buffer). - * @param duration the duration of the portion (in seconds) to be played. This parameter is optional, with the default value equal to the total duration of the AudioBuffer minus the offset parameter. Thus if neither offset nor duration are specified then the implied duration is the total duration of the AudioBuffer. - */ - start(when?: number, offset?: number, duration?: number): void; - - /** - * Schedules a sound to stop playback at an exact time. Please see deprecation section for the old method name. - * - * The when parameter describes at what time (in seconds) the sound should stop playing. It is in the same time coordinate system as AudioContext.currentTime. If 0 is passed in for this value or if the value is less than currentTime, then the sound will stop playing immediately. stop must only be called one time and only after a call to start or stop, or an exception will be thrown. - */ - stop(when?: number): void; -} - -/* - * This interface represents an audio source from an audio or video element. - * - * numberOfInputs : 0 - * numberOfOutputs : 1 - */ -interface MediaElementAudioSourceNode extends AudioNode { -} - -interface AudioProcessingEventHandler { - (e: AudioProcessingEvent): void; -} - -/** - * This interface is an AudioNode which can generate, process, or analyse audio directly using JavaScript. - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - * - * The ScriptProcessorNode is constructed with a bufferSize which must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls how frequently the onaudioprocess event handler is called and how many sample-frames need to be processed each call. Lower numbers for bufferSize will result in a lower (better) latency. Higher numbers will be necessary to avoid audio breakup and glitches. The value chosen must carefully balance between latency and audio quality. - * - * numberOfInputChannels and numberOfOutputChannels determine the number of input and output channels. It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. - * - * var node = context.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels); - */ -interface ScriptProcessorNode extends AudioNode { - /** - * An event listener which is called periodically for audio processing. An event of type AudioProcessingEvent will be passed to the event handler. - */ - onaudioprocess: AudioProcessingEventHandler; - - /** - * The size of the buffer (in sample-frames) which needs to be processed each time onprocessaudio is called. Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384). - */ - bufferSize: number; -} - -/** - * This interface is a type of Event which is passed to the onaudioprocess event handler used by ScriptProcessorNode. - * - * The event handler processes audio from the input (if any) by accessing the audio data from the inputBuffer attribute. The audio data which is the result of the processing (or the synthesized data if there are no inputs) is then placed into the outputBuffer. - */ -interface AudioProcessingEvent extends Event { - /** - * The time when the audio will be played in the same time coordinate system as AudioContext.currentTime. playbackTime allows for very tight synchronization between processing directly in JavaScript with the other events in the context's rendering graph. - */ - playbackTime: number; - - /** - * An AudioBuffer containing the input audio data. It will have a number of channels equal to the numberOfInputChannels parameter of the createScriptProcessor() method. This AudioBuffer is only valid while in the scope of the onaudioprocess function. Its values will be meaningless outside of this scope. - */ - inputBuffer: AudioBuffer; - - /** - * An AudioBuffer where the output audio data should be written. It will have a number of channels equal to the numberOfOutputChannels parameter of the createScriptProcessor() method. Script code within the scope of the onaudioprocess function is expected to modify the Float32Array arrays representing channel data in this AudioBuffer. Any script modifications to this AudioBuffer outside of this scope will not produce any audible effects. - */ - outputBuffer: AudioBuffer; -} - declare enum PanningModelType { /** * A simple and efficient spatialization algorithm using equal-power panning. @@ -683,267 +60,6 @@ declare enum DistanceModelType { exponential } -/** - * This interface represents a processing node which positions / spatializes an incoming audio stream in three-dimensional space. The spatialization is in relation to the AudioContext's AudioListener (listener attribute). - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - * - * The audio stream from the input will be either mono or stereo, depending on the connection(s) to the input. - * - * The output of this node is hard-coded to stereo (2 channels) and currently cannot be configured. - */ -interface PannerNode extends AudioNode { - /** - * Determines which spatialization algorithm will be used to position the audio in 3D space. The default is "HRTF". - */ - panningModel: PanningModelType; - - /** - * Sets the position of the audio source relative to the listener attribute. A 3D cartesian coordinate system is used. - * - * The default value is (0,0,0) - * - * @param x the x coordinates in 3D space. - * @param y the y coordinates in 3D space. - * @param z the z coordinates in 3D space. - */ - setPosition(x: number, y: number, z: number): void; - - /** - * Describes which direction the audio source is pointing in the 3D cartesian coordinate space. Depending on how directional the sound is (controlled by the cone attributes), a sound pointing away from the listener can be very quiet or completely silent. - * - * The default value is (1,0,0) - * - * @param x - * @param y - * @param z - */ - setOrientation(x: number, y: number, z: number): void; - - /** - * Sets the velocity vector of the audio source. This vector controls both the direction of travel and the speed in 3D space. This velocity relative to the listener's velocity is used to determine how much doppler shift (pitch change) to apply. The units used for this vector is meters / second and is independent of the units used for position and orientation vectors. - * - * The default value is (0,0,0) - * - * @param x a direction vector indicating direction of travel and intensity. - * @param y - * @param z - */ - setVelocity(x: number, y: number, z: number): void; - - /** - * Determines which algorithm will be used to reduce the volume of an audio source as it moves away from the listener. The default is "inverse". - */ - distanceModel: DistanceModelType; - - /** - * A reference distance for reducing volume as source move further from the listener. The default value is 1. - */ - refDistance: number; - - /** - * The maximum distance between source and listener, after which the volume will not be reduced any further. The default value is 10000. - */ - maxDistance: number; - - /** - * Describes how quickly the volume is reduced as source moves away from listener. The default value is 1. - */ - rolloffFactor: number; - - /** - * A parameter for directional audio sources, this is an angle, inside of which there will be no volume reduction. The default value is 360. - */ - coneInnerAngle: number; - - /** - * A parameter for directional audio sources, this is an angle, outside of which the volume will be reduced to a constant value of coneOuterGain. The default value is 360. - */ - coneOuterAngle: number; - - /** - * A parameter for directional audio sources, this is the amount of volume reduction outside of the coneOuterAngle. The default value is 0. - */ - coneOuterGain: number; -} - -/** - * This interface represents the position and orientation of the person listening to the audio scene. All PannerNode objects spatialize in relation to the AudioContext's listener. See this section for more details about spatialization. - */ -interface AudioListener { - /** - * A constant used to determine the amount of pitch shift to use when rendering a doppler effect. The default value is 1. - */ - dopplerFactor: number; - - /** - * The speed of sound used for calculating doppler shift. The default value is 343.3 meters / second. - */ - speedOfSound: number; - - /** - * Sets the position of the listener in a 3D cartesian coordinate space. PannerNode objects use this position relative to individual audio sources for spatialization. - * - * The default value is (0,0,0) - * - * @param x - * @param y - * @param z - */ - setPosition(x: number, y: number, z: number): void; - - /** - * Describes which direction the listener is pointing in the 3D cartesian coordinate space. Both a front vector and an up vector are provided. In simple human terms, the front vector represents which direction the person's nose is pointing. The up vector represents the direction the top of a person's head is pointing. These values are expected to be linearly independent (at right angles to each other). For normative requirements of how these values are to be interpreted, see the spatialization section. - * - * @param x x coordinate of a front direction vector in 3D space, with the default value being 0 - * @param y y coordinate of a front direction vector in 3D space, with the default value being 0 - * @param z z coordinate of a front direction vector in 3D space, with the default value being -1 - * @param xUp x coodinate of an up direction vector in 3D space, with the default value being 0 - * @param yUp y coodinate of an up direction vector in 3D space, with the default value being 1 - * @param zUp z coodinate of an up direction vector in 3D space, with the default value being 0 - */ - setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; - - /** - * Sets the velocity vector of the listener. This vector controls both the direction of travel and the speed in 3D space. This velocity relative to an audio source's velocity is used to determine how much doppler shift (pitch change) to apply. The units used for this vector is meters / second and is independent of the units used for position and orientation vectors. - * - * @param x x coordinate of a direction vector indicating direction of travel and intensity. The default value is 0 - * @param y y coordinate of a direction vector indicating direction of travel and intensity. The default value is 0 - * @param z z coordinate of a direction vector indicating direction of travel and intensity. The default value is 0 - */ - setVelocity(x: number, y: number, z: number): void; -} - - -/** - * This interface represents a processing node which applies a linear convolution effect given an impulse response. Normative requirements for multi-channel convolution matrixing are described [here](http://www.w3.org/TR/2012/WD-webaudio-20121213/#Convolution-reverb-effect). - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - */ -interface ConvolverNode extends AudioNode { - /** - * A mono, stereo, or 4-channel AudioBuffer containing the (possibly multi-channel) impulse response used by the ConvolverNode. At the time when this attribute is set, the buffer and the state of the normalize attribute will be used to configure the ConvolverNode with this impulse response having the given normalization. - */ - buffer: AudioBuffer; - - /** - * Controls whether the impulse response from the buffer will be scaled by an equal-power normalization when the buffer atttribute is set. Its default value is true in order to achieve a more uniform output level from the convolver when loaded with diverse impulse responses. If normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. Changes to this value do not take effect until the next time the buffer attribute is set. - */ - normalize: boolean; -} - -/** - * This interface represents a node which is able to provide real-time frequency and time-domain analysis information. The audio stream will be passed un-processed from input to output. - * - * numberOfInputs : 1 - * numberOfOutputs : 1 Note that this output may be left unconnected. - */ -interface AnalyserNode extends AudioNode { - /** - * Copies the current frequency data into the passed floating-point array. If the array has fewer elements than the frequencyBinCount, the excess elements will be dropped. - * @param array where frequency-domain analysis data will be copied. - */ - getFloatFrequencyData(array: Float32Array): void; - - /** - * Copies the current frequency data into the passed unsigned byte array. If the array has fewer elements than the frequencyBinCount, the excess elements will be dropped. - * @param array where frequency-domain analysis data will be copied. - */ - getByteFrequencyData(array: Uint8Array): void; - - /** - * Copies the current time-domain (waveform) data into the passed unsigned byte array. If the array has fewer elements than the frequencyBinCount, the excess elements will be dropped. If the array has more elements than fftSize, the excess elements will be ignored. - * @param array where the time-domain sample data will be copied. - */ - getByteTimeDomainData(array: Uint8Array): void; - - /** - * The size of the FFT used for frequency-domain analysis. This must be a power of two. - */ - fftSize: number; - - /** - * Half the FFT size. - */ - frequencyBinCount: number; - - /** - * The minimum power value in the scaling range for the FFT analysis data for conversion to unsigned byte values. - */ - minDecibels: number; - - /** - * The maximum power value in the scaling range for the FFT analysis data for conversion to unsigned byte values. - */ - maxDecibels: number; - - /** - * A value from 0 -> 1 where 0 represents no time averaging with the last analysis frame. - */ - smoothingTimeConstant: number; -} - -/** - * The ChannelSplitterNode is for use in more advanced applications and would often be used in conjunction with ChannelMergerNode. - * - * numberOfInputs : 1 - * numberOfOutputs : Variable N (defaults to 6) // number of "active" (non-silent) outputs is determined by number of channels in the input - */ -interface ChannelSplitterNode extends AudioNode { -} - -/** - * The ChannelMergerNode is for use in more advanced applications and would often be used in conjunction with ChannelSplitterNode. - * - * numberOfInputs : Variable N (default to 6) // number of connected inputs may be less than this - * numberOfOutputs : 1 - */ -interface ChannelMergerNode extends AudioNode { -} - -/** - * DynamicsCompressorNode is an AudioNode processor implementing a dynamics compression effect. - * - * Dynamics compression is very commonly used in musical production and game audio. It lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is especially important in games and musical applications where large numbers of individual sounds are played simultaneous to control the overall signal level and help avoid clipping (distorting) the audio output to the speakers. - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - */ -interface DynamicsCompressorNode extends AudioNode { - /** - * The decibel value above which the compression will start taking effect. Its default value is -24, with a nominal range of -100 to 0. - */ - threshold: AudioParam; - - /** - * A decibel value representing the range above the threshold where the curve smoothly transitions to the "ratio" portion. Its default value is 30, with a nominal range of 0 to 40. - */ - knee: AudioParam; - - /** - * The amount of dB change in input for a 1 dB change in output. Its default value is 12, with a nominal range of 1 to 20. - */ - ratio: AudioParam; - - /** - * A read-only decibel value for metering purposes, representing the current amount of gain reduction that the compressor is applying to the signal. If fed no signal the value will be 0 (no gain reduction). The nominal range is -20 to 0. - */ - reduction: AudioParam; - - /** - * The amount of time (in seconds) to reduce the gain by 10dB. Its default value is 0.003, with a nominal range of 0 to 1. - */ - attack: AudioParam; - - /** - * The amount of time (in seconds) to increase the gain by 10dB. Its default value is 0.250, with a nominal range of 0 to 1. - */ - release: AudioParam; - -} - declare enum BiquadFilterType { /** * A lowpass filter allows frequencies below the cutoff frequency to pass through and attenuates frequencies above the cutoff. It implements a standard second-order resonant lowpass filter with 12dB/octave rolloff. @@ -1042,75 +158,12 @@ declare enum BiquadFilterType { allpass } -/** - * BiquadFilterNode is an AudioNode processor implementing very common low-order filters. - * - * Low-order filters are the building blocks of basic tone controls (bass, mid, treble), graphic equalizers, and more advanced filters. Multiple BiquadFilterNode filters can be combined to form more complex filters. The filter parameters such as "frequency" can be changed over time for filter sweeps, etc. Each BiquadFilterNode can be configured as one of a number of common filter types as shown in the IDL below. The default filter type is "lowpass" - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - * - * The filter types are briefly described below. We note that all of these filters are very commonly used in audio processing. In terms of implementation, they have all been derived from standard analog filter prototypes. For more technical details, we refer the reader to the excellent reference by Robert Bristow-Johnson. - * - * All parameters are k-rate with the following default parameter values: - * - * ## frequency - * 350Hz, with a nominal range of 10 to the Nyquist frequency (half the sample-rate). - * ## Q - * 1, with a nominal range of 0.0001 to 1000. - * ## gain - * 0, with a nominal range of -40 to 40. - */ -interface BiquadFilterNode extends AudioNode { - - type: BiquadFilterType; - frequency: AudioParam; - Q: AudioParam; - gain: AudioParam; - - /** - * Given the current filter parameter settings, calculates the frequency response for the specified frequencies. - * @param frequencyHz an array of frequencies at which the response values will be calculated. - * @param magResponse an output array receiving the linear magnitude response values. - * @param phaseResponse an output array receiving the phase response values in radians. - */ - getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; -} - declare enum OverSampleType { 'none', '2x', '4x' } -/** - * WaveShaperNode is an AudioNode processor implementing non-linear distortion effects. - * - * Non-linear waveshaping distortion is commonly used for both subtle non-linear warming, or more obvious distortion effects. Arbitrary non-linear shaping curves may be specified. - * - * numberOfInputs : 1 - * numberOfOutputs : 1 - */ -interface WaveShaperNode extends AudioNode { - /** - * The shaping curve used for the waveshaping effect. The input signal is nominally within the range -1 -> +1. Each input sample within this range will index into the shaping curve with a signal level of zero corresponding to the center value of the curve array. Any sample value less than -1 will correspond to the first value in the curve array. Any sample value less greater than +1 will correspond to the last value in the curve array. - */ - curve: Float32Array; - - /** - * Specifies what type of oversampling (if any) should be used when applying the shaping curve. The default value is "none", meaning the curve will be applied directly to the input samples. A value of "2x" or "4x" can improve the quality of the processing by avoiding some aliasing, with the "4x" value yielding the highest quality. For some applications, it's better to use no oversampling in order to get a very precise shaping curve. - * - * A value of "2x" or "4x" means that the following steps must be performed: - * - * 1. Up-sample the input samples to 2x or 4x the sample-rate of the AudioContext. Thus for each processing block of 128 samples, generate 256 (for 2x) or 512 (for 4x) samples. - * 2. Apply the shaping curve. - * 3. Down-sample the result back to the sample-rate of the AudioContext. Thus taking the 256 (or 512) processed samples, generating 128 as the final result. - * - * The exact up-sampling and down-sampling filters are not specified, and can be tuned for sound quality (low aliasing, etc.), low latency, and performance. - */ - oversample: OverSampleType -} - declare enum OscillatorType { sine, square, @@ -1118,90 +171,3 @@ declare enum OscillatorType { triangle, custom } - -/** - * OscillatorNode represents an audio source generating a periodic waveform. It can be set to a few commonly used waveforms. Additionally, it can be set to an arbitrary periodic waveform through the use of a PeriodicWave object. - * - * Oscillators are common foundational building blocks in audio synthesis. An OscillatorNode will start emitting sound at the time specified by the start() method. - * - * Mathematically speaking, a continuous-time periodic waveform can have very high (or infinitely high) frequency information when considered in the frequency domain. When this waveform is sampled as a discrete-time digital audio signal at a particular sample-rate, then care must be taken to discard (filter out) the high-frequency information higher than the Nyquist frequency (half the sample-rate) before converting the waveform to a digital form. If this is not done, then aliasing of higher frequencies (than the Nyquist frequency) will fold back as mirror images into frequencies lower than the Nyquist frequency. In many cases this will cause audibly objectionable artifacts. This is a basic and well understood principle of audio DSP. - * - * There are several practical approaches that an implementation may take to avoid this aliasing. But regardless of approach, the idealized discrete-time digital audio signal is well defined mathematically. The trade-off for the implementation is a matter of implementation cost (in terms of CPU usage) versus fidelity to achieving this ideal. - * - * It is expected that an implementation will take some care in achieving this ideal, but it is reasonable to consider lower-quality, less-costly approaches on lower-end hardware. - * - * Both .frequency and .detune are a-rate parameters and are used together to determine a computedFrequency value: - * - * computedFrequency(t) = frequency(t) * pow(2, detune(t) / 1200) - * - * The OscillatorNode's instantaneous phase at each time is the time integral of computedFrequency. - * - * numberOfInputs : 0 - * numberOfOutputs : 1 (mono output) - */ -interface OscillatorNode extends AudioNode { - /** - * The shape of the periodic waveform. It may directly be set to any of the type constant values except for "custom". The setPeriodicWave() method can be used to set a custom waveform, which results in this attribute being set to "custom". The default value is "sine". - */ - type: OscillatorType; - - /** - * The frequency (in Hertz) of the periodic waveform. This parameter is a-rate - * @readonly - */ - frequency: AudioParam; - - /** - * A detuning value (in Cents) which will offset the frequency by the given amount. This parameter is a-rate - */ - detune: AudioParam; // in Cents - - /** - * defined as in AudioBufferSourceNode. - */ - start(when: number): void; - - /** - * defined as in AudioBufferSourceNode. - */ - stop(when: number): void; - - /** - * Sets an arbitrary custom periodic waveform given a PeriodicWave. - */ - setPeriodicWave(periodicWave: PeriodicWave): void; - - /** - * A property used to set the EventHandler (described in HTML) for the ended event that is dispatched to OscillatorNode node types. When the playback of the buffer for an OscillatorNode is finished, an event of type Event (described in HTML) will be dispatched to the event handler. - */ - onended: EventHandler -} - -/** - * PeriodicWave represents an arbitrary periodic waveform to be used with an OscillatorNode. Please see createPeriodicWave() and setPeriodicWave() and for more details. - */ -interface PeriodicWave { -} - -/** - * This interface represents an audio source from a MediaStream. The first AudioMediaStreamTrack from the MediaStream will be used as a source of audio. - * - * numberOfInputs : 0 - * numberOfOutputs : 1 - */ -interface MediaStreamAudioSourceNode extends AudioNode { -} - -/** - * This interface is an audio destination representing a MediaStream with a single AudioMediaStreamTrack. This MediaStream is created when the node is created and is accessible via the stream attribute. This stream can be used in a similar way as a MediaStream obtained via getUserMedia(), and can, for example, be sent to a remote peer using the RTCPeerConnection addStream() method. - * - * numberOfInputs : 1 - * numberOfOutputs : 0 - * - * channelCount = 2; - * channelCountMode = "explicit"; - * channelInterpretation = "speakers"; - */ -interface MediaStreamAudioDestinationNode extends AudioNode { - stream: MediaStream; -} diff --git a/webcrypto/WebCrypto.d.ts b/webcrypto/WebCrypto.d.ts index 069f0ca25..3de5cc71e 100644 --- a/webcrypto/WebCrypto.d.ts +++ b/webcrypto/WebCrypto.d.ts @@ -3,11 +3,4 @@ // Definitions by: Lucas Dixon // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module crypto { - - // A cryptographically strong pseudo-random number generator seeded with - // truly random values. The buffer passed in is modified, and a reference to - // argument is returned for convenience. - function getRandomValues(array: ArrayBufferView) : ArrayBufferView - -} +// DEPRECATED: use TypeScript 1.5.3 diff --git a/webcrypto/readme.md b/webcrypto/readme.md deleted file mode 100644 index 420dc479f..000000000 --- a/webcrypto/readme.md +++ /dev/null @@ -1,17 +0,0 @@ -# WebCrypto Definition Notes - -## The WebCrypto specification - -The WebCrypto specification is for performing basic cryptographic operations in -web applications, such as hashing, signature generation and verification, and -encryption and decryption. The API is also for applications to generate and/or -manage the keying material necessary to perform these operations. Uses for this -API range from user or service authentication, document or code signing, and the confidentiality and integrity of communications. - -The latest version of the specification can be found at: http://www.w3.org/TR/WebCryptoAPI/ - -## Adding the reference to your project - -``` -/// -``` diff --git a/webfontloader/webfontloader-tests.ts b/webfontloader/webfontloader-tests.ts new file mode 100644 index 000000000..92711d706 --- /dev/null +++ b/webfontloader/webfontloader-tests.ts @@ -0,0 +1,30 @@ +/// +import webfontloader = require("webfontloader"); + +var config: webfontloader.Config = { + classes: false, + events: false, + loading: function() {}, + active: function() {}, + inactive: function() {}, + fontloading: function(familyName:string, fvd:string) {}, + fontactive: function(familyName:string, fvd:string) {}, + fontinactive: function(familyName:string, fvd:string) {}, + google: { + families: ['Droid Sans', 'Droid Serif:bold'], + text: 'abcdedfghijklmopqrstuvwxyz!' + }, + custom: { + families: ['My Font', 'My Other Font:n4,i4,n7'], + urls: ['/fonts.css'] + }, + fontdeck: { + id: 'xxxx' + }, + monotype: { + projectId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + version: 12345 + }, + timeout: 2000 +} +webfontloader.load(config); \ No newline at end of file diff --git a/webfontloader/webfontloader-tests.ts.tscparams b/webfontloader/webfontloader-tests.ts.tscparams new file mode 100644 index 000000000..4169d3605 --- /dev/null +++ b/webfontloader/webfontloader-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --target es5 \ No newline at end of file diff --git a/webfontloader/webfontloader.d.ts b/webfontloader/webfontloader.d.ts new file mode 100644 index 000000000..0afadfd3b --- /dev/null +++ b/webfontloader/webfontloader.d.ts @@ -0,0 +1,60 @@ +// Type definitions for typekit-webfontloader 1.6.4 +// Project: https://github.com/typekit/webfontloader +// Definitions by: doskallemaskin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module WebFont { + export function load(config:WebFont.Config):void; + export interface Config { + /** Setting this to false will disable html classes (defaults to true) */ + classes?:boolean; + /** Settings this to false will disable callbacks/events (defaults to true) */ + events?:boolean; + /** Time (in ms) until the fontinactive callback will be triggered (defaults to 5000) */ + timeout?:number; + /** This event is triggered when all fonts have been requested. */ + loading?():void; + /** This event is triggered when the fonts have rendered. */ + active?():void; + /** This event is triggered when the browser does not support linked fonts or if none of the fonts could be loaded. */ + inactive?():void; + /** This event is triggered once for each font that's loaded. */ + fontloading?(familyName:string, fvd:string):void; + /** This event is triggered once for each font that renders. */ + fontactive?(familyName:string, fvd:string):void; + /** This event is triggered if the font can't be loaded. */ + fontinactive?(familyName:string, fvd:string):void; + + /** Child window or iframes to manage fonts for */ + context?:Array; + + custom?:Custom; + google?:Google; + typekit?:Typekit; + fontdeck?:Fontdeck; + monotype?:Monotype; + } + export interface Google { + families?:Array; + text: string; + } + export interface Typekit { + id?:Array; + } + export interface Custom { + families?:Array; + urls?:Array; + testStrings?:{[fontFamily:string]:string}; + } + export interface Fontdeck { + id?:string; + } + export interface Monotype { + projectId?:string; + version?:number; + } + +} +declare module "webfontloader" { + export = WebFont; +} \ No newline at end of file

): CompositeComponent; - findRenderedComponentWithType>( - tree: Component, type: ComponentClass): C; - } - - interface SyntheticEventData { - altKey?: boolean; - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - changedTouches?: TouchList; - charCode?: boolean; - clipboardData?: DataTransfer; - ctrlKey?: boolean; - deltaMode?: number; - deltaX?: number; - deltaY?: number; - deltaZ?: number; - detail?: number; - getModifierState?(key: string): boolean; - key?: string; - keyCode?: number; - locale?: string; - location?: number; - metaKey?: boolean; - pageX?: number; - pageY?: number; - relatedTarget?: EventTarget; - repeat?: boolean; - screenX?: number; - screenY?: number; - shiftKey?: boolean; - targetTouches?: TouchList; - touches?: TouchList; - view?: AbstractView; - which?: number; - } - - interface EventSimulator { - (element: Element, eventData?: SyntheticEventData): void; - (descriptor: Component, eventData?: SyntheticEventData): void; - } - - interface Simulate { - blur: EventSimulator; - change: EventSimulator; - click: EventSimulator; - cut: EventSimulator; - doubleClick: EventSimulator; - drag: EventSimulator; - dragEnd: EventSimulator; - dragEnter: EventSimulator; - dragExit: EventSimulator; - dragLeave: EventSimulator; - dragOver: EventSimulator; - dragStart: EventSimulator; - drop: EventSimulator; - focus: EventSimulator; - input: EventSimulator; - keyDown: EventSimulator; - keyPress: EventSimulator; - keyUp: EventSimulator; - mouseDown: EventSimulator; - mouseEnter: EventSimulator; - mouseLeave: EventSimulator; - mouseMove: EventSimulator; - mouseOut: EventSimulator; - mouseOver: EventSimulator; - mouseUp: EventSimulator; - paste: EventSimulator; - scroll: EventSimulator; - submit: EventSimulator; - touchCancel: EventSimulator; - touchEnd: EventSimulator; - touchMove: EventSimulator; - touchStart: EventSimulator; - wheel: EventSimulator; - } - - // - // react Exports - // ---------------------------------------------------------------------- - - interface Exports extends TopLevelAPI { - DOM: ReactDOM; - PropTypes: ReactPropTypes; - Children: ReactChildren; - } - - // - // react/addons Exports - // ---------------------------------------------------------------------- - - interface AddonsExports extends Exports { - addons: { - CSSTransitionGroup: CSSTransitionGroup; - LinkedStateMixin: LinkedStateMixin; - PureRenderMixin: PureRenderMixin; - TransitionGroup: TransitionGroup; - - batchedUpdates(callback: (a: A, b: B) => any, a: A, b: B): void; - batchedUpdates(callback: (a: A) => any, a: A): void; - batchedUpdates(callback: () => any): void; - - classSet(cx: ClassSet): string; - cloneWithProps