From a4b7732937f1eebd5902a7d6fc2fd164d8574d67 Mon Sep 17 00:00:00 2001 From: flashandy Date: Sat, 17 Jan 2015 12:10:10 +0100 Subject: [PATCH 001/416] Update underscore.d.ts missing declaration for wrapped.pick --- underscore/underscore.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 8cf92df12..2b3818c3e 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -3020,6 +3020,7 @@ interface _Chain { * @see _.pick **/ pick(...keys: string[]): _Chain; + pick(keys: string[]): _Chain; pick(fn: (value: any, key: any, object: any) => any): _Chain; /** From d2ed7b747941ff02d923a97119cd24caac4516eb Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 14 Apr 2015 08:51:08 +0900 Subject: [PATCH 002/416] bump tsc version 1.4.1 to 1.5.0-alpha --- npm-shrinkwrap.json | 172 ++++++++++++++++++++++++++++++-------------- package.json | 2 +- 2 files changed, 118 insertions(+), 56 deletions(-) diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index 738ac2834..04fa1a957 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.24", + "from": "bluebird@>=2.5.3 <3.0.0", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.24.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.12.0", + "from": "hoek@>=2.2.0 <3.0.0", + "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.12.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.2", + "from": "moment@>=2.0.0 <3.0.0", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.10.2.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.4", + "from": "minimatch@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.4.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.1", + "from": "once@>=1.3.0 <2.0.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.3.1.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.4", + "from": "minimatch@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.4.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": { @@ -133,12 +195,12 @@ }, "once": { "version": "1.3.1", - "from": "once@^1.3.0", + "from": "once@>=1.3.0 <2.0.0", "resolved": "https://registry.npmjs.org/once/-/once-1.3.1.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.7", + "from": "through@>=2.2.7 <3.0.0", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.7.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", + "from": "wordwrap@>=0.0.2 <0.1.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.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.0-alpha", + "from": "typescript@1.5.0-alpha", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.5.0-alpha.tgz" } } } diff --git a/package.json b/package.json index 10d5c872a..2630763e6 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,6 @@ }, "devDependencies": { "definition-tester": "0.2.0", - "typescript": "1.4.1" + "typescript": "1.5.0-alpha" } } From 523dc9d4831c6ce242127e4a7c1380ecc906a659 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:23:21 +0900 Subject: [PATCH 003/416] fix react/react-tests.ts and react/react-addons-tests.ts compile error --- react/react-addons-tests.ts | 2 +- react/react-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/react/react-addons-tests.ts b/react/react-addons-tests.ts index 72d6db486..f2ebdef37 100644 --- a/react/react-addons-tests.ts +++ b/react/react-addons-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/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')" From 25407fa708d034e5c420dc2e9a994810501a7512 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:25:52 +0900 Subject: [PATCH 004/416] fix react/legacy/react-0.12-tests.ts compile error --- react/legacy/react-0.12-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/legacy/react-0.12-tests.ts b/react/legacy/react-0.12-tests.ts index 27eae4c64..98faad646 100644 --- a/react/legacy/react-0.12-tests.ts +++ b/react/legacy/react-0.12-tests.ts @@ -121,7 +121,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')" From ffa4719d92d613669e9afbe792527d0b21e39b03 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:29:38 +0900 Subject: [PATCH 005/416] fix passport-local/passport-local-tests.ts compile error --- passport-local/passport-local-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/passport-local/passport-local-tests.ts b/passport-local/passport-local-tests.ts index de799a4d8..c58772eaa 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); From 8d7f10e0304131e1526801977f69e836c5f1b305 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:32:15 +0900 Subject: [PATCH 006/416] fix microsoft-ajax/microsoft.ajax-tests.ts compile error --- microsoft-ajax/microsoft.ajax-tests.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) 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() { From b79d800626c9e98914c82aa095e76857fd8b4c68 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:35:12 +0900 Subject: [PATCH 007/416] fix jqueryui/jqueryui-tests.ts compile error --- jqueryui/jqueryui-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 +} From 23d8d30144ccd79f5e8625db65ecffe5a25d9af8 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 15 Apr 2015 23:36:46 +0900 Subject: [PATCH 008/416] fix hooker/hooker-tests.ts compile error --- hooker/hooker-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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', () => { From ad1887a3d3352ce5fefb81b1da2a0074b6bdf126 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Thu, 16 Apr 2015 09:25:35 +1000 Subject: [PATCH 009/416] fix acl/acl-mongodbBackend.d.ts compile error --- acl/acl.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 5d0498fed..121541cad 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -14,7 +14,7 @@ declare module "acl" { type Value = string|number; type Values = Value|Value[]; type Action = () => any; - type Callback = (err: Error) => any; + export type Callback = (err: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; @@ -84,7 +84,7 @@ declare module "acl" { // // For internal use // - interface Backend { + export interface Backend { begin: () => T; end: (transaction: T, cb?: Action) => void; clean: (cb?: Action) => void; From c9d2949f7e20b5e6532b89b3f65df23c598a24e4 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Thu, 16 Apr 2015 09:27:56 +1000 Subject: [PATCH 010/416] fix acl/acl-redisBackend compile error --- acl/acl-redisBackend.d.ts | 2 +- acl/acl.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/acl/acl-redisBackend.d.ts b/acl/acl-redisBackend.d.ts index e199f8b81..2f222e252 100644 --- a/acl/acl-redisBackend.d.ts +++ b/acl/acl-redisBackend.d.ts @@ -9,7 +9,7 @@ declare module "acl" { import redis = require('redis'); - interface AclStatic { + export interface AclStatic { redisBackend: RedisBackendStatic; } diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 121541cad..ded8be22b 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -19,7 +19,7 @@ declare module "acl" { type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; - interface AclStatic { + export interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; new (backend: Backend, logger: Logger): Acl; new (backend: Backend): Acl; From 316a02d99ee5445daeabd51e883d646c5979437f Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Thu, 16 Apr 2015 10:00:42 +1000 Subject: [PATCH 011/416] tests: revert my ugly hacks. See https://github.com/Microsoft/TypeScript/issues/2784 --- acl/acl-redisBackend.d.ts | 2 +- acl/acl.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/acl/acl-redisBackend.d.ts b/acl/acl-redisBackend.d.ts index 2f222e252..e199f8b81 100644 --- a/acl/acl-redisBackend.d.ts +++ b/acl/acl-redisBackend.d.ts @@ -9,7 +9,7 @@ declare module "acl" { import redis = require('redis'); - export interface AclStatic { + interface AclStatic { redisBackend: RedisBackendStatic; } diff --git a/acl/acl.d.ts b/acl/acl.d.ts index ded8be22b..5d0498fed 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -14,12 +14,12 @@ declare module "acl" { type Value = string|number; type Values = Value|Value[]; type Action = () => any; - export type Callback = (err: Error) => any; + type Callback = (err: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; - export interface AclStatic { + interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; new (backend: Backend, logger: Logger): Acl; new (backend: Backend): Acl; @@ -84,7 +84,7 @@ declare module "acl" { // // For internal use // - export interface Backend { + interface Backend { begin: () => T; end: (transaction: T, cb?: Action) => void; clean: (cb?: Action) => void; From 7faade2b2301cea8758b3bb2a488f771748c584d Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 29 Apr 2015 11:15:25 +0900 Subject: [PATCH 012/416] suppress `Octal literals are not available when targeting ECMAScript 5 and higher.` --- emscripten/emscripten-tests.ts | 2 +- gulp-concat/gulp-concat-tests.ts | 2 +- jquery.pickadate/jquery.pickadate-tests.ts | 4 ++-- mock-fs/mock-fs-tests.ts | 2 +- vinyl-fs/vinyl-fs-tests.ts | 8 ++++---- 5 files changed, 9 insertions(+), 9 deletions(-) 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/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/jquery.pickadate/jquery.pickadate-tests.ts b/jquery.pickadate/jquery.pickadate-tests.ts index fde52f3e3..89c250cf8 100644 --- a/jquery.pickadate/jquery.pickadate-tests.ts +++ b/jquery.pickadate/jquery.pickadate-tests.ts @@ -282,7 +282,7 @@ picker.set('disable', undefined); picker.set('select', [2013, 3, 20]); // Using JavaScript Date objects. -picker.set('select', new Date(2013,03,20)); +picker.set('select', new Date(2013, 3, 20)); // Using positive integers as UNIX timestamps. picker.set('select', 1365961912346); @@ -417,4 +417,4 @@ picker.on('open', function () { picker.trigger('open'); picker.$node; -picker.$root; \ No newline at end of file +picker.$root; 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/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts index 016da5e8b..335254f79 100644 --- a/vinyl-fs/vinyl-fs-tests.ts +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -227,7 +227,7 @@ var dataWrap = function(fn:any) { }; var realMode = function(n:any) { - return n & 07777; + return n & parseInt("07777", 8); }; describe('dest stream', function() { @@ -370,7 +370,7 @@ describe('dest stream', function() { var expectedContents = fs.readFileSync(inputPath); var expectedCwd = __dirname; var expectedBase = path.join(__dirname, "./out-fixtures"); - var expectedMode = 0655; + var expectedMode = parseInt("0655", 8); var expectedFile = new File({ base: inputBase, @@ -410,7 +410,7 @@ describe('dest stream', function() { var expectedContents = fs.readFileSync(inputPath); var expectedCwd = __dirname; var expectedBase = path.join(__dirname, "./out-fixtures"); - var expectedMode = 0655; + var expectedMode = parseInt("0655", 8); var contentStream = through.obj(); var expectedFile = new File({ @@ -454,7 +454,7 @@ describe('dest stream', function() { var expectedPath = path.join(__dirname, "./out-fixtures/test"); var expectedCwd = __dirname; var expectedBase = path.join(__dirname, "./out-fixtures"); - var expectedMode = 0655; + var expectedMode = parseInt("0655", 8); var expectedFile = new File({ base: inputBase, From 6d64be2b2844adc0f4ea0f128b41faad98a1c96d Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 29 Apr 2015 12:03:44 +0900 Subject: [PATCH 013/416] merge acl-mongodbBackend.d.ts and acl-redisBackend.d.ts into acl.d.ts --- acl/acl-mongodbBackend-tests.ts | 3 +-- acl/acl-mongodbBackend.d.ts | 22 ---------------------- acl/acl-redisBackend-test.ts | 2 +- acl/acl-redisBackend.d.ts | 21 --------------------- acl/acl.d.ts | 30 ++++++++++++++++++++++++++++++ 5 files changed, 32 insertions(+), 46 deletions(-) delete mode 100644 acl/acl-mongodbBackend.d.ts delete mode 100644 acl/acl-redisBackend.d.ts 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 = _; } From 609e8e45ca5017c0db5c2513ed9ad52798c4ed1c Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 1 May 2015 12:22:00 +0900 Subject: [PATCH 014/416] update typescript version 1.5.0-alpha to 1.5.0-beta --- npm-shrinkwrap.json | 18 +++++++++--------- package.json | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index 04fa1a957..d3f7dc16e 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -8,9 +8,9 @@ "resolved": "https://registry.npmjs.org/definition-tester/-/definition-tester-0.2.0.tgz", "dependencies": { "bluebird": { - "version": "2.9.24", + "version": "2.9.25", "from": "bluebird@>=2.5.3 <3.0.0", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.24.tgz" + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.25.tgz" }, "definition-header": { "version": "0.1.0", @@ -103,9 +103,9 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "minimatch": { - "version": "2.0.4", + "version": "2.0.7", "from": "minimatch@>=2.0.1 <3.0.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.4.tgz", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.7.tgz", "dependencies": { "brace-expansion": { "version": "1.1.0", @@ -170,9 +170,9 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" }, "minimatch": { - "version": "2.0.4", + "version": "2.0.7", "from": "minimatch@>=2.0.1 <3.0.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.4.tgz", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.7.tgz", "dependencies": { "brace-expansion": { "version": "1.1.0", @@ -305,9 +305,9 @@ } }, "typescript": { - "version": "1.5.0-alpha", - "from": "typescript@1.5.0-alpha", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.5.0-alpha.tgz" + "version": "1.5.0-beta", + "from": "typescript@1.5.0-beta", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-1.5.0-beta.tgz" } } } diff --git a/package.json b/package.json index 2630763e6..d2826fc15 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,6 @@ }, "devDependencies": { "definition-tester": "0.2.0", - "typescript": "1.5.0-alpha" + "typescript": "1.5.0-beta" } } From c3fce999444a0af7376a1317da93eb15ddd07ee2 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 8 May 2015 14:19:01 -0700 Subject: [PATCH 015/416] Added typings and tests for core-js --- core-js/core-js-tests.ts | Bin 0 -> 45732 bytes core-js/core-js-tests.ts.tscparams | Bin 0 -> 94 bytes core-js/core-js.d.ts | 3037 ++++++++++++++++++++++++++++ 3 files changed, 3037 insertions(+) create mode 100644 core-js/core-js-tests.ts create mode 100644 core-js/core-js-tests.ts.tscparams create mode 100644 core-js/core-js.d.ts diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b9f6f9d7c63ced3b95e8f3b50ae2ea81e9fae29 GIT binary patch literal 45732 zcmd^Idv6=Z5x>6+^g9SiQOH23v<;8|jblKFlvYV?3s%|`FpNfTGt~>E5=Sob)!WYR zhQpcJ+ZV|bB{C2!i@e==@67D%y!|8O}cSwoeomk7qTl{f0rit+hx(rqTwuN;+Q#%b#QHu1AJkt^-&^W;*tR<) zICstGEp~Y_Zl8>))u`p?Ja|5gV6c#n+UG|kjq4U0aCi)7ZHvw33DNNdNp++7sg>PH z(C)fz_mZUd15tfU6nQwK_W3J%cHZogTyBErW8&?yZNqY5RPacpcHxQSkJn zwGD2wGx^)o@NdG-I^Ay}+|cI{QF_;W(?0R7Z(2TKJFpGaU8>b5q-Ea{R^VG7621}9 zcGtWl+g6yq-|Oa0Wj|o>eeq4H|3NEjmN0r-iI@7uCC4;CE1^tF@U~m4Mt`>NQu_mA z>)Q7<@t|YiqbamESy}vz#tdu%x=>i#Qyt0krxV(q1zH&rPFT<(Sv^K%SEqYHi>F5C zHP9@#-dehlyE4!oZ)oItOU%=*J;lOe__P%yuAk7Sj8P%pwxhW$y|BkD(hU0o+Y96G zm3r8swr0)hXQuTj*_DkJp8xrHx75_pU@0i+H{<~PTkERBXh+#R7*)#pR~_cp#=iQI z_BHuyjutALl(t`xg`)L5JX(Wm$3lfckUb8*Gm{tCB!Vy7_Ws^rsQ|z0U^n5 z+>s}imJqYF@x3Kl%2Nv=M*j`rzb4JWLQWgWH#|&m#aa#9S?D2sHIRkcGW0U-C7SDL z^^oE;T4;5&X;$aqccp7#BOA?27SR4dIvl#OE1G&boh^k>PN)ZFNnL7oCQmFKb-hJa zF$gg!SsFAhXm9WTF>mC#`G?J_{wNQ-&6nhZwkZcvzq-+U+Ind_i`{5`Pvh?^$`nz9 zxFy|O(_aebIek8%r^x?#Hje*4rCP+bnG0``&l}UvkY>ME4g6ZX75qT@DSX6jGa%m$ zuYov#xhrN|1N!@{?WvS)5ElOv#|bzC!t3Wx()KLie2eHmB#(t^4D92?@X~Gjw&i<3 zd|$N~&;u2iEhE8IwWSYR9w6@o*RY@TqpX+WKdYnDZtY zd6eh0*U$>l7RjEo1M3m&a~bn8R_!xXM{meG44QXjo2Z$>LQ{~==;;OhT4hOK3`$M)i0Z36x`vZ+SMHB-#&V29 zNI|P-47A)isBn=O}I(5F3}*?`yI(jYJ6k*V7he7r=E+|FD**{I9mXf)B|6u%<0q-=A90 zHc1ANP)4d`<7ge~X_I6Kt;So61xSqTww5^nU|Y?m@LS!Lp&k$?vTCj4=F5qlE5{o5 zg=eA5L*NngJz38Y$?f||J|%5O#KRfc@FCgEc=BvrtfuVc?Aj80In-Z~S*Z-t9?q^a zu}$)9encJtH4#)%t@rTl*(y*uIiA>KIFc_rw5-o4wvykXoe%poXWpYq?@L+>@bhWk z5;Oj<+7ZpULTt=+dtgq0yb*qJ6!jC`J}*f6FDly}P+RQDN#hak_Rr>D#QQdJ zwM&2P5zcSvufNd0SHavT?2ESZ^+kq1B1xVS)(f&z*gX84c#=4^+Kc&|uZQ=%f=R|5 z#?eLdzWJp2laqb7-H@tns4sT?V7IMQ7_GH*TR{@%%^#aT6fkqU5`6;grT~p2^(EoW zQ-_#0CeM^_1x~Mut&mHUTVYpN4Ng?IYOun}YVf{otGB4)*60?|lB>{p$#B&OEl&zE zJf=vAOv}R4c(B?&xEvF0?Q&cd2kkzob&(VJkQ|Bm3+p9_?>5u=mTdccS}*Z^u>;e$ z#?C>Ga}1qlq*nGdE!1PDpdh}^_>^m&cn5u2(IYUN1rgbK) z7#+8<=YZxa$fOTxY)b8^3_~hGoN1NXb2fEMzOmGjb9&^&Sd%HWMifOft${plXMxAW zKW3k0$Tt+(1GLi&y>>{vN^KCA`?TY^#Miy!9}Y2463<RK5S?KL6!KP+2L>{+`|VYb~#;9^@eAD$U|U1CvA+i`rjhEg;zOf$1{AuDOrTbBi3?6 zZDCvN5w)%2UiYj8(FChAyvLq*Bh+OthzmDvo(|b_{ZMLzvY%=|{zO`bvvqC5{nthI z;Dfp5xfw@0wJ~{y5f1so25q(>&p8j-CHWyzZqmG>S0e> zPl&Y_oKE>=IwrJ|%$`zkvd6X5NTiV#9Hndve&XS!p1_db_35S4#6Ug6t&`>k-$FLJ8I7DhzPizxqJqbIy;%FnD^tv$ym zjzcI((aMc$59^+Z>`nbK&r9pF5F6z%KNg?PFkthNi|Cvq-;Se>?Ky6J7`}mik7(X> zLRr%#{jc~qhQP|#L0jM>X->@Nf<`D~5VLH2<3wM?Ak_e%S68laht+q4pyaq47Q?(6_CsUiB}Q z4f~bFB%XrVkGzG#`Q;s_uWuR4IVhIv6?tdmfO0Bo7Hsf*a@wXGqp>R=`=8Qtvee8g ze2K&?}v3C-@F)fkLeBZj@7GMT65H@lfd@%|caNPm`pt(yN2hYVT&&hsm=nhpQF{!1FU~oG)MA~W4_e4u(;!6-M60&V$9p!FBYpQPxh zoW8)g#W!;Ax2~A@cD8=-BvHNdF?(55r8W6@>5S|9q3IPH*d%+%(Xvez!}sXKH16#W zH>mM_M5$HsvS(=+7}y8Sc9504VR4ctxWS zw}J2}8s$5E2L@tUtjB8a@&)IIZ9cp~w=h@^;dO85=Yq~JZW8B+@_c$teV4WNZQ5CM zH?^b`Oq{d#cZVo!@rYfhj9aW!_KAn|Vh36Iz=<`1R9@LoP|C)g~V}2 zPlY1B0FIuT&e2tZGMs945h(sNW*DRPCOgM)a{|tAB95>{v9Awxjh(@I=9N!k=}FR* z^~o6#k&d^kx?ZgF*>T|%u*at-QbX=?=Vy1w%EPm% zq1JZ^4}RUAz~&arc}YgdhfdpB-4)T~DPzxVDNAw1yO7b6CCzs4t-r3XjJA3Dsy~&u zRpOrMPFt9#LbHa|&H-}S(r3kcQ9h$nHEN+aVS~Fax_1Sloj>~nUk{1GpLL&Jkd5Q4 zSh~f?v`}5d?>_|mYZ_aUO=JBCx1KBI7LRYq-grRmai4+QzOEy1(C%FieX`z?2;3M| zfP=dVaee@;kzb*DQbW6(qhPA>zB`OYwnv<=w^GFUP2o>kDvs5*Rq!F6Lv`n8on0HW zl_$tdeYxD1fEy0^Zm{?>u|}LQ00hmfECjL0ZYxi#&20Rw5B}VS#x&pGp4v&n3Qtcd zG(_-A;-Y)c{H&RWk18Sy1|I=FWPcQg2LrBxJ+aji@FPm)FGa~??^19G%9e1Va|--XCCXI=?N!v&=& zn1WMAsipS^vN%NUJY@BHDI8t8C7dJhS@J(Aa+|DD(dgv-q)i}P>Pl7)- zg86Q)vNd>!{!e942hr%?d07Atb2wq}>I zPf(dY|HwQD_pnEgvPyK9MhlSIlR&Vp-yGBdc1jBxcp zTnET=rems0Gq2m>4zm=^?1RwL-zpHxvILrDS+m1U(GjOTzdyzMPkfTPc3fgxG$VoC z%9ekGsMNZ(Kk4b$L$t?g%USt&K@v&bK`egF>I16=W18)&6ye##4y9&hpYxrfn9pM# z>(`*w?{U2F{p?PaaBV_y=3!tShe)69ud-Neo$}cEvehT=I>rwEen$^R1=ioOr};En zJJ<2U?>$);DJvhjk;6P=WN>8T-!e-0DY6&5U#8Rw8IHUILDzc(2Hs6RjyzX7*TJgg zUF&_@v%J||rIm{W-PWruTje@u%b|Z2DfoHWYqG*Oll`%^J%%&);Jqq>Cr$}R60Gsz zUhN$kA9(lLCe>c}FHg6ON&D2U6?fq%cd@?vG^UaJ%RF#V{Mx^ZSK_m@;n*ynY+SCH zEvG2oGP45AUr(}ftizPvn z-QCy4p_&d?Z_@I}uQG8>jcW(7F%DS@Y_t*z{8g*)_|XDBxw5owoQC6eeL0PJka})IkL%YW<5mwF zTCU}WtCHQQs%!A8L$lrG@K~uE$qg{&bZz%TTOxR$?0==)xNovRfOEi&i!!= zjy%`+MmUe_E|h?-t8u&ShUbFS|7vSW`N&m5<&4Fdk$_h3*VB4;S{ubm64wYYr^b6l5#7&ww_3ab z6=ysLQEaNEoV5xJZT)MoO<8#r?&Uq-tS@;}rB)sD?f>3qoXu)`oJi!IJlgZuV81E>U)SSoF!fZWg?E$K9B_ZS4pXy_rzYD`8vNcU zzn@?89BuD8k~ooiu9;t|MGe=0^4K_E-yF~Ga_u{lv*$|GC*-_|?SVBx|L#bIvHE^R zd8>P;B72iz=Z)ws`|v8tqV*6nXcP{_y{ahBkcW?2ep^=(`-HJnAZ-2RnvwCD6LK($oc5;L}Z>vfS4 t+cowI;?yASce5t8axkfurxuLq_B8JQ3`EgC3JbW*0F;b@k_drFg1{6k51bH%3%`HQZ5WltKw)ELChDACdeNzx aN+WTqW=YgnKC3Jo|Hc{FnY3_8mIq$Ba}rDd literal 0 HcmV?d00001 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; +} From b29697846d7c2469b63a5ae4e2ba5cb968aa8d4c Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Mon, 11 May 2015 09:19:22 -0400 Subject: [PATCH 016/416] Adding missing property & other minor changes * the `permissionLevel` property was missing * `needsPermission` and `isSupported` are properties, not functions * Spelling fixes in comments --- notifyjs/notifyjs.d.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index 0cff4e0c5..5fe321efa 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -10,20 +10,25 @@ declare var Notify: { * Check is permission is needed for the user to receive notifications. * @return true : needs permission, false : does not need */ - needsPermission() : boolean; + needsPermission : boolean; /** * Asks the user for permission to display notifications - * @param onPermissionGrantedCallback A callback for permmision is granted. - * @param onPermissionDeniedCallback A callback for permmision is denied. + * @param onPermissionGrantedCallback A callback for permission is granted. + * @param onPermissionDeniedCallback A callback for permission is denied. */ requestPermission(onPermissionGrantedCallback?: ()=> any, onPermissionDeniedCallback? : ()=> any) : void; /** * return true if the browser supports HTML5 Notification - * @param true : the browser supports HTML5 Notification, false ; the browswer does not supports HTML5 Notification. + * @param true : the browser supports HTML5 Notification, false ; the browser does not supports HTML5 Notification. */ - isSupported() : boolean; + isSupported: boolean; + + /** + * shows the user's current permission level (granted, denied or default), returns null if notifications are not supported. + */ + permissionLevel: string; } declare module notifyjs { From 139d9e9386d4501cb9768ad8c8942079a1a0861e Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 11 May 2015 08:18:16 -0700 Subject: [PATCH 017/416] Update core-js-tests.ts --- core-js/core-js-tests.ts | Bin 45732 -> 22819 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts index 4b9f6f9d7c63ced3b95e8f3b50ae2ea81e9fae29..8a4ec2c0b83c0c1c1299584a6cdeb8fa9eecc456 100644 GIT binary patch literal 22819 zcmc&+{camK693-7DO0hC?p7q-4n-dqvTD$(iBIaAr6hlKStz|FgThn>?@7L{+L7sbrotH!r>! zm6aNPsMB%U)ZZk#FSob0xALM<)g%MVd5OQ1-;*!V@{p9TGgBmsRUF|1t)%DSrxqR2RGYoS(yDF#BqV|)cswyk_9A^z$4)I@U_^2T1 zc~#C;)!hE947YRA2s-G00?AE#V`LrUM}`$*s3p~dX>UogXl@oulf z94NG$cHs^RNCJI#+b>w_+5lpQ3sB z$k7?LxOdF7ffJhxhK`tCi{f}eglngFIr9$C(n)tHOuDv2|l0eS(j0b6t%*57pn1X`LoJC0%bq>MgO6Dt*aPh z0t2oF3yAz_;`k1I_+vQTYMJ=d>&t;m7%?v1AVM;WOrR6IU%j%aR7+_{-g5 z|Jz$w&A)xhe|UtWS0@J-Y^%xlW{FMyoV;EXqb4s4hB+z6i>bmguIlg8l2_q0tLyx_ z*m0Zk+WUmf4xzxNY;NajSWb2lCYG3g9AZs5G-gk&6B#@$vYEn)HRe%l>rGY<^P+At zBspmxYTDkKbDH!*QVrkST%)nB7>emne}H#fN$k09mK zsS7sAi}8+cFUAfGLNSIFjMbMuG|*ZAk1h_M5|@KHWvW*+7dhrG=szYN9UvDVgr820 zMdZlUoCGtSs^Yr2p<&$SE(KEWFRa}G2++Tb(E&3iwJ2&JP;ysO;@Tm6K*RHN4&0sy z3l3!NXNz56>>pkv4!BELJc-oFF10s)7&a7m7l979n{#j{fd~^;17+y`eHe4#&N`h# z)Ym(z(6M!JW>XlBko62D@{wChUzL5<{wv=t*f48ipb*;Y4`_QWn0Ch^DpVNYI&ttUD?puA zEUb&Kr3*kWc$3F-^U4g&zE8GKv;+VX^jmf{`b}D^bTZAZYkc*gn!x1rZV4uLf+9s| zaC*-KO=7{T79-@*+B~Eks%Y{N^k^n|W~e-6zVt1ZPM}fEe0p?#as1}&6e^?%md3n( zofn7-?abMZV^m$PRTb$u%}yh&7uiI4IJCY9wUdK?{d#fm`sml=(|1RIJ9-Ny+}`8U z6}|JUs@3ahnKgr&jKo3YE{wUNLyVV@XztR{^y}VVHTSkHpDm`=25l=Pj2*yfdHvmA z!nQ6w0-JZh;MBA4I&Gt}zUeg8dC_e`;@EAaz!!NBV5m?ITaPW#-=>4@>$;Gp911dsYCp`j4G@imXqM2i^5b%$~gO6U=PBD zPouABpIxTP6gxSFKdz68#Y|TOecUJnQ;;O@g69c5$WG{5H4Y=Xw;piLHXknoYbz^* zY=;WIG}-HdGdD8&SRs2?Rt=gM5P93Df>u}`JgR>-LASX~!mwz5>k0OGBpb4-X5Vxko<5(JvoS%@fPR~VLP?@-SUVL%gsOwumA5rn5zBNKH5GNBQ8hF5$^$Gz?bnexi%NCroj)?JYWk2|PMQG09uW+{Mc^ zN(>Muz(8zhE;twLRv~ctb56^FuGbN4>ke_uNj{}qrmdVhNGk?}t!Nx)xIX+n2xG_^ z=^!W)#gGJ3Paj+%?QKuZOhvl6QN=*7agx!vb`T=K8p6husn8-3_N_o@E#aQ1fjIZ1 zL&k_D!WNS6NhV5KMn0e+fHi=Iw*v2YoG@# z>7?pjv~+xOC-89@dnC#}n@^^IhfHdOsi>)J6p`8mLuS{*cKl*BU~6_8qG+Ln_`PtQ z+YcM!JMPQt+J@*J>#iBzi;g4418BJ-dHik2Q%J|*@BXxW^IylLJRw$@dmCpx3)Y6I zsW>96qT~k12rV5cLLJA=Hwy$~As?#t z7&VXEjSa!07_Zt#eTVq`* z*L4~f&y#dr*9{3c(#D8DVN{(u*Q1&0)SyyzIsK$|l1kAdvAsK+coSkfp19hel7Z-)&vp)8+1JR&*MVjg@FDFw z(4viw4A8p0G|RlYDy1`$*lb99Fa-u)A0NAv^7@G0H`O`L5=6}sm1Wj{R=1AS<>vwo za%%0;!F7U9C^!o-9GYrkE(l7Xvc#xM=BCL=n{|MFAE;x2gI1Z zZ7OQl=jY_}THADaLLWw;N$c7+^`UPpt|#SJ+)B@qpR!Mxej>52uP!Ios!$a!Ao{kA zN0zKf7&Bi_?1N2xvEYCvD4j2G`^~iwxqjf>LSRdQLIt6md+@v_OSGf?p#{X^j7@+C z3rBDu36rK&)BOPC4ltXZi(!E&PU1eI2hWR($3cCQPkaWJGFwmcPA&`A5bua`P?xxX z=l1L*13X~mEN>^l>s0=Ww=3*aE~piQE^URwE@v_d&WwsT^Zy7xw`1ToSD=P)j$3$s z9)UL|F2fd{MQLHDS>5ncg_ZEMd>yc{(X8EeD0}CRkfp%O2lLif>_wD$`JUBzCCgGv zwk~JBDPS%*6xsP$pQ>im+{P~loU*sKe^K5J8!Mrf%Ix43r-u^ zOupM?mXKzVllDp*NkBnMub8>wJx?LONlW6ifPaQN>)4j6uw@kIL)sLsHBRuIQt5 ztk#_#swDwDGCz1o(g(|t$-&69**AN2e5R2mRZ#HceGfs5^V)v*!8cS*Pte!ZGre4o zDA_hYd8rZn`YvGB5n@52_$5DWjdkR7Q9ss!stR>EMBqSl3~>mu1E-n7rT)~rVhh7m z+un0=w7c-R-{O)#Q%joH+`%3hF3T=)b0u-y%D-e)_NrMt3a{szAbJCvG@?Vm%0Lx2 zr_ZUJ^58+YE!oAprAElQGHRkiXE?-a5FTbVhz#XWHUmO9M+6ptV{C_V{eRPiM^9PoDcTkEpG(bb{dStQ!vw+0jV z^`OUMqt|WLIewra&!!2T3+E^)<2B*B$tIqr6Y9`GjpUy8M}i2vkCd6m@RLwF#F(VS z0B8I(&wX%0$vb}CFhNFur^yZ8FRrUv`f0>rixyEULG&R*M4PmErQzubBjln-mG&IV zY5&K&SGKDUPND4sDq^jxW3FsOG|TNNxqKg7NA&BKT%c3)Ov8u4_=bzLjL1rPiNYs5@+hkXgzkFA7zO_AnBk}rFl2ETaX zZ9hghqLX?GaHE?HH`h>euGiHtAMyir*rG<%Ess(4jey}zGn@9KaSC>|oQVJZ-N_rS p1nI^_p}DcmeQ*R_<2CmBQI3Hl`fS^u*f{KyHG7kfht{_t{s$y5#1H@g literal 45732 zcmd^Idv6=Z5x>6+^g9SiQOH23v<;8|jblKFlvYV?3s%|`FpNfTGt~>E5=Sob)!WYR zhQpcJ+ZV|bB{C2!i@e==@67D%y!|8O}cSwoeomk7qTl{f0rit+hx(rqTwuN;+Q#%b#QHu1AJkt^-&^W;*tR<) zICstGEp~Y_Zl8>))u`p?Ja|5gV6c#n+UG|kjq4U0aCi)7ZHvw33DNNdNp++7sg>PH z(C)fz_mZUd15tfU6nQwK_W3J%cHZogTyBErW8&?yZNqY5RPacpcHxQSkJn zwGD2wGx^)o@NdG-I^Ay}+|cI{QF_;W(?0R7Z(2TKJFpGaU8>b5q-Ea{R^VG7621}9 zcGtWl+g6yq-|Oa0Wj|o>eeq4H|3NEjmN0r-iI@7uCC4;CE1^tF@U~m4Mt`>NQu_mA z>)Q7<@t|YiqbamESy}vz#tdu%x=>i#Qyt0krxV(q1zH&rPFT<(Sv^K%SEqYHi>F5C zHP9@#-dehlyE4!oZ)oItOU%=*J;lOe__P%yuAk7Sj8P%pwxhW$y|BkD(hU0o+Y96G zm3r8swr0)hXQuTj*_DkJp8xrHx75_pU@0i+H{<~PTkERBXh+#R7*)#pR~_cp#=iQI z_BHuyjutALl(t`xg`)L5JX(Wm$3lfckUb8*Gm{tCB!Vy7_Ws^rsQ|z0U^n5 z+>s}imJqYF@x3Kl%2Nv=M*j`rzb4JWLQWgWH#|&m#aa#9S?D2sHIRkcGW0U-C7SDL z^^oE;T4;5&X;$aqccp7#BOA?27SR4dIvl#OE1G&boh^k>PN)ZFNnL7oCQmFKb-hJa zF$gg!SsFAhXm9WTF>mC#`G?J_{wNQ-&6nhZwkZcvzq-+U+Ind_i`{5`Pvh?^$`nz9 zxFy|O(_aebIek8%r^x?#Hje*4rCP+bnG0``&l}UvkY>ME4g6ZX75qT@DSX6jGa%m$ zuYov#xhrN|1N!@{?WvS)5ElOv#|bzC!t3Wx()KLie2eHmB#(t^4D92?@X~Gjw&i<3 zd|$N~&;u2iEhE8IwWSYR9w6@o*RY@TqpX+WKdYnDZtY zd6eh0*U$>l7RjEo1M3m&a~bn8R_!xXM{meG44QXjo2Z$>LQ{~==;;OhT4hOK3`$M)i0Z36x`vZ+SMHB-#&V29 zNI|P-47A)isBn=O}I(5F3}*?`yI(jYJ6k*V7he7r=E+|FD**{I9mXf)B|6u%<0q-=A90 zHc1ANP)4d`<7ge~X_I6Kt;So61xSqTww5^nU|Y?m@LS!Lp&k$?vTCj4=F5qlE5{o5 zg=eA5L*NngJz38Y$?f||J|%5O#KRfc@FCgEc=BvrtfuVc?Aj80In-Z~S*Z-t9?q^a zu}$)9encJtH4#)%t@rTl*(y*uIiA>KIFc_rw5-o4wvykXoe%poXWpYq?@L+>@bhWk z5;Oj<+7ZpULTt=+dtgq0yb*qJ6!jC`J}*f6FDly}P+RQDN#hak_Rr>D#QQdJ zwM&2P5zcSvufNd0SHavT?2ESZ^+kq1B1xVS)(f&z*gX84c#=4^+Kc&|uZQ=%f=R|5 z#?eLdzWJp2laqb7-H@tns4sT?V7IMQ7_GH*TR{@%%^#aT6fkqU5`6;grT~p2^(EoW zQ-_#0CeM^_1x~Mut&mHUTVYpN4Ng?IYOun}YVf{otGB4)*60?|lB>{p$#B&OEl&zE zJf=vAOv}R4c(B?&xEvF0?Q&cd2kkzob&(VJkQ|Bm3+p9_?>5u=mTdccS}*Z^u>;e$ z#?C>Ga}1qlq*nGdE!1PDpdh}^_>^m&cn5u2(IYUN1rgbK) z7#+8<=YZxa$fOTxY)b8^3_~hGoN1NXb2fEMzOmGjb9&^&Sd%HWMifOft${plXMxAW zKW3k0$Tt+(1GLi&y>>{vN^KCA`?TY^#Miy!9}Y2463<RK5S?KL6!KP+2L>{+`|VYb~#;9^@eAD$U|U1CvA+i`rjhEg;zOf$1{AuDOrTbBi3?6 zZDCvN5w)%2UiYj8(FChAyvLq*Bh+OthzmDvo(|b_{ZMLzvY%=|{zO`bvvqC5{nthI z;Dfp5xfw@0wJ~{y5f1so25q(>&p8j-CHWyzZqmG>S0e> zPl&Y_oKE>=IwrJ|%$`zkvd6X5NTiV#9Hndve&XS!p1_db_35S4#6Ug6t&`>k-$FLJ8I7DhzPizxqJqbIy;%FnD^tv$ym zjzcI((aMc$59^+Z>`nbK&r9pF5F6z%KNg?PFkthNi|Cvq-;Se>?Ky6J7`}mik7(X> zLRr%#{jc~qhQP|#L0jM>X->@Nf<`D~5VLH2<3wM?Ak_e%S68laht+q4pyaq47Q?(6_CsUiB}Q z4f~bFB%XrVkGzG#`Q;s_uWuR4IVhIv6?tdmfO0Bo7Hsf*a@wXGqp>R=`=8Qtvee8g ze2K&?}v3C-@F)fkLeBZj@7GMT65H@lfd@%|caNPm`pt(yN2hYVT&&hsm=nhpQF{!1FU~oG)MA~W4_e4u(;!6-M60&V$9p!FBYpQPxh zoW8)g#W!;Ax2~A@cD8=-BvHNdF?(55r8W6@>5S|9q3IPH*d%+%(Xvez!}sXKH16#W zH>mM_M5$HsvS(=+7}y8Sc9504VR4ctxWS zw}J2}8s$5E2L@tUtjB8a@&)IIZ9cp~w=h@^;dO85=Yq~JZW8B+@_c$teV4WNZQ5CM zH?^b`Oq{d#cZVo!@rYfhj9aW!_KAn|Vh36Iz=<`1R9@LoP|C)g~V}2 zPlY1B0FIuT&e2tZGMs945h(sNW*DRPCOgM)a{|tAB95>{v9Awxjh(@I=9N!k=}FR* z^~o6#k&d^kx?ZgF*>T|%u*at-QbX=?=Vy1w%EPm% zq1JZ^4}RUAz~&arc}YgdhfdpB-4)T~DPzxVDNAw1yO7b6CCzs4t-r3XjJA3Dsy~&u zRpOrMPFt9#LbHa|&H-}S(r3kcQ9h$nHEN+aVS~Fax_1Sloj>~nUk{1GpLL&Jkd5Q4 zSh~f?v`}5d?>_|mYZ_aUO=JBCx1KBI7LRYq-grRmai4+QzOEy1(C%FieX`z?2;3M| zfP=dVaee@;kzb*DQbW6(qhPA>zB`OYwnv<=w^GFUP2o>kDvs5*Rq!F6Lv`n8on0HW zl_$tdeYxD1fEy0^Zm{?>u|}LQ00hmfECjL0ZYxi#&20Rw5B}VS#x&pGp4v&n3Qtcd zG(_-A;-Y)c{H&RWk18Sy1|I=FWPcQg2LrBxJ+aji@FPm)FGa~??^19G%9e1Va|--XCCXI=?N!v&=& zn1WMAsipS^vN%NUJY@BHDI8t8C7dJhS@J(Aa+|DD(dgv-q)i}P>Pl7)- zg86Q)vNd>!{!e942hr%?d07Atb2wq}>I zPf(dY|HwQD_pnEgvPyK9MhlSIlR&Vp-yGBdc1jBxcp zTnET=rems0Gq2m>4zm=^?1RwL-zpHxvILrDS+m1U(GjOTzdyzMPkfTPc3fgxG$VoC z%9ekGsMNZ(Kk4b$L$t?g%USt&K@v&bK`egF>I16=W18)&6ye##4y9&hpYxrfn9pM# z>(`*w?{U2F{p?PaaBV_y=3!tShe)69ud-Neo$}cEvehT=I>rwEen$^R1=ioOr};En zJJ<2U?>$);DJvhjk;6P=WN>8T-!e-0DY6&5U#8Rw8IHUILDzc(2Hs6RjyzX7*TJgg zUF&_@v%J||rIm{W-PWruTje@u%b|Z2DfoHWYqG*Oll`%^J%%&);Jqq>Cr$}R60Gsz zUhN$kA9(lLCe>c}FHg6ON&D2U6?fq%cd@?vG^UaJ%RF#V{Mx^ZSK_m@;n*ynY+SCH zEvG2oGP45AUr(}ftizPvn z-QCy4p_&d?Z_@I}uQG8>jcW(7F%DS@Y_t*z{8g*)_|XDBxw5owoQC6eeL0PJka})IkL%YW<5mwF zTCU}WtCHQQs%!A8L$lrG@K~uE$qg{&bZz%TTOxR$?0==)xNovRfOEi&i!!= zjy%`+MmUe_E|h?-t8u&ShUbFS|7vSW`N&m5<&4Fdk$_h3*VB4;S{ubm64wYYr^b6l5#7&ww_3ab z6=ysLQEaNEoV5xJZT)MoO<8#r?&Uq-tS@;}rB)sD?f>3qoXu)`oJi!IJlgZuV81E>U)SSoF!fZWg?E$K9B_ZS4pXy_rzYD`8vNcU zzn@?89BuD8k~ooiu9;t|MGe=0^4K_E-yF~Ga_u{lv*$|GC*-_|?SVBx|L#bIvHE^R zd8>P;B72iz=Z)ws`|v8tqV*6nXcP{_y{ahBkcW?2ep^=(`-HJnAZ-2RnvwCD6LK($oc5;L}Z>vfS4 t+cowI;?yASce5t8axkfurxuLq_B8 Date: Mon, 11 May 2015 10:37:10 -0700 Subject: [PATCH 018/416] Added typings for es6-collections --- es6-collections/es6-collections-tests.ts | 59 +++++++++ .../es6-collections-tests.ts.tscparams | 1 + es6-collections/es6-collections.d.ts | 113 ++++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 es6-collections/es6-collections-tests.ts create mode 100644 es6-collections/es6-collections-tests.ts.tscparams create mode 100644 es6-collections/es6-collections.d.ts 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 From 9b14d38a1ac99f5e6374c2f94bc251350cb2b52a Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 11 May 2015 11:34:57 -0700 Subject: [PATCH 019/416] Added typings for es6-shim --- es6-shim/es6-shim-tests.ts | 222 +++++++++ es6-shim/es6-shim-tests.ts.tscparams | 1 + es6-shim/es6-shim.d.ts | 673 +++++++++++++++++++++++++++ 3 files changed, 896 insertions(+) create mode 100644 es6-shim/es6-shim-tests.ts create mode 100644 es6-shim/es6-shim-tests.ts.tscparams create mode 100644 es6-shim/es6-shim.d.ts 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 From 75f03d73ce8a8a10f4594bd6500d6f207b2e8191 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Tue, 12 May 2015 08:13:37 -0400 Subject: [PATCH 020/416] Adding missing `timeout` property, changing others to be properties instead of functions, spelling fixes --- notifyjs/notifyjs-tests.ts | 6 ++++-- notifyjs/notifyjs.d.ts | 25 ++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/notifyjs/notifyjs-tests.ts b/notifyjs/notifyjs-tests.ts index 8771224c8..3289791de 100644 --- a/notifyjs/notifyjs-tests.ts +++ b/notifyjs/notifyjs-tests.ts @@ -14,6 +14,7 @@ function test_Notify_constructor() { body : "fuga", icon : "./logo.png", tag : "user", + timeout: 2, notifyShow : (e:Event)=> console.log("notifyShow", e), notifyClose : ()=> console.log("notifyClose"), notifyClick : ()=> console.log("notifyClick"), @@ -26,9 +27,10 @@ function test_Notify_constructor() { } function test_Notify_static_methods() { - Notify.needsPermission(); + Notify.needsPermission; Notify.requestPermission(); Notify.requestPermission(()=> console.log("onPermissionGrantedCallback")); Notify.requestPermission(()=> console.log("onPermissionGrantedCallback"), ()=> console.log("onPermissionDeniedCallback")); - Notify.isSupported(); + Notify.isSupported; + Notify.permissionLevel; } diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index f36b8fbcd..dc7bc57fe 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for notify.js 1.2.0 +// Type definitions for notify.js 1.2.3 // Project: https://github.com/alexgibson/notify.js // Definitions by: soundTricker // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -10,20 +10,26 @@ declare var Notify: { * Check is permission is needed for the user to receive notifications. * @return true : needs permission, false : does not need */ - needsPermission() : boolean; + needsPermission : boolean; /** * Asks the user for permission to display notifications - * @param onPermissionGrantedCallback A callback for permmision is granted. - * @param onPermissionDeniedCallback A callback for permmision is denied. + * @param onPermissionGrantedCallback A callback for permission is granted. + * @param onPermissionDeniedCallback A callback for permission is denied. */ requestPermission(onPermissionGrantedCallback?: ()=> any, onPermissionDeniedCallback? : ()=> any) : void; /** * return true if the browser supports HTML5 Notification - * @param true : the browser supports HTML5 Notification, false ; the browswer does not supports HTML5 Notification. + * @param true : the browser supports HTML5 Notification, false ; the browser does not supports HTML5 Notification. */ - isSupported() : boolean; + isSupported: boolean; + + /** + * shows the user's current permission level (granted, denied or default), returns null if notifications are not supported. + * @return 'granted' : permission has been given, 'denied' : permission has been denied, 'default' : permission has not yet been set, null : notifications are not supported + */ + permissionLevel: string; } declare module notifyjs { @@ -72,6 +78,11 @@ declare module notifyjs { * unique identifier to stop duplicate notifications */ tag? : string; + + /** + * number of seconds to close the notification automatically + */ + timeout? : number; /** * callback when notification is shown @@ -98,4 +109,4 @@ declare module notifyjs { */ permissionDenied? : Function; } -} +} \ No newline at end of file From 3f15066480dd9a016203bc258858ab16eb50ea13 Mon Sep 17 00:00:00 2001 From: Aaron Dandy Date: Tue, 12 May 2015 11:48:26 -0700 Subject: [PATCH 021/416] Update auth0.d.ts for typescript 1.5.0-beta --- auth0/auth0.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 5d3149ead..3562e50d5 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 { From c068c64bce9a2cfe7826e46dfe69a922978f9952 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 17 May 2015 00:47:08 +0300 Subject: [PATCH 022/416] Refactored sharepoint.d.ts to use microsoft.ajax.d.ts, added\fixed some definitions --- README.md | 0 angularjs/angular.d.ts | 0 chrome/chrome.d.ts | 0 microsoft-ajax/microsoft.ajax.d.ts | 992 ++++++----------- sharepoint/SharePoint.d.ts | 1642 ++++++++++++++++++++++++---- 5 files changed, 1768 insertions(+), 866 deletions(-) mode change 100644 => 100755 README.md mode change 100755 => 100644 angularjs/angular.d.ts mode change 100755 => 100644 chrome/chrome.d.ts diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100755 new mode 100644 diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts old mode 100755 new mode 100644 diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 1c8968f44..7100b8c51 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -18,7 +18,7 @@ * Object Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397554(v=vs.100).aspx} */ -interface Object { +interface ObjectConstructor { /** * Formats a number by using the invariant culture. */ @@ -34,173 +34,9 @@ interface Object { * Array Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb383786(v=vs.100).aspx} */ -interface Array { - - //#region lib.d.ts - - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): boolean; - prototype: Array; - - ///** - // * Returns a string representation of an array. - // */ - //toString(): string; - //toLocaleString(): string; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: U[]): T[]; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: 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(separator?: string): string; - ///** - // * Removes the last element from an array and returns it. - // */ - //pop(): T; - ///** - // * Appends new elements to an array, and returns the new length of the array. - // * @param items New elements of the Array. - // */ - //push(...items: T[]): number; - ///** - // * Reverses the elements in an Array. - // */ - //reverse(): T[]; - ///** - // * Removes the first element from an array and returns it. - // */ - //shift(): 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(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(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(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(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(...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(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(searchElement: 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(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(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(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(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(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(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. 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(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(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(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - ///** - // * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - // */ - //length: number; - - //[n: number]: T; - - //#endregion +interface ArrayConstructor { + //#region Extensions /** @@ -210,55 +46,55 @@ interface Array { * @param item * */ - add(array: any[], element: any): void; + add(array: T[], element: T): void; /** * Copies all the elements of the specified array to the end of an Array object. */ - addRange(array: any, items: any): void; + addRange(array: T[], items: T[]): void; /** * Removes all elements from an Array object. */ - clear(): void; + clear(array: T[]): void; /** * Creates a shallow copy of an Array object. */ - clone(): any[]; + clone(array: T[]): T[]; /** * Determines whether an element is in an Array object. */ - contains(element: any): boolean; + contains(array: T[], element: T): boolean; /** * Removes the first element from an Array object. */ - dequeue(): any; + dequeue(array: T[]): T; /** * Adds an element to the end of an Array object. Use the add function instead of the Array.enqueue function. */ - enqueue(element: any): void; + enqueue(array: T[], element: T): void; /** * Performs a specified action on each element of an Array object. */ - forEach(array: any[], method: Function, instance: any[]): void; + forEach(array: T[], method: (element: T, index: number, array: T[]) => void, instance: any): void; /** * Searches for the specified element of an Array object and returns its index. */ - indexOf(array: any[], item: any, startIndex?: number): number; + indexOf(array: T[], item: T, startIndex?: number): number; /** * Inserts a value at the specified location in an Array object. */ - insert(array: any[], index: number, item: any); + insert(array: T[], index: number, item: T): void; /** * Creates an Array object from a string representation. */ - parse(value: string): any[]; + parse(value: string): T[]; /** * Removes the first occurrence of an element in an Array object. */ - remove(array: any[], item: any): boolean; + remove(array: T[], item: T): boolean; /** * Removes an element at the specified location in an Array object. */ - removeAt(array: any[], index: number): void; + removeAt(array: T[], index: number): void; //#endregion } @@ -277,6 +113,10 @@ interface Number { * Formats a number by using the current culture. */ localeFormat(format: string): string; +} + +interface NumberConstructor { + /** * Returns a numeric value from a string representation of a number. This function is static and can be called without creating an instance of the object. */ @@ -297,11 +137,14 @@ interface Date { /** * Formats a date by using the invariant (culture-independent) culture. */ - format(value: string): string; + format(format: string): string; /** * Formats a date by using the current culture. This function is static and can be invoked without creating an instance of the object. */ - localeFormat(value: string): string; + localeFormat(format: string): string; +} + +interface DateConstructor { /** * Creates a date from a locale-specific string by using the current culture. This function is static and can be invoked without creating an instance of the object. * @exception (Debug) formats contains an invalid format. @@ -310,9 +153,8 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseLocale(value: string): string; - parseLocale(value: string, formats?: string[]): string; - parseLocale(value: string, ...formats: string[]): string; + parseLocale(value: string, formats?: string[]): Date; + parseLocale(value: string, ...formats: string[]): Date; /** * Creates a date from a string by using the invariant culture. This function is static and can be invoked without creating an instance of the object. * @return If value is a valid string representation of a date in the invariant format, an object of type Date; otherwise, null. @@ -321,352 +163,172 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseInvariant(value: string): string; parseInvariant(value: string, formats?: string[]): string; parseInvariant(value: string, ...formats: string[]): string; } -declare module MicrosoftAjaxBaseTypeExtensions { + +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception +* details and support for application-compilation modes (debug or release). +* @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} +*/ +interface FunctionConstructor { + + //#region Extensions /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception - * details and support for application-compilation modes (debug or release). - * @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} - */ - interface Function { - - //#region lib.d.ts - - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - prototype: Function; - - //#endregion - - //#region Extensions - - /** - * Creates a delegate function that retains the context first used during an objects creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } - */ - createCallback(method: Function, ...context: any[]): Function; - /** - * Creates a callback function that retains the parameter initially used during an object's creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } - */ - createDelegate(instance: any, method: Function): Function; - - /** - * A function that does nothing. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } - */ - emptyMethod(): Function; - - /** - * Validates the parameters to a method are as expected. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } - */ - validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - - //#endregion - } + * Creates a delegate function that retains the context first used during an objects creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } + */ + createCallback(method: Function, ...context: any[]): Function; + /** + * Creates a callback function that retains the parameter initially used during an object's creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } + */ + createDelegate(instance: any, method: Function): Function; /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). - * Error Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} - */ - interface Error { - - //#region lib.d.ts - - name: string; - message: string; - - new (message?: string): Error; - (message?: string): Error; - prototype: Error; - - //#endregion - - //#region Extensions - - /** - * Creates an Error object that represents the Sys.ParameterCountException exception. - */ - parameterCount(message?: string): Error; - /** - * Creates an Error object that represents the Sys.NotImplementedException exception. - */ - notImplemented(message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentException exception. - */ - argument(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentNullException exception. - */ - argumentNull(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. - */ - argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentTypeException exception. - */ - argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. - */ - argumentUndefined(paramName?: string, message?: string): Error; - /** - * Creates an Error object that can contain additional error information. - */ - create(message?: string, errorInfo?: Object): Error; - /** - * Creates an Error object that represents the Sys.FormatException exception. - */ - format(message?: string): Error; - /** - * Creates an Error object that represents the Sys.InvalidOperationException exception. - */ - invalidOperation(message?: string): Error; - /** - * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. - */ - popStackFrame(): void; - - //#endregion - } + * A function that does nothing. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } + */ + emptyMethod(): Function; /** - * Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. - * String Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} - */ - interface String { + * Validates the parameters to a method are as expected. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } + */ + validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - //#region lib.d.ts + //#endregion +} - new (value?: any): String; - (value?: any): string; - prototype: String; - fromCharCode(...codes: number[]): string; +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). +* Error Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} +*/ +interface ErrorConstructor { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): string[]; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): string[]; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Returns the length of a String object. */ - length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - [index: number]: string; - - //#endregion - - //#region Extensions - - /** - * Formats a number by using the invariant culture. - * @returns true if the end of the String object matches suffix; otherwise, false. - */ - endsWith(suffix: string): boolean; - /** - * Replaces each format item in a String object with the text equivalent of a corresponding object's value. - * @returns A copy of the string with the formatting applied. - */ - format(format: string, ...args: any[]): string; - /** - * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. - * @returns A copy of the string with the formatting applied. - */ - localeFormat(format: string, ...args: any[]): string; - /** - * Removes leading and trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start and end of the string. - */ - trim(): string; - /** - * Removes trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the end of the string. - */ - trimEnd(): string; - /** - * Removes leading white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start of the string. - */ - trimStart(): string; - - //#endregion - } + //#region Extensions /** - * Provides extensions to the base ECMAScript (JavaScript) Boolean object. - * Boolean Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} + * Creates an Error object that represents the Sys.ParameterCountException exception. */ - interface Boolean { + parameterCount(message?: string): Error; + /** + * Creates an Error object that represents the Sys.NotImplementedException exception. + */ + notImplemented(message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentException exception. + */ + argument(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentNullException exception. + */ + argumentNull(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. + */ + argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentTypeException exception. + */ + argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. + */ + argumentUndefined(paramName?: string, message?: string): Error; + /** + * Creates an Error object that can contain additional error information. + */ + create(message?: string, errorInfo?: Object): Error; + /** + * Creates an Error object that represents the Sys.FormatException exception. + */ + format(message?: string): Error; + /** + * Creates an Error object that represents the Sys.InvalidOperationException exception. + */ + invalidOperation(message?: string): Error; - //#region lib.d.ts - new (value?: any): Boolean; - (value?: any): boolean; - prototype: Boolean; + //#endregion +} - //#endregion +interface Error { + /** + * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. + */ + popStackFrame(): void; +} - //#region Extensions - /** - * Converts a string representation of a logical value to its Boolean object equivalent. - */ - parse(value: string): Boolean; - //#endregion - } +interface String { + + //#region Extensions + + /** + * Formats a number by using the invariant culture. + * @returns true if the end of the String object matches suffix; otherwise, false. + */ + endsWith(suffix: string): boolean; + + /** + * Removes leading and trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start and end of the string. + */ + trim(): string; + /** + * Removes trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the end of the string. + */ + trimEnd(): string; + /** + * Removes leading white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start of the string. + */ + trimStart(): string; + + //#endregion +} + +/** +* Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. +* String Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} +*/ +interface StringConstructor { + /** +* Replaces each format item in a String object with the text equivalent of a corresponding object's value. +* @returns A copy of the string with the formatting applied. +*/ + format(format: string, ...args: any[]): string; + /** + * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. + * @returns A copy of the string with the formatting applied. + */ + localeFormat(format: string, ...args: any[]): string; +} + + +/** +* Provides extensions to the base ECMAScript (JavaScript) Boolean object. +* Boolean Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} +*/ +interface BooleanConstructor { + + //#region Extensions + + /** + * Converts a string representation of a logical value to its Boolean object equivalent. + */ + parse(value: string): Boolean; + + //#endregion } //#endregion @@ -908,7 +570,7 @@ declare function $find(id: string, parent?: HTMLElement): Sys.Component; * @param handler The event handler to add. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandler(element: Sys.UI.DomElement, eventName: string, handler: Function, autoRemove?: boolean): void; +declare function $addHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void, autoRemove?: boolean): void; /** * Provides a shortcut to the addHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -918,7 +580,7 @@ declare function $addHandler(element: Sys.UI.DomElement, eventName: string, hand * @param handlerOwner (Optional) The object instance that is the context for the delegates that should be created from the handlers. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOwner?: any, autoRemove?: boolean): void; +declare function $addHandlers(element: HTMLElement, events: { [event: string]: (e: Sys.UI.DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Provides a shortcut to the clearHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -926,21 +588,19 @@ declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOw * @see {@link http://msdn.microsoft.com/en-us/library/bb310959(v=vs.100).aspx} * @param The DOM element that exposes the events. */ -declare function $clearHandlers(element: Sys.UI.DomElement): void; +declare function $clearHandlers(element: HTMLElement): void; /** -* Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class. +* Provides a shortcut to the getElementById method of the HTMLElement class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397717(v=vs.100).aspx} * @param id * The ID of the DOM element to find. * @param element * The parent element to search. The default is the document element. * @return -* The Sys.UI.DomElement +* The HTMLElement */ -declare function $get(id: string): any; // Examples use HTMLElement and DomElement declare function $get(id: string, element?: HTMLElement): HTMLElement; -declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; /** * Provides a shortcut to the removeHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -949,9 +609,7 @@ declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElemen * @param eventName The name of the DOM event. * @param handler The event handler to remove. */ -declare function $removeHandler(element: any, eventName: string, handler: Function): void; -declare function $removeHandler(element: HTMLElement, eventName: string, handler: Function): void; -declare function $removeHandler(element: Sys.UI.DomElement, eventName: string, handler: Function): void; +declare function $removeHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void): void; //#endregion @@ -973,7 +631,7 @@ declare module Sys { * The members can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb384161(v=vs.100).aspx} */ - interface Application { + interface Application extends Component, IContainer { //#region Constructors @@ -986,27 +644,27 @@ declare module Sys { /** * Raised after all scripts have been loaded but before objects are created. */ - add_init(handler: Function): void; + add_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded but before objects are created. */ - remove_init(handler: Function): void; + remove_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - add_load(handler: Function): void; + add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - remove_load(handler: Function): void; + remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - add_navigate(handler: Function): void; + add_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - remove_navigate(handler: Function): void; + remove_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. @@ -2175,67 +1833,67 @@ declare module Sys { //#endregion //#region Exception Types + // Really not a types + ///** + //* Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. + //*/ + //class ArgumentException { - /** - * Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. - */ - class ArgumentException { + //} + ///** + //* Raised when an argument has an invalid value of null. + //*/ + //class ArgumentNullException { - } - /** - * Raised when an argument has an invalid value of null. - */ - class ArgumentNullException { + //} + ///** + //* Raised when an argument value is outside an acceptable range. + //*/ + //class ArgumentOutOfRangeException { - } - /** - * Raised when an argument value is outside an acceptable range. - */ - class ArgumentOutOfRangeException { + //} + ///** + //* Raised when a parameter is not an allowed type. + //*/ + //class ArgumentTypeException { - } - /** - * Raised when a parameter is not an allowed type. - */ - class ArgumentTypeException { + //} + ///** + //* Raised when an argument for a required method parameter is undefined. + //*/ + //class ArgumentUndefinedException { - } - /** - * Raised when an argument for a required method parameter is undefined. - */ - class ArgumentUndefinedException { + //} + ///** + //* + //*/ + //class FormatException { - } - /** - * - */ - class FormatException { + //} + ///** + //* Raised when a call to a method has failed, but the reason was not invalid arguments. + //*/ + //class InvalidOperationException { - } - /** - * Raised when a call to a method has failed, but the reason was not invalid arguments. - */ - class InvalidOperationException { + //} + ///** + //* Raised when a requested method is not supported by an object. + //*/ + //class NotImplementedException { - } - /** - * Raised when a requested method is not supported by an object. - */ - class NotImplementedException { + //} + ///** + //* Raised when an invalid number of arguments have been passed to a function. + //*/ + //class ParameterCountException { - } - /** - * Raised when an invalid number of arguments have been passed to a function. - */ - class ParameterCountException { + //} + ///** + //* Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. + //*/ + //class ScriptLoadFailedException { - } - /** - * Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. - */ - class ScriptLoadFailedException { - - } + //} //#endregion @@ -2252,7 +1910,28 @@ declare module Sys { * Enables your application to call Web services asynchronously by using ECMAScript (JavaScript). * @see {@link http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx} */ - // Cannot create definitions for generated proxy classes. + class WebServiceProxy { + static invoke( + servicePath: string, + methodName: string, + useGet?: boolean, + params?: any, + onSuccess?: (result: string, eventArgs: EventArgs) => void, + onFailure?: (error: WebServiceError) => void, + userContext?: any, + timeout?: number, + enableJsonp?: boolean, + jsonpCallbackParameter?: string): WebRequest; + } + + class WebServiceError { + get_errorObject(): any; + get_exceptionType(): any; + get_message(): string; + get_stackTrace(): string; + get_statusCode(): number; + get_timedOut(): boolean; + } /** * Contains information about a Web request that is ready to be sent to the current Sys.Net.WebRequestExecutor instance. @@ -2261,7 +1940,7 @@ declare module Sys { * * @see {@link http://msdn.microsoft.com/en-us/library/bb397488(v=vs.100).aspx} */ - class NetWorkRequestEventArgs { + class NetworkRequestEventArgs { //#region Constructors @@ -2310,6 +1989,19 @@ declare module Sys { //#endregion //#region Members + get_url(): string; + set_url(value: string): void; + get_httpVerb(): string; + set_httpVerb(value: string): void; + get_timeout(): number; + set_timeout(value: number): void; + get_body(): string; + set_body(value: string): void; + get_headers(): { [key: string]: string; }; + get_userContext(): any; + set_userContext(value: any): void; + get_executor(): WebRequestExecutor; + set_executor(value: WebRequestExecutor): void; /** * Registers a handler for the completed request event of the Web request. @@ -2387,7 +2079,7 @@ declare module Sys { * Gets the value of the specified response header. * @return The specified response header. */ - getResponseHeader(): string; + getResponseHeader(key: string): string; //#endregion @@ -2478,13 +2170,13 @@ declare module Sys { * @param handler * The function registered to handle the completed request event. */ - add_completedRequest(handler: (sender: any, eventArgs: any) => void): void; + add_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Registers a handler for processing the invoking request event of the WebRequestManager. * @param handler * The function registered to handle the invoking request event. */ - add_invokingRequest(handler: (sender: any, networkRequestEventArgs: any) => void): void; + add_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; /** * Sends Web requests to the default network executor. * This member supports the client-script infrastructure and is not intended to be used directly from your code. @@ -2498,14 +2190,14 @@ declare module Sys { * @param handler * The function that handles the completed request event. */ - remove_completedRequest(handler: Function): void; + remove_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Removes the event handler set by the add_invokingRequest method. * Use the remove_invokingRequest method to remove the event handler you set using the add_invokingRequest method. * @param handler * The function that handles the invoking request event. */ - remove_invokingRequest(handler: Function): void; + remove_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; //#endregion @@ -2943,16 +2635,16 @@ declare module Sys { * Gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element. This member a static member and can be invoked without creating an instance of the class. * @return The specified Behavior object, if found; otherwise, null. */ - static getBehaviorByName(element: Sys.UI.DomElement, name: string): Behavior; + static getBehaviorByName(element: HTMLElement, name: string): Behavior; /** * Gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element. This method is static and can be invoked without creating an instance of the class. * @return An array of all Behavior objects of the specified type that are associated with the specified DOM element, if found; otherwise, an empty array. */ - static getBehaviorsByType(element: Sys.UI.DomElement, type: Sys.UI.Behavior): Behavior[]; + static getBehaviorsByType(element: HTMLElement, type: Sys.UI.Behavior): Behavior[]; /** * Gets the Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to search. + * The HTMLElement object to search. * @return An array of references to Behavior objects, or null if no references exist. */ static getBehaviors(element: DomElement): Behavior[]; @@ -2971,10 +2663,10 @@ declare module Sys { * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Behavior object is associated with. * @return The DOM element that the current Behavior object is associated with. */ - get_element(): Sys.UI.DomElement; + get_element(): HTMLElement; /** * Gets or sets the identifier for the Sys.UI.Behavior object. - * A generated identifier that consists of the ID of the associated Sys.UI.DomElement, the "$" character, and the name value of the Behavior object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Behavior object. */ get_id(): string; /** @@ -3050,11 +2742,11 @@ declare module Sys { * When called from a derived class, initializes a new instance of that class. * The Control constructor is a complete constructor function. However, because the Control class is an abstract base class, the constructor should be called only from derived classes. * @param element - * The Sys.UI.DomElement object that the control will be associated with. + * The HTMLElement object that the control will be associated with. * * @throws Error.invalidOperation Function */ - constructor(element: Sys.UI.DomElement); + constructor(element: HTMLElement); //#endregion @@ -3122,6 +2814,33 @@ declare module Sys { toggleCssClass(className: string): void; //#endregion + + //#region Properties + + /** + * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Control object is associated with. + * @return The DOM element that the current Control object is associated with. + */ + get_element(): HTMLElement; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Control object. + */ + get_id(): string; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * @param value + * The string value to use as the identifier. + */ + set_id(value: string): void; + /* + * Gets or sets the name of the Sys.UI.Control object. + * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Control object. The name property remains null until it is accessed. + * @param value + * A string value to use as the name. + */ + + //#endregion } /** * Defines static methods and properties that provide helper APIs for manipulating and inspecting DOM elements. @@ -3131,11 +2850,7 @@ declare module Sys { //#region Constructors - /** - * Initializes a new instance of the Sys.UI.DomElement class. - */ - constructor(): void; - + //#endregion //#region Methods @@ -3144,38 +2859,38 @@ declare module Sys { * Adds a CSS class to a DOM element if the class is not already part of the DOM element. This member is static and can be invoked without creating an instance of the class. * If the element does not support a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to add the CSS class to. + * The HTMLElement object to add the CSS class to. * @param className * The name of the CSS class to add. */ - addCssClass(element: Sys.UI.DomElement, className: string): void; + addCssClass(element: HTMLElement, className: string): void; /** * Gets a value that indicates whether the DOM element contains the specified CSS class. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to test for the CSS class. + * The HTMLElement object to test for the CSS class. * @param className * The name of the CSS class to test for. * @return * true if the element contains the specified CSS class; otherwise, false. */ - containsCssClass(element: Sys.UI.DomElement, className: string): boolean; + containsCssClass(element: HTMLElement, className: string): boolean; /** * Gets a set of integer coordinates that represent the position, width, and height of a DOM element. This member is static and can be invoked without creating an instance of the class. * * @param element - * The Sys.UI.DomElement instance to get the coordinates of. + * The HTMLElement instance to get the coordinates of. * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the upper-left corner, the width, and the height of the element in pixels. */ - getBounds(element: Sys.UI.DomElement): Object; + getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; /** * @param id * The ID of the element to find. * @param element * (optional) The parent element to search in. The default is the document element. */ - getElementById(id: string): Sys.UI.DomElement; - getElementById(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; + getElementById(id: string): HTMLElement; + getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element: any): any; /** @@ -3185,17 +2900,15 @@ declare module Sys { * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the element in pixels. */ - getLocation(element: Sys.UI.DomElement): Sys.UI.Point; - getLocation(element: any): Object; + getLocation(element: HTMLElement): Sys.UI.Point; /* - * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. This member is static and can be invoked without creating an instance of the class. + * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. This member is static and can be invoked without creating an instance of the class. * @param element * The target DOM element. * @return * A Sys.UI.VisibilityMode enumeration value that indicates the layout characteristics of element when it is hidden by invoking the setVisible method. */ - getVisibilityMode(element: Sys.UI.DomElement): Sys.UI.VisibilityMode; - getVisibilityMode(element: any): Sys.UI.VisibilityMode; + getVisibilityMode(element: HTMLElement): Sys.UI.VisibilityMode; /** * Gets a value that indicates whether a DOM element is currently visible on the Web page. This member is static and can be invoked without creating an instance of the class. * @param element @@ -3219,16 +2932,15 @@ declare module Sys { * @param args * The event arguments */ - raiseBubbleEvent(source: Sys.UI.DomElement, args: EventArgs): void; - raiseBubbleEvent(source: any, args: any): void; + raiseBubbleEvent(source: HTMLElement, args: EventArgs): void; /** * Removes a CSS class from a DOM element. This member is static and can be invoked without creating an instance of the class. If the element does not include a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to remove the CSS class from. + * The HTMLElement object to remove the CSS class from. * @param className * The name of the CSS class to remove. */ - removeCssClass(element: Sys.UI.DomElement, className: string): void; + removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: any, className: string): void; /** @@ -3241,9 +2953,7 @@ declare module Sys { * @return * A DOM element. */ - resolveElement(elementOrElementId: Sys.UI.DomElement, containerElement?: Sys.UI.DomElement): Sys.UI.DomElement; - resolveElement(elementOrElementId: HTMLElement, containerElement?: HTMLElement): HTMLElement; - resolveElement(elementOrElementId: string): any; + resolveElement(elementOrElementId: string|HTMLElement, containerElement?: HTMLElement): HTMLElement; /** * Sets the position of a DOM element. This member is static and can be invoked without creating an instance of the class. * he left and top style attributes (upper-left corner) of an element specify the relative position of an element. @@ -3252,14 +2962,12 @@ declare module Sys { * @param x The x-coordinate in pixels. * @param y The y-coordinate in pixels. */ - setLocation(element: Sys.UI.DomElement, x: number, y: number): void; setLocation(element: HTMLElement, x: number, y: number): void; - setLocation(element: any, x: number, y: number): void; /** - * Sets the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Sets the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * This member is static and can be invoked without creating an instance of the class. * - * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * For example, if value is set to Sys.UI.VisibilityMode.collapse, the element uses no space on the page when the setVisible method is called to hide the element. * * @param element @@ -3267,41 +2975,37 @@ declare module Sys { * @param value * A Sys.UI.VisibilityMode enumeration value. */ - setVisibilityMode(element: Sys.UI.DomElement, value: Sys.UI.VisibilityMode): void; + setVisibilityMode(element: HTMLElement, value: Sys.UI.VisibilityMode): void; /** * Sets a DOM element to be visible or hidden. This member is static and can be invoked without creating an instance of the class. * * Use the setVisible method to set a DOM element as visible or hidden on the Web page. * If you invoke this method with value set to false for an element whose visibility mode is set to "hide," the element will not be visible. * However, it will occupy space on the page. If the element's visibility mode is set to "collapse," the element will occupy no space in the page. - * For more information about how to set the layout characteristics of hidden DOM elements, see Sys.UI.DomElement setVisibilityMode Method. + * For more information about how to set the layout characteristics of hidden DOM elements, see HTMLElement setVisibilityMode Method. * * @param element * The target DOM element. * @param value * true to make element visible on the Web page; false to hide element. */ - setVisible(element: Sys.UI.DomElement, value: boolean): void; setVisible(element: HTMLElement, value: boolean): void; - setVisible(element: any, value: boolean): void; /** * Toggles a CSS class in a DOM element. This member is static and can be invoked without creating an instance of the class. * Use the toggleCssClass method to hide a CSS class of an element if it is shown, or to show a CSS class of an element if it is hidden. * * @param element - * The Sys.UI.DomElement object to toggle. + * The HTMLElement object to toggle. * @param className * The name of the CSS class to toggle. */ - toggleCssClass(element: Sys.UI.DomElement, className: string): void; toggleCssClass(element: HTMLElement, className: string): void; - toggleCssClass(element: any, className: string): void; //#endregion } - var DomElement: Sys.UI.DomElement; + var DomElement: DomElement; /** * Provides cross-browser access to DOM event properties and helper APIs that are used to attach handlers to DOM element events. @@ -3312,12 +3016,11 @@ declare module Sys { //#region Constructors /** - * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified DomElement object. + * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified HTMLElement object. * @param domElement - * The DomElement object to associate with the event. + * The HTMLElement object to associate with the event. */ - constructor(domElement: DomElement); - constructor(domElement: any); + constructor(domElement: HTMLElement); //#endregion @@ -3337,7 +3040,7 @@ declare module Sys { * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ - static addHandler(element: any, eventName: string, handler: Function, autoRemove?: boolean): void; + static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean); /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. @@ -3359,7 +3062,7 @@ declare module Sys { * @throws Error.invalidOperation - (Debug) One of the handlers specified in events is not a function. * */ - static addHandlers(element: any, events: any, handlerOwner?: any, autoRemove?: boolean): void; + static addHandlers(element: HTMLElement, events: { [event: string]: (e: DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Removes all DOM event handlers from a DOM element that were added through the Sys.UI.DomEvent addHandler or the Sys.UI.DomEvent addHandlers methods. * This member is static and can be invoked without creating an instance of the class. @@ -3368,7 +3071,7 @@ declare module Sys { * @param element * The element that exposes the events. */ - static clearHandlers(element: any): void; + static clearHandlers(element: HTMLElement): void; /** * Removes a DOM event handler from the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. * @@ -3379,7 +3082,7 @@ declare module Sys { * @param handler * The event handler to remove. */ - static removeHandler(element: any, eventName: string, handler: Function): void; + static removeHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void): void; /** * Prevents the default DOM event action from happening. * Use the preventDefault method to prevent the default event action for the browser from occurring. @@ -3544,10 +3247,21 @@ declare module Sys { * Describes mouse button locations. */ enum MouseButton { - // todo + /** + * Represents the left mouse button. + */ + leftButton, + /** + * Represents the middle mouse button. + */ + middleButton, + /** + * Represents the right mouse button. + */ + rightButton } /** - * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the Sys.UI.DomElement class returns a Point object. + * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the HTMLElement class returns a Point object. * @see {@link http://msdn.microsoft.com/en-us/library/bb383992(v=vs.100).aspx} * */ class Point { @@ -3829,7 +3543,7 @@ declare module Sys { * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of
elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. */ - get_panelsDeleted(): HTMLDivElement[]; + get_panelsDeleting(): HTMLDivElement[]; /** * Gets an array of HTML
elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding
elements. diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 1f7a2feaf..026658ef8 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,157 +1,13 @@ -// Type definitions for sptypescript +// Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Sys { - export class EventArgs { - static Empty: Sys.EventArgs; - } - export class StringBuilder { - /** Appends a string to the string builder */ - append(s: string): void; - /** Appends a line to the string builder */ - appendLine(s: string): void; - /** Clears the contents of the string builder */ - clear(): void; - /** Indicates wherever the string builder is empty */ - isEmpty(): boolean; - /** Gets the contents of the string builder as a string */ - toString(): string; - } - export class Component { - get_id(): string; - static create(type: Component, properties?: any, events?: any, references?: any, element?: Node); - initialize(): void; - updated(): void; - } - - export interface IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - } - - export class Application extends Component implements IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - - static add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - static remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - } - - export class ApplicationLoadEventArgs { - constructor(components: Component[], isPartialLoad: boolean); - public components: Component[]; - public isPartialLoad: boolean; - } - - module UI { - export class Control extends Component { } - export class DomEvent { - static addHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - static removeHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - } - - export class DomElement { - static getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; - } - } - module Net { - export class WebRequest { - get_url(): string; - set_url(value: string): void; - get_httpVerb(): string; - set_httpVerb(value: string): void; - get_timeout(): number; - set_timeout(value: number): void; - get_body(): string; - set_body(value: string): void; - get_headers(): { [key: string]: string; }; - get_userContext(): any; - set_userContext(value: any): void; - get_executor(): WebRequestExecutor; - set_executor(value: WebRequestExecutor): void; - - getResolvedUrl(); string; - invoke(): void; - completed(args: Sys.EventArgs): void; - - add_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - remove_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - } - - export class WebRequestExecutor { - get_aborted(): boolean; - get_responseAvailable(): boolean; - get_responseData(): string; - get_object(): any; - get_started(): boolean; - get_statusCode(): number; - get_statusText(): string; - get_timedOut(): boolean; - get_xml(): Document; - get_webRequest(): WebRequest; - abort(): void; - executeRequest(): void; - getAllResponseHeaders(): string; - getResponseHeader(key: string): string; - } - - export class NetworkRequestEventArgs extends EventArgs { - get_webRequest(): WebRequest; - } - - - export class WebRequestManager { - static get_defaultExecutorType(): string; - static set_defaultExecutorType(value: string): void; - static get_defaultTimeout(): number; - static set_defaultTimeout(value: number): void; - - static executeRequest(request: WebRequest): void; - static add_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static remove_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static add_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - static remove_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - } - - export class WebServiceProxy { - static invoke( - servicePath: string, - methodName: string, - useGet?: boolean, - params?: any, - onSuccess?: (result: string, eventArgs: EventArgs) => void, - onFailure?: (error: WebServiceError) => void, - userContext?: any, - timeout?: number, - enableJsonp?: boolean, - jsonpCallbackParameter?: string): WebRequest; - } - - export class WebServiceError { - get_errorObject(): any; - get_exceptionType(): any; - get_message(): string; - get_stackTrace(): string; - get_statusCode(): number; - get_timedOut(): boolean; - } - } - interface IDisposable { - dispose(): void; - } - -} - -declare var $get: { (id: string): HTMLElement; }; -declare var $addHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; -declare var $removeHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; +/// +declare var _spBodyOnLoadFunctions: Function[]; +declare var _spBodyOnLoadFunctionNames: string[]; +declare var _spBodyOnLoadCalled: boolean; declare module SP { export class SOD { @@ -463,7 +319,8 @@ interface ContextInfo extends SPClientTemplates.RenderContext { } -declare function GetCurrentCtx():ContextInfo; +declare function GetCurrentCtx(): ContextInfo; +declare function SetFullScreenMode(fullscreen: boolean); declare module SP { export enum RequestExecutorErrors { requestAbortedOrTimedout, @@ -490,7 +347,7 @@ declare module SP { method?: string; headers?: { [key: string]: string; }; /** Can be string or bytearray depending on binaryStringRequestBody field */ - body?: any; + body?: string|Uint8Array; binaryStringRequestBody?: boolean; /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ @@ -509,7 +366,7 @@ declare module SP { headers?: { [key: string]: string; }; contentType?: string; /** Can be string or bytearray depending on request.binaryStringResponseBody field */ - body?: any; + body?: string|Uint8Array; state?: any; } @@ -1116,8 +973,8 @@ declare module SPClientTemplates { Type: string; } -/** Represents field schema in Grid mode and on list forms. - Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ + /** Represents field schema in Grid mode and on list forms. + Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ export interface FieldSchema_InForm extends FieldSchema { /** Description for this field. */ Description: string; @@ -1166,6 +1023,7 @@ declare module SPClientTemplates { FormUniqueId: string; ListData: ListData_InForm; ListSchema: ListSchema_InForm; + CSRCustomLayout?: boolean; } @@ -1389,7 +1247,7 @@ declare module SPClientTemplates { StateInitDone: boolean; TableCbxFocusHandler: any; TableMouseOverHandler: any; - TotalListItems: any; + TotalListItems: number; verEnabled: number; /** Guid of the view. */ view: string; @@ -1404,10 +1262,10 @@ declare module SPClientTemplates { } export interface RenderContext_FieldInView extends RenderContext_ItemInView { /** If in grid mode (context.inGridMode == true), cast to FieldSchema_InForm, otherwise cast to FieldSchema_InView */ - CurrentFieldSchema: any; + CurrentFieldSchema: FieldSchema_InForm | FieldSchema_InView; CurrentFieldValue: any; FieldControlsModes: { [fieldInternalName: string]: ClientControlMode; }; - FormContext: any; + FormContext: ClientFormContext; FormUniqueId: string; } @@ -1417,6 +1275,7 @@ declare module SPClientTemplates { export interface Group { Items: Item[]; } + type RenderCallback = (ctx: RenderContext) => void; export interface RenderContext { BaseViewID?: number; @@ -1426,8 +1285,8 @@ declare module SPClientTemplates { CurrentSelectedItems?: any; CurrentUICultureName?: string; ListTemplateType?: number; - OnPostRender?: any; - OnPreRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; + OnPreRender?: RenderCallback | RenderCallback[]; onRefreshFailed?: any; RenderBody?: (renderContext: RenderContext) => string; RenderFieldByName?: (renderContext: RenderContext, fieldName: string) => string; @@ -1484,18 +1343,18 @@ declare module SPClientTemplates { } export interface Templates { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplates; } @@ -1505,18 +1364,18 @@ declare module SPClientTemplates { } export interface TemplateOverrides { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplateMap; } @@ -1525,10 +1384,10 @@ declare module SPClientTemplates { Templates?: TemplateOverrides; /** �allbacks called before rendering starts. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPreRender?: any; + OnPreRender?: RenderCallback | RenderCallback[]; /** �allbacks called after rendered html inserted into DOM. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPostRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; /** View style (SPView.StyleID) for which the templates should be applied. If not defined, the templates will be applied only to default view style. */ @@ -1538,11 +1397,11 @@ declare module SPClientTemplates { ListTemplateType?: number; /** Base view ID (SPView.BaseViewID) for which the template should be applied. If not defined, the templates will be applied to all views. */ - BaseViewID?: any; + BaseViewID?: number|string; } export class TemplateManager { static RegisterTemplateOverrides(renderCtx: TemplateOverridesOptions): void; - static GetTemplates(renderCtx: any): Templates; + static GetTemplates(renderCtx: RenderContext): Templates; } export interface ClientUserValue { @@ -1616,13 +1475,13 @@ declare module SPClientTemplates { EnableVesioning: boolean; Id: string; }; - registerInitCallback(fieldname: string, callback: () => void ): void; - registerFocusCallback(fieldname: string, callback: () => void ): void; - registerValidationErrorCallback(fieldname: string, callback: (error: any) => void ): void; + registerInitCallback(fieldname: string, callback: () => void): void; + registerFocusCallback(fieldname: string, callback: () => void): void; + registerValidationErrorCallback(fieldname: string, callback: (error: any) => void): void; registerGetValueCallback(fieldname: string, callback: () => any): void; updateControlValue(fieldname: string, value: any): void; registerClientValidator(fieldname: string, validator: SPClientForms.ClientValidation.ValidatorSet): void; - registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void ); + registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void); } } @@ -1653,6 +1512,14 @@ declare module SPClientForms { } } +declare class SPMgr { + NewGroup(listItem: Object, fieldName: string): boolean; + RenderHeader(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema): string; + RenderField(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; + RenderFieldByName(renderCtx: SPClientTemplates.RenderContext, fieldName: string, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; +} + +declare var spMgr: SPMgr; declare module SPAnimation { export enum Attribute { @@ -7241,7 +7108,7 @@ declare module SP { } export class Status { - static addStatus(strTitle: string, strHtml: string, atBegining: boolean): string; + static addStatus(strTitle: string, strHtml?: string, atBegining?: boolean): string; static appendStatus(sid: string, strTitle: string, strHtml: string): string; static updateStatus(sid: string, strHtml: string): void; static setStatusPriColor(sid: string, strColor: string): void; @@ -7378,19 +7245,19 @@ declare module SP { @param url overrides options.url @param callback overrides options.dialogResultValueCallback @param args overrides options.args */ - static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback: SP.UI.DialogReturnValueCallback, args: any): void; + static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback?: SP.UI.DialogReturnValueCallback, args?: any): void; /** Refresh the page if specified dialogResult equals to SP.UI.DialogResult.OK */ static RefreshPage(dialogResult: SP.UI.DialogResult): void; /** Show page specified by the url in a modal dialog. If the dialog returns SP.UI.DialogResult.OK, the page is refreshed. */ static ShowPopupDialog(url: string): void; /** Show modal dialog specified by url, callback, height and width. */ - static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width: number, height: number): void; + static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width?: number, height?: number): void; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel/close button is not shown. */ - static showWaitScreenWithNoClose(title: string, message: string, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenWithNoClose(title: string, message?: string, height?: number, width?: number): SP.UI.ModalDialog; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel button is shown. If user clicks it, the callbackFunc is called. */ - static showWaitScreenSize(title: string, message: string, callbackFunc: SP.UI.DialogReturnValueCallback, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenSize(title: string, message?: string, callbackFunc?: SP.UI.DialogReturnValueCallback, height?: number, width?: number): SP.UI.ModalDialog; static showPlatformFirstRunDialog(url: string, callbackFunc: SP.UI.DialogReturnValueCallback): SP.UI.ModalDialog; - static get_childDialog: any; + static get_childDialog: ModalDialog; /** Closes the dialog using the specified dialog result. */ close(dialogResult: SP.UI.DialogResult): void; } @@ -7469,6 +7336,11 @@ declare module SP { } } + export module Workplace { + export function add_resized(handler: Function); + export function remove_resized(handler:Function); + } + export module UIUtility { export function generateRandomElementId(): string; export function cancelEvent(evt: Event): void; @@ -8410,11 +8282,11 @@ declare module SP.WorkflowServices { /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - get_restrictScope(): string; + get_restrictToScope(): string; /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - set_restrictScope(value: string): string; + set_restrictToScope(value: string): string; /** RestrictToType determines the possible event source type for a workflow subscription that uses this definition. Possible values include "List", "Site", the empty string, or null. */ get_restrictToType(): string; @@ -9441,6 +9313,7 @@ interface ISPClientAutoFillData { AutoFillMenuOptionType?: number; } + declare class SPClientPeoplePicker { static ValueName: string; // = 'Key'; static DisplayTextName: string; // = 'DisplayText'; @@ -9460,54 +9333,112 @@ declare class SPClientPeoplePicker { }; static InitializeStandalonePeoplePicker(clientId: string, value: ISPClientPeoplePickerEntity[], schema: ISPClientPeoplePickerSchema): void; + static ParseUserKeyPaste(userKey: string): string; + static GetTopLevelControl(elmChild: HTMLElement): HTMLElement; + static AugmentEntity(entity: ISPClientPeoplePickerEntity): ISPClientPeoplePickerEntity; + static AugmentEntitySuggestions(pickerObj: SPClientPeoplePicker, allEntities: ISPClientPeoplePickerEntity[], mergeLocal?: boolean): ISPClientPeoplePickerEntity[]; + static PickerObjectFromSubElement(elmSubElement: HTMLElement): SPClientPeoplePicker; + static TestLocalMatch(strSearchLower: string, dataEntity: ISPClientPeoplePickerEntity): boolean; + static BuildUnresolvedEntity(key: string, dispText: string): ISPClientPeoplePickerEntity; + static AddAutoFillMetaData(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[], numOpts: number): ISPClientPeoplePickerEntity[]; + static BuildAutoFillMenuItems(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[]): ISPClientPeoplePickerEntity[]; + static IsUserEntity(entity: ISPClientPeoplePickerEntity): boolean; + static CreateSPPrincipalType(acctStr: string): number; - public TopLevelElementId: string;// '', - public EditorElementId: string;//'', - public AutoFillElementId: string;//'', - public ResolvedListElementId: string;//'', - public InitialHelpTextElementId: string;//'', - public WaitImageId: string;//'', - public HiddenInputId: string;//'', - public AllowEmpty: boolean;//true, - public ForceClaims: boolean;//false, - public AutoFillEnabled: boolean;//true, - public AllowMultipleUsers: boolean;//false, + + public TopLevelElementId: string; // '', + public EditorElementId: string; //'', + public AutoFillElementId: string; //'', + public ResolvedListElementId: string; //'', + public InitialHelpTextElementId: string; //'', + public WaitImageId: string; //'', + public HiddenInputId: string; //'', + public AllowEmpty: boolean; //true, + public ForceClaims: boolean; //false, + public AutoFillEnabled: boolean; //true, + public AllowMultipleUsers: boolean; //false, public OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public UrlZone: string;//null, - public AllUrlZones: boolean;//false, - public SharePointGroupID: number;//0, - public AllowEmailAddresses: boolean;//false, + public UrlZone: SP.UrlZone; //null, + public AllUrlZones: boolean; //false, + public SharePointGroupID: number; //0, + public AllowEmailAddresses: boolean; //false, public PPMRU: SPClientPeoplePickerMRU; - public UseLocalSuggestionCache: boolean;//true, - public CurrentQueryStr: string;//'', - public LatestSearchQueryStr: string;// '', + public UseLocalSuggestionCache: boolean; //true, + public CurrentQueryStr: string; //'', + public LatestSearchQueryStr: string; // '', public InitialSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - public VisibleSuggestions: number;//5, - public PrincipalAccountType: string;//'', + public VisibleSuggestions: number; //5, + public PrincipalAccountType: string; //'', public PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - public EnabledClaimProviders: string;//'', - public SearchPrincipalSource: SP.Utilities.PrincipalSource;//null, - public ResolvePrincipalSource: SP.Utilities.PrincipalSource;//null, - public MaximumEntitySuggestions: number;//30, - public EditorWidthSet: boolean;//false, - public QueryScriptInit: boolean;//false, - public AutoFillControl: string;//null, - public TotalUserCount: number;//0, - public UnresolvedUserCount: number;//0, - public UserQueryDict: ISPClientPeoplePickerEntity; - public ProcessedUserList: ISPClientPeoplePickerEntity; - public HasInputError: boolean;//false, - public HasServerError: boolean;//false, - public ShowUserPresence: boolean;//true, - public TerminatingCharacter: string;//';', - public UnresolvedUserElmIdToReplace: string;//'', - public WebApplicationID: SP.Guid;//'{00000000-0000-0000-0000-000000000000}', - + public EnabledClaimProviders: string; //'', + public SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, + public ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, + public MaximumEntitySuggestions: number; //30, + public EditorWidthSet: boolean; //false, + public QueryScriptInit: boolean; //false, + public AutoFillControl: SPClientAutoFill; //null, + public TotalUserCount: number; //0, + public UnresolvedUserCount: number; //0, + public UserQueryDict: { [index: string]: SP.StringResult }; + public ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; + public HasInputError: boolean; //false, + public HasServerError: boolean; //false, + public ShowUserPresence: boolean; //true, + public TerminatingCharacter: string; //';', + public UnresolvedUserElmIdToReplace: string; //'', + public WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', public GetAllUserInfo(): ISPClientPeoplePickerEntity[]; + + public SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void + public AddUserKeys(userKeys: string, bSearch: boolean): void; + public BatchAddUserKeysOperation(allKeys: string[], numProcessed: number); + public ResolveAllUsers(fnContinuation: () => void): void; + public ExecutePickerQuery(queryIds: string, onSuccess: (queryId: string, result: SP.StringResult) => void, onFailure: (queryId: string, result: SP.StringResult) => void, fnContinuation: () => void): void; + public AddUnresolvedUserFromEditor(bRunQuery?: boolean): void; + public AddUnresolvedUser(unresolvedUserObj: ISPClientPeoplePickerEntity, bRunQuery?: boolean): void; + public UpdateUnresolvedUser(results: SP.StringResult, user: ISPClientPeoplePickerEntity): void; + public AddPickerSearchQuery(queryStr: string): string; + public AddPickerResolveQuery(queryStr: string): string; + public GetPeoplePickerQueryParameters(): SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters; + public AddProcessedUser(userObject: ISPClientPeoplePickerEntity, fResolved?: boolean): string; + public DeleteProcessedUser(elmToRemove: HTMLElement): void; + public OnControlValueChanged(): void; + public OnControlResolvedUserChanged(): void; + public EnsureAutoFillControl(): void; + public ShowAutoFill(resultsTable: ISPClientAutoFillData[]): void; + public FocusAutoFill(): void; + public BlurAutoFill(): void; + public IsAutoFillOpen(): boolean; + public EnsureEditorWidth(): void; + public SetFocusOnEditorEnd(): void; + public ToggleWaitImageDisplay(bShowImage?: boolean): void; + public SaveAllUserKeysToHiddenInput(): void; + public GetCurrentEditorValue(): string; + public GetControlValueAsJSObject(): ISPClientPeoplePickerEntity[]; + public GetAllUserKeys(): string; + public GetControlValueAsText(): string; + public IsEmpty(): boolean; + public IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; + public HasResolvedUsers(): boolean; + public Validate(): void; + public ValidateCurrentState(): void + public GetUnresolvedEntityErrorMessage(): string; + public ShowErrorMessage(msg: string): void; + public ClearServerError(): void; + public SetServerError(): void; + public OnControlValidate(): void; + public SetEnabledState(bEnabled: boolean): void; + public DisplayLocalSuggestions(): void; + public CompileLocalSuggestions(input: string): void; + public PlanningGlobalSearch(): boolean; + public AddLoadingSuggestionMenuOption(): void; + public ShowingLocalSuggestions(): boolean; + public ShouldUsePPMRU(): boolean; + public AddResolvedUserToLocalCache(resolvedEntity: ISPClientPeoplePickerEntity, resolveText: string); } interface ISPClientPeoplePickerSchema { @@ -9583,11 +9514,38 @@ interface ISPClientPeoplePickerEntity { Department: string; Email: string; }; - MultipleMatches: Object[]; + MultipleMatches: ISPClientPeoplePickerEntity[]; DomainText?: string; [key: string]: any; } +declare class SPClientPeoplePickerProcessedUser { + UserContainerElementId: string;// '', + DisplayElementId: string;// '', + PresenceElementId: string;// '', + DeleteUserElementId: string;// '', + SID: string;// '', + DisplayName: string;// '', + SIPAddress: string;// '', + UserInfo: ISPClientPeoplePickerEntity;// null, + ResolvedUser: boolean;// true, + Suggestions: ISPClientAutoFillData[];// null, + ErrorDescription: string;// '', + ResolveText: string;// '', + public UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; + public UpdateSuggestions(entity: ISPClientPeoplePickerEntity); + public BuildUserHTML(): string; + public UpdateUserMaxWidth(): void; + public ResolvedAsUnverifiedEmail(): string; + + static BuildUserPresenceHtml(elmId: string, strSip: string, bResolved?: boolean): string; + static GetUserContainerElement(elmChild: HTMLElement): HTMLElement; + static HandleProcessedUserClick(ndClicked: HTMLElement): void; + static DeleteProcessedUser(elmToRemove: HTMLElement): void; + static HandleDeleteProcessedUserKey(e: Event): void; + static HandleResolveProcessedUserKey(e: Event): void; +} + declare module Microsoft { export module Office { export module Server { @@ -9757,4 +9715,1234 @@ declare module SPThemeUtils { export function Suspend(): void; } +declare module SP { + export module JsGrid { + export enum TextDirection { + Default, //0, + RightToLeft, //1, + LeftToRight //2 + } + + export enum PaneId { + MainGrid, //0, + PivotedGrid, //1, + Gantt //2 + } + + export enum PaneLayout { + GridOnly, //0, + GridAndGantt, //1, + GridAndPivotedGrid //2 + + } + export enum EditMode { + ReadOnly, //0, + ReadWrite, //1, + ReadOnlyDefer, //2, + ReadWriteDefer, //3, + Defer //4 + } + + export enum GanttDrawBarFlags { + LeftLink, //0x01, + RightLink //0x02 + + } + export enum GanttBarDateType { + Start, //0, + End //1 + } + + export enum ValidationState { + Valid, //0, + Pending, //1, + Invalid //2 + } + + export enum HierarchyMode { + None, //0, + Standard, //1, + Grouping //2 + } + + export enum EditActorWriteType { + Both, //1, + LocalizedOnly, //2, + DataOnly, //3, + Either //4 + } + + export enum EditActorReadType { + Both, //1, + LocalizedOnly, //2, + DataOnly //3 + } + + export enum EditActorUpdateType { + Committed, //0, + Uncommitted, //1 + } + + export enum SortMode { + Ascending, //1, + Descending, //-1, + None //0 + } + + export module RowHeaderStyleId { + export var Transfer: string; //'Transfer', + export var Conflict: string; //'Conflict' + + } + + export module RowHeaderAutoStyleId { + export var Dirty:string; //'Dirty', + export var Error: string; //'Error', + export var NewRow: string; //'NewRow' + } + + export enum RowHeaderStatePriorities { + Dirty, //10, + Transfer, //30, + CellError, //40, + Conflict, //50, + RowError, //60, + NewRow //90 + } + + export enum UpdateSerializeMode { + Cancel, //0, + Default, //1, + PropDataOnly, //2, + PropLocalizedOnly, //3, + PropBoth //4 + } + + export enum UpdateTrackingMode { + PropData, //2, + PropLocalized, //3, + PropBoth //4 + } + + export module UserAction { + export var UserEdit:string; //'User Edit':string; + export var DeleteRecord:string; //'Delete Record':string; + export var InsertRecord:string; //'Insert Record':string; + export var Indent:string; //'Indent':string; + export var Outdent:string; //'Outdent':string; + export var Fill:string; //'Fill':string; + export var Paste:string; //'Paste':string; + export var CutPaste: string; //'Cut/Paste' + } + + export enum ReadOnlyActiveState { + ReadOnlyActive, //0, + ReadOnlyDisabled, //1 + } + + export interface IValue { + data?: any; + localized?:string; + } + + + export class JsGridControl { + constructor(parentNode: HTMLElement, bShowLoadingBanner: boolean); + /** Returns true if Init method has been executed successfully */ + IsInitialized(): boolean; + /** Replaces the control TableCache object with the provided one */ + ResetData(cache: SP.JsGrid.TableCache): void; + /** Initialize the control */ + Init(parameters: SP.JsGrid.JsGridControl.Parameters): void; + Cleanup(): void; + /** Removes all event handlers and markup associated with the control */ + Dispose(): void; + + // todo + NotifyDataAvailable(): void; + NotifySave(): void; + NotifyHide(): void; + NotifyResize(): void; + ClearTableView(): void; + HideInitialLoadingBanner(): void; + ShowInitialGridErrorMsg(errorMsg: string): void; + ShowGridErrorMsg(errorMsg: string): void; + LaunchPrintView(additionalScriptFiles, beforeInitFnName, beforeInitFnArgsObj, title, bEnableGantt, optGanttDelegateNames, optInitTableViewParamsFnName, optInitTableViewParamsFnArgsObj, optInitGanttStylesFnName, optInitGanttStylesFnArgsObj): void; + GetAllDataJson(fnOnFinished, optFnGetCellStyleID?): void; + SetTableView(tableViewParams): void; + SetRowView(rowViewParams): void; + + /** Enable grid after Disable. */ + Enable(): void; + /** Covers the grid with the semi-transparent panel, preventing any operations with it. + Additionally, displays loading animated gif and optMsg as the message next to it. + If optMsg is not specified, displays "Loading..." text. */ + Disable(optMsg?: string): void; + /** Enables grid editing */ + EnableEditing(): void; + /** Disables grid editing: all the records become readonly */ + DisableEditing(): void; + /** Switches the currently selected cell into edit mode: displays edit control and sets focus into it. + Returns true if success. */ + TryBeginEdit(): boolean; + FinalizeEditing(fnContinue, fnError): void; + /** Get diff tracker object that tracks changes to the grid data. */ + GetDiffTracker(): SP.JsGrid.Internal.DiffTracker; + /** Moves focus to the JsGrid control */ + Focus(): void; + + /** Try saving the new record row (aka entry row) if it was edited. */ + TryCommitFirstEntryRecords(fnCommitComplete: { (): void }): void; + /** Removes all new record rows (aka entry rows), including unsaved and even empty ones. + The latter seems to be a bug, as I haven't found any easy way to restore the empty entry row. */ + ClearUncommitedEntryRecords(): void; + /** Returns true if there are any unsaved new record rows (aka entry rows). */ + AnyUncommitedEntryRecords(): boolean; + + + // todo + AnyUncomittedProvisionalRecords(): boolean; + + /** Gets record based on the recordKey + @recordKey internal unique id of a row. You can get recordKey from view index via GetRecordKeyByViewIndex method. */ + GetRecord(recordKey: number): IRecord; + /** Get entry record with the specified key. + Entry record is a special type of record because it represents a new record that doesn't exist yet. */ + GetEntryRecord(key): any; + /** Determine if the specified record key identifies valid entry row. */ + IsEntryRecord(recordKey: number): boolean; + /** Determine whether the specified cell is editable. */ + IsCellEditable(record: IRecord, fieldKey: string, optPaneId?): boolean; + /** Adds one of builtin row state indicator icons into the row header. + Please pass one of the values of SP.JsGrid.RowHeaderStyleId + Row header is the leftmost gray column of the table. */ + AddBuiltInRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + /** Adds the specified state into the row header. + There can be several row header states for one row. Only one is shown (according to the Priority). + Row header is the leftmost gray column of the table. */ + AddRowHeaderState(recordKey: number, rowHeaderState: SP.JsGrid.RowHeaderState): void; + /** Removes header state with specified id from the row. */ + RemoveRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + + GetCheckSelectionManager(): any; + UpdateProperties(propertyUpdates, changeName, optChangeKey?): any; + GetLastRecordKey(): string; + InsertProvisionalRecordBefore(beforeRecordKey: number, newRecord, initialValues): any; + InsertProvisionalRecordAfter(afterRecordKey: number, newRecord, initialValues): any; + IsProvisionalRecordKey(recordKey: number): boolean; + InsertRecordBefore(beforeRecordKey: number, newRecord, optChangeKey?): any; + InsertRecordAfter(afterRecordKey: number, newRecord, optChangeKey?): any; + InsertHiddenRecord(recordKey: number, changeKey, optAfterRecordKey?): any; + DeleteRecords(recordKeys, optChangeKey?): any; + IndentRecords(recordKeys, optChangeKey?): any; + OutdentRecords(recordKeys, optChangeKey?): any; + ReorderRecords(beginRecordKey: number, endRecordKey: number, afterRecordKey: number, bSelectAfterwards: boolean): any; + GetContiguousRowSelectionWithoutEntryRecords(): { begin; end; keys }; + CanMoveRecordsUpByOne(recordKeys): boolean; + CanMoveRecordsDownByOne(recordKeys): boolean; + MoveRecordsUpByOne(recordKeys): any; + MoveRecordsDownByOne(recordKeys): any; + GetReorderRange(recordKeys): any; + GetNodeExpandCollapseState(recordKey): any; + ToggleExpandCollapse(recordKey: number): void; + + /** Attach event handler to a particular event type */ + AttachEvent(eventType: JsGrid.EventType, fnOnEvent: { (args: IEventArgs): void }): void; + /** Detach a previously set event handler */ + DetachEvent(eventType: JsGrid.EventType, fnOnEvent): void; + + /** Set a delegate. Delegates are way to replace default functionality with custom one. */ + SetDelegate(delegateKey: JsGrid.DelegateType, fn): void; + /** Get current delegate. */ + GetDelegate(delegateKey: JsGrid.DelegateType): any; + + /** Re-render the specified row in the view. */ + RefreshRow(recordKey: number): void; + /** Re-render all rows in the view. + It can be used e.g. if you have some custom display controls and they are rendered differently depending on some external settings. + In this case, if you update the external settings, obviously you have to then update the view for these settings to take effect. */ + RefreshAllRows(): void; + /** Clears undo queue, and also differencies tracker state and versions manager state. */ + ClearChanges(): void; + + GetGanttZoomLevel(): any; + SetGanttZoomLevel(level: any): void; + ScrollGanttToDate(date): void; + + /** Get top record view index. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRecordIndex(): number; + /** Get number of rows displayed in the current view. */ + GetViewRecordCount(): number; + /** Get record key for a row that is specified by the viewIdx. + viewIdx - index of the row in the view, use GetTopRecordIndex to get the first one. + Returns recordKey, which is a unique numeric identifier of a row within a dataset. + Main difference between viewIdx and recordKey is that viewIdx is only unique within a view, + e.g. if you do paging, it can be same for different records. + */ + GetRecordKeyByViewIndex(viewIdx: number): number; + /** Opposite to GetRecordKeyByViewIndex, resolves the view index of the record based on record key. + recordKey - unique numeric identifier of a row in the current dataset. + Returns viewIdx - index of the row in the current view */ + GetViewIndexOfRecord(recordKey: number): number; + /** Get top row index. Usually returns 0. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRowIndex(): number; + + GetOutlineLevel(record): any; + GetSplitterPosition(): any; + SetSplitterPosition(pos): void; + GetLeftColumnIndex(optPaneId?): any; + EnsurePaneWidth(): void; + + /** Show a previously hidden column at a specified position. + If atIdx is not defined, column will be shown at it's previous position. */ + ShowColumn(columnKey: string, atIdx?: number): void; + /** Hide the specified column from grid */ + HideColumn(columnKey: string): void; + /** Update column descriptions */ + UpdateColumns(columnInfoCollection: ColumnInfoCollection): void; + GetColumns(optPaneId?): ColumnInfo[]; + /** Get ColumnInfo object by fieldKey + @fieldKey when working with SharePoint data sources, fieldKey corresponds to field internal name */ + GetColumnByFieldKey(fieldKey: string, optPaneId?): ColumnInfo; + /** Adds a column, based on the specified grid field */ + AddColumn(columnInfo: ColumnInfo, gridField: GridField): void; + + /** Switches column header in rename mode, showing textbox and thus giving the user possibility to rename this column. */ + RenameColumn(columnKey: string): void; + /** Shows a dialog where user can reorder columns and change their widths. */ + ShowColumnConfigurationDialog(): void; + + + /** Returns true, if there are any errors in the JsGrid */ + AnyErrors(): boolean; + /** Returns true, if there are any errors in a specified row */ + AnyErrorsInRecord(recordKey: number): boolean; + /** Set error for the specified by recordKey and fieldKey cell. + Returns id of the error, so that later you can clear the error using this id. */ + SetCellError(recordKey: number, fieldKey: string, errorMessage: string): number; + /** Set error for the specified by recordKey row. + In the leftmost column of this row, exclamation mark error indicator will appear. + Clicking on this indicator will cause the specified error message appear in form of a reddish tooltip. + Returns id of the error, so that later you can clear the error using this id. */ + SetRowError(recordKey: number, errorMessage: string): number; + /** Clear specified by id error that was previously set on the specified by recordKey and fieldKey cell. */ + ClearCellError(recordKey: number, fieldKey: string, id: number): void; + /** Clear all errors in the specified cell. */ + ClearAllErrorsOnCell(recordKey: number, fieldKey: string): void; + /** Clear specified by id error that was previously set on the specified by recordKey row. */ + ClearRowError(recordKey: number, id: number): void; + /** Clear all errors in the specified row. */ + ClearAllErrorsOnRow(recordKey: number): void; + /** Get error message for the specified cell. + If many errors are set on the cell, only first is returned. + If there are no errors in the cell, returns null. */ + GetCellErrorMessage(recordKey: number, fieldKey: string): string; + /** Get error message for the specified row. + If many errors are set on the row, only first is returned. + If there are no errors in the row, returns null. */ + GetRowErrorMessage(recordKey: number): string; + /** This method is used mostly when you have a rather tall JSGrid and you want to ensure that user sees + that some error has occured. + You can specify the minId or/and filter function. + If minId is specified, method searches for an error with first id which is greater than minId. + Scrolls to the Returns the id of the found record. + If there aren't any errors, that satisfy the conditions, method does nothing and returns null. */ + ScrollToAndExpandNextError(minId?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }): any; + /** Same as ScrollToAndExpandNextError, but searches within the specified record. + recordKey should be not null, otherwise you'll get an exception. + bDontExpand controls whether the error tooltip will be shown (if bDontExpand=true, tooltip will not be shown). */ + ScrollToAndExpandNextErrorOnRecord(minId?: number, recordKey?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }, bDontExpand?: boolean): any; + + GetFocusedItem(): any; + SendKeyDownEvent(eventInfo:Sys.UI.DomEvent): any; + /** Moves cursor to entry record (the row that is used to add new records) */ + JumpToEntryRecord(): void; + + SelectRowRange(rowIdx1, rowIdx2, bAppend, optPaneId?): void; + SelectColumnRange(colIdx1, colIdx2, bAppend, optPaneId?): void; + SelectCellRange(rowIdx1, rowIdx2, colIdx1, colIdx2, bAppend, optPaneId): void; + SelectRowRangeByKey(rowKey1, rowKey2, bAppend, optPaneId?): void; + SelectColumnRangeByKey(colKey1, colKey2, bAppend, optPaneId?): void; + SelectCellRangeByKey(recordKey1: string, recordKey2: string, colKey1, colKey2, bAppend, optPaneId?): void; + + ChangeKeys(oldKey, newKey): void; + GetSelectedRowRanges(optPaneId?): any; + GetSelectedColumnRanges(optPaneId?): any; + GetSelectedRanges(optPaneId?): any; + MarkPropUpdateInvalid(recordKey: number, fieldKey, changeKey, optErrorMsg?): any; + GetCurrentChangeKey(): any; + CreateAndSynchronizeToNewChangeKey(): any; + CreateDataUpdateCmd(bUseCustomInitialUpdate: boolean): any; + IsChangeKeyApplied(changeKey): any; + GetChangeKeyForVersion(version): any; + TryReadPropForChangeKey(recordKey: number, fieldKey, changeKey): any; + GetUnfilteredHierarchyMap(): any; + GetHierarchyState(bDecompressGuidKeys: boolean): any; + IsGroupingRecordKey(recordKey: number): boolean; + IsGroupingColumnKey(recordKey: number): boolean; + GetSelectedRecordKeys(bDuplicatesAllowed: boolean): any; + /** Cut data from currently selected cells into the clipboard. + Will not work if current selection contains entry row or readonly cells. */ + CutToClipboard(): void; + /** Copy data from currently selected cells into the clipboard. */ + CopyToClipboard(): void; + /** Paste data from clipboard into currently selected cells. */ + PasteFromClipboard(): void; + TryRestoreFocusAfterInsertOrDeleteColumns(origFocus): void; + /** Get undo manager for performing undo/redo operations programmatically. */ + GetUndoManager(): SP.JsGrid.CommandManager; + /** Gets number of records visible in the current view, including the entry row. */ + GetVisibleRecordCount(): number; + /** Returns index of the system RecordIndicatorCheckBoxColumn. If not present in the view, returns null. */ + GetRecordIndicatorCheckBoxColumnIndex(): number; + /** Determines if the specified record is visible in the current view. */ + IsRecordVisibleInView(recordKey: number): boolean; + GetHierarchyQueryObject(): any; + GetSpCsrRenderCtx(): any; + } + + export interface IChangeKey { + Reserve(): void; + Release(): void; + GetVersionNumber(): number; + CompareTo(changeKey: IChangeKey): number; + } + + export enum EventType { + OnCellFocusChanged, + OnRowFocusChanged, + OnCellEditBegin, + OnCellEditCompleted, + OnRightClick, + OnPropertyChanged, + OnRecordInserted, + OnRecordDeleted, + OnRecordChecked, + OnCellErrorStateChanged, + OnEntryRecordAdded, + OnEntryRecordCommitted, + OnEntryRecordPropertyChanged, + OnRowErrorStateChanged, + OnDoubleClick, + OnBeforeGridDispose, + OnSingleCellClick, + OnInitialChangesForChangeKeyComplete, + OnVacateChange, + OnGridErrorStateChanged, + OnSingleCellKeyDown, + OnRecordsReordered, + OnBeforePropertyChanged, + OnRowEscape, + OnBeginRenameColumn, + OnEndRenameColumn, + OnPasteBegin, + OnPasteEnd, + OnBeginRedoDataUpdateChange, + OnBeginUndoDataUpdateChange + } + + export enum DelegateType { + ExpandColumnMenu, + AddColumnMenuItems, + Sort, + Filter, + InsertRecord, + DeleteRecords, + IndentRecords, + OutdentRecords, + IsRecordInsertInView, + ExpandDelayLoadedHierarchyNode, + AutoFilter, + ExpandConflictResolution, + GetAutoFilterEntries, + LaunchFilterDialog, + ShowColumnConfigurationDialog, + GetRecordEditMode, + GetGridRowStyleId, + CreateEntryRecord, + TryInsertEntryRecord, + WillAddColumnMenuItems, + NextPage, + AddNewColumn, + RemoveColumnFromView, + ReorderColumnPositionInView, + TryCreateProvisionalRecord, + CanReorderRecords, + AddNewColumnMenuItems, + TryBeginPaste, + AllowSelectionChange, + GetFieldEditMode, + GetFieldReadOnlyActiveState, + OnBeforeRecordReordered + } + + export enum ClickContext { + SelectAllSquare, + RowHeader, + ColumnHeader, + Cell, + Gantt, + Other + } + + export class RowHeaderState { + constructor(id: string, img: SP.JsGrid.Image, priority: SP.JsGrid.RowHeaderStatePriorities, tooltip: string, fnOnClick: { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }); + GetId(): string; + GetImg(): SP.JsGrid.Image; + GetPriority(): SP.JsGrid.RowHeaderStatePriorities; + GetOnClick(): { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }; + GetTooltip(): string; + toString(): string; + } + + export class Image { + /** optOuterCssNames and optImgCssNames are strings that contain css class names separated by spaces. + optImgCssNames are applied to the img tag. + if bIsClustered, image is rendered inside div, and optOuterCssNames are applied to the div. */ + constructor(imgSrc: string, bIsClustered: boolean, optOuterCssNames: string, optImgCssNames: string, bIsAnimated: boolean); + imgSrc: string; + bIsClustered: boolean; + optOuterCssNames: string; + imgCssNames: string; + bIsAnimated: boolean; + /** Renders the image with specified alternative text and on-click handler. + If bHideTooltip == false, then alternative text is also shown as the tooltip (title attribute). */ + Render(altText: string, clickFn: { (eventInfo:Sys.UI.DomEvent): void }, bHideTooltip: boolean): HTMLElement; + } + + export interface IEventArgs { } + export module EventArgs { + export class OnEntryRecordAdded implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + + export class CellFocusChanged implements IEventArgs { + constructor(newRecordKey: number, newFieldKey: string, oldRecordKey: number, oldFieldKey: string); + newRecordKey: number; + newFieldKey: string; + oldRecordKey: number; + oldFieldKey: string; + } + export class RowFocusChanged implements IEventArgs { + constructor(newRecordKey: number, oldRecordKey: number); + newRecordKey: number; + oldRecordKey: number; + } + export class CellEditBegin implements IEventArgs { + constructor(recordKey: number, fieldKey: string); + recordKey: number; + fieldKey: string; + } + export class CellEditCompleted implements IEventArgs { + constructor(recordKey: number, fieldKey: string, changeKey: JsGrid.IChangeKey, bCancelled: boolean); + recordKey: number; + fieldKey: string; + changeKey: JsGrid.IChangeKey; + bCancelled: boolean; + } + export class Click implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, context: JsGrid.ClickContext, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + context: JsGrid.ClickContext; + recordKey: number; + fieldKey: string; + } + export class PropertyChanged implements IEventArgs { + constructor(recordKey: number, fieldKey: string, oldProp: SP.JsGrid.Internal.PropertyUpdate, newProp: SP.JsGrid.Internal.PropertyUpdate, propType: SP.JsGrid.IPropertyType, changeKey: SP.JsGrid.IChangeKey, validationState: SP.JsGrid.ValidationState); + recordKey: number; + fieldKey: string; + oldProp: SP.JsGrid.Internal.PropertyUpdate; + newProp: SP.JsGrid.Internal.PropertyUpdate; + propType: SP.JsGrid.IPropertyType; + changeKey: SP.JsGrid.IChangeKey; + validationState: SP.JsGrid.ValidationState; + } + export class RecordInserted implements IEventArgs { + constructor(recordKey, recordIdx, afterRecordKey, changeKey); + recordKey: number; + recordIdx: number; + afterRecordKey: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordDeleted implements IEventArgs { + constructor(recordKey, recordIdx, changeKey); + recordKey: number; + recordIdx: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordChecked implements IEventArgs { + constructor(recordKeySet: SP.Utilities.Set, bChecked: boolean); + recordKeySet: SP.Utilities.Set; + bChecked: boolean; + } + export class OnCellErrorStateChanged implements IEventArgs { + constructor(recordKey, fieldKey, bAddingError, bCellCurrentlyHasError, bCellHadError, errorId); + recordKey: number; + fieldKey: string; + bAddingError: boolean; + bCellCurrentlyHasError: boolean; + bCellHadError: boolean; + errorId: number; + } + export class OnRowErrorStateChanged implements IEventArgs { + constructor(recordKey, bAddingError, bErrorCurrentlyInRow, bRowHadError, errorId, message); + recordKey: number; + bAddingError: boolean; + bErrorCurrentlyInRow: boolean; + bRowHadError: boolean; + errorId: number; + message: string; + } + export class OnEntryRecordCommitted implements IEventArgs { + constructor(origRecKey: string, recordKey: number, changeKey: JsGrid.IChangeKey); + originalRecordKey: number; + recordKey: number; + changeKey: JsGrid.IChangeKey + } + export class SingleCellClick implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class PendingChangeKeyInitiallyComplete implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class VacateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class GridErrorStateChanged implements IEventArgs { + constructor(bAnyErrors: boolean); + bAnyErrors: boolean; + } + export class SingleCellKeyDown implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class OnRecordsReordered implements IEventArgs { + constructor(recordKeys: string[], changeKey: JsGrid.IChangeKey); + reorderedKeys: string[]; + changeKey: JsGrid.IChangeKey; + } + export class OnRowEscape implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + export class OnEndRenameColumn implements IEventArgs { + constructor(columnKey: string, originalColumnTitle: string, newColumnTitle: string); + columnKey: string; + originalColumnTitle: string; + newColumnTitle: string; + } + export class OnBeginRedoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class OnBeginUndoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + + } + + export module JsGridControl { + export class Parameters { + tableCache: SP.JsGrid.TableCache; + name: any; // TODO + bNotificationsEnabled: boolean; + styleManager: IStyleManager; + minHeaderHeight: number; + minRowHeight: number; + commandMgr: SP.JsGrid.CommandManager; + enabledRowHeaderAutoStates: SP.Utilities.Set; + } + } + + export class CommandManager { + // todo + } + + export class TableCache { + // todo + } + + export interface IStyleManager { + gridPaneStyle: IStyleType.GridPane; + columnHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + rowHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + splitterStyleCollection: { + normal: IStyleType.Splitter; + normalHandle: IStyleType.SplitterHandle; + hover: IStyleType.Splitter; + hoverHandle: IStyleType.SplitterHandle; + dra: IStyleType.Splitter; + dragHandle: IStyleType.SplitterHandle; + }; + defaultCellStyle: IStyleType.Cell; + readOnlyCellStyle: IStyleType.Cell; + readOnlyFocusedCellStyle: IStyleType.Cell; + timescaleTierStyle: IStyleType.TimescaleTier; + groupingStyles: any[]; + widgetDockStyle: IStyleType.Widget; + widgetDockHoverStyle: IStyleType.Widget; + widgetDockPressedStyle: IStyleType.Widget; + RegisterCellStyle(styleId: string, cellStyle: IStyleType.Cell): void; + GetCellStyle(styleId: string): IStyleType.Cell; + UpdateSplitterStyleFromCss(styleObject: IStyleType.Splitter, splitterStyleNameCollection): void; + UpdateHeaderStyleFromCss(styleObject: IStyleType.Header, headerStyleNameCol): void; + UpdateGridPaneStyleFromCss(styleObject: IStyleType.GridPane, gridStyleNameCollection): void; + UpdateDefaultCellStyleFromCss(styleObject: IStyleType.Cell, cssClass): void; + UpdateGroupStylesFromCss(styleObject, prefix): void; + } + + export interface IStyleType { } + export module IStyleType { + export interface Splitter extends IStyleType { + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + } + export interface SplitterHandle extends IStyleType{ + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + gripUpperColor: any; + gripLowerColor: any; + } + export interface GridPane { + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + backgroundColor: any; + columnDropIndicatorColor: any; + rowDropIndicatorColor: any; + linkColor: any; + visitedLinkColor: any; + copyRectForeBorderColor: any; + copyRectBackBorderColor: any; + focusRectBorderColor: any; + selectionRectBorderColor: any; + selectedCellBgColor: any; + readonlySelectionRectBorderColor: any; + changeHighlightCellBgColor: any; + fillRectBorderColor: any; + errorRectBorderColor: any; + } + export interface Header { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + eyeBrowBorderColor: any; + eyeBrowColor: any; + menuColor: any; + menuBorderColor: any; + resizeColor: any; + resizeBorderColor: any; + menuHoverColor: any; + menuHoverBorderColor: any; + resizeHoverColor: any; + resizeHoverBorderColor: any; + eyeBrowHoverColor: any; + eyeBrowHoverBorderColor: any; + elementClickColor: any; + elementClickBorderColor: any; + } + export interface Cell extends IStyleType { + /** -> CSS font-family */ + font: any; + /** -> CSS font-size */ + fontSize: any; + /** -> CSS font-weight */ + fontWeight: any; + /** -> CSS font-style */ + fontStyle: any; + /** -> CSS color */ + textColor: any; + /** -> CSS background-color */ + backgroundColor: any; + /** -> CSS text-align */ + textAlign: any; + } + export interface Widget { + backgroundColor: any; + borderColor: any; + } + export interface RowHeaderStyle { + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + } + export interface TimescaleTier { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + outerBorderColor: any; + todayLineColor: any; + } + } + + export class Style { + + static Type: { + Splitter: IStyleType.Splitter; + SplitterHandle: IStyleType.SplitterHandle; + GridPane: IStyleType.GridPane; + Header: IStyleType.Header; + RowHeaderStyle: IStyleType.RowHeaderStyle; + TimescaleTier: IStyleType.TimescaleTier; + Cell: IStyleType.Cell; + Widget: IStyleType.Widget; + }; + + static SetRTL: { (rtlObject): void; }; + static MakeJsGridStyleManager: { (): IStyleManager }; + static CreateStyleFromCss: { (styleType: IStyleType, cssStyleName: string, optExistingStyle, optClassId): any; }; + static CreateStyle: { (styleType: IStyleType, styleProps: any): any; }; + static MergeCellStyles: { (majorStyle, minorStyle): any; }; + static ApplyCellStyle: { (td, style): void; }; + static ApplyRowHeaderStyle: { (domObj, style, fnGetHeaderSibling): void; }; + static ApplyCornerHeaderBorderStyle: { (domObj, colStyle, rowStyle): void; }; + static ApplyHeaderInnerBorderStyle: { (domObj, bIsRowHeader, headerObject): void }; + static ApplyColumnContextMenuStyle: { (domObj, style): void }; + static ApplySplitterStyle: { (domObj, style): void }; + static MakeBorderString: { (width: number, style: string, color: string): string }; + static GetCellStyleDefaultBackgroundColor: { (): string }; + + } + + export class ColumnInfoCollection { + constructor(colInfoArray: any[]); + GetColumnByKey(key: string): any; + GetColumnArray(bVisibleOnly?: boolean): any[]; + GetColumnMap(): { [key: string]: any; }; + AppendColumn(colInfo: any): void; + InsertColumnAt(idx: number, colInfo: any): void; + RemoveColumn(key: string): void; + /** Returns null if the specified column is not found or hidden. */ + GetColumnPosition(key: string): number; + } + + export class ColumnInfo { + constructor(name: string, imgSrc: string, key: string, width: number); + /** Column title */ + name: string; + /** Column image URL. + If not null, the column header cell will show the image instead of title text. + If the title is defined at the same time as the imgSrc, the title will be shown as a tooltip. */ + imgSrc: string; + /** Custom image HTML. + If you define this in addition to the imgSrc attribute, then instead of standard img tag + the custom HTML defined by this field will be used. */ + imgRawSrc: string; + /** Column identifier */ + columnKey: string; + /** Field keys of the fields, that are displayed in this column */ + fieldKeys: string[]; + /** Width of the column */ + width: number; + bOpenMenuOnContentClick: boolean; + /** always returns 'column' */ + ColumnType(): string; + /** true by default */ + isVisible: boolean; + /** true by default */ + isHidable: boolean; + /** true by default */ + isResizable: boolean; + /** true by default */ + isSortable: boolean; + /** true by default */ + isAutoFilterable: boolean; + /** false by default */ + isFooter: boolean; + /** determine whether the cells in this column should be clickable */ + fnShouldLinkSingleValue: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): boolean }; + /** if a particular cell is determined as clickable by fnShouldLinkSingleValue, this function will be called when the cell is clicked */ + fnSingleValueClicked: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): void }; + /** this is used when you need to make some of the cells in the column readonly, but at the same time keep others editable */ + fnGetCellEditMode: { (record: IRecord, fieldKey: string): JsGrid.EditMode }; + /** this function should return name of the display control for the given cell in the column + the name should be previously associated with the display control via SP.JsGrid.PropertyType.Utils.RegisterDisplayControl method */ + fnGetDisplayControlName: { (record: IRecord, fieldKey: string): string }; + /** this function should return name of the edit control for the given cell in the column + the name should be previously associated with the edit control via SP.JsGrid.PropertyType.Utils.RegisterEditControl method */ + fnGetEditControlName: { (record: IRecord, fieldKey: string): string }; + /** set widget control names for a particular cell + widgets are basically in-cell buttons with associated popup controls, e.g. date selector or address book button + standard widget ids are defined in the SP.JsGrid.WidgetControl.Type enumeration + it is also possible to create your own widgets + usually this function is not used, and instead, widget control names are determined via PropertyType + */ + fnGetWidgetControlNames: { (record: IRecord, fieldKey: string): string[] }; + /** this function should return id of the style for the given cell in the column + styles and their ids are registered for a JsGridControl via jsGridParams.styleManager.RegisterCellStyle method */ + fnGetCellStyleId: { (record: IRecord, fieldKey: string, dataValue: any): string }; + /** set custom tooltip for the given cell in the column. by default, localized value is displayed as the tooltip */ + fnGetSingleValueTooltip: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): string }; + } + + + export interface IRecord { + /** True if this is an entry row */ + bIsNewRow: boolean; + + /** Please use SetProp and GetProp */ + properties: { [fieldKey: string]: IPropertyBase }; + + /** returns recordKey */ + key(): number; + /** returns raw data value for the specified field */ + GetDataValue(fieldKey: string): any; + /** returns localized text value for the specified field */ + GetLocalizedValue(fieldKey: string): string; + /** returns true if data value for the specified field is available */ + HasDataValue(fieldKey: string): boolean; + /** returns true if localized text value for the specified field is available */ + HasLocalizedValue(fieldKey: string): boolean; + + GetProp(fieldKey: string): IPropertyBase; + SetProp(fieldKey: string, prop: IPropertyBase): void; + + /** Update the specified field with the specified value */ + AddFieldValue(fieldKey: string, value: any): void; + /** Removes value of the specified field. + Does not refresh the view. */ + RemoveFieldValue(fieldKey: string): void; + } + + + export class RecordFactory { + constructor(gridFieldMap: any, keyColumnName: string, fnGetPropType: any); + gridFieldMap: any; + /** Create a new record */ + MakeRecord(dataPropMap, localizedPropMap, bKeepRawData): IRecord; + } + + export interface IPropertyBase { + HasLocalizedValue(): boolean; + HasDataValue(): boolean; + Clone(): IPropertyBase; + /** dataValue actually is cloned */ + Update(dataValue: any, localizedValue: string): void; + GetLocalized(): string; + GetData(): any; + } + + export class Property { + static MakeProperty(dataValue: any, localizedValue: string, bHasDataValue: boolean, bHasLocalizedValue: boolean, propType): IPropertyBase; + static MakePropertyFromGridField(gridField: any, dataValue: any, localizedVal: string, optPropType?): IPropertyBase; + } + + export class GridField { + constructor(key: string, hasDataValue: boolean, hasLocalizedValue: boolean, textDirection, defaultCellStyleId, editMode, dateOnly, csrInfo); + key: string; + hasDataValue: boolean; + hasLocalizedValue: boolean; + textDirection: any; + dateOnly: boolean; + csrInfo: any; + GetEditMode(): any; + SetEditMode(mode: any): void; + GetDefaultCellStyleId(): any; + CompareSingleDataEqual(dataValue1, dataValue2): boolean; + GetPropType(): any; + GetSingleValuePropType(): any; + GetMultiValuePropType(): any; + SetSingleValuePropType(svPropType: any): void; + SetIsMultiValue(listSeparator: any): void; + GetIsMultiValue(): boolean; + } + + export interface IEditActorGridContext { + jsGridObj: JsGridControl; + parentNode: HTMLElement; + styleManager: IStyleManager; + RTL: any; + emptyValue: any; + bLightFocus: boolean; + OnKeyDown: { (domEvent: Sys.UI.DomEvent): void; }; + } + + export interface IEditControlGridContext extends IEditActorGridContext { + OnActivateActor(): void; + OnDeactivateActor():void; + } + + export interface IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + } + + export interface ILookupPropertyType extends IPropertyType { + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + } + + export interface IMultiValuePropertyType extends IPropertyType { + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + + export class PropertyType { + /** Lookup property type factory, based on SP.JsGrid.PropertyType.LookupTable class. + displayCtrlName should be one of the following: SP.JsGrid.DisplayControl.Type.Image, SP.JsGrid.DisplayControl.Type.ImageText or SP.JsGrid.DisplayControl.Type.Text + */ + static RegisterNewLookupPropType(id: string, items: any[], displayCtrlName: string, bLimitToList: boolean): void; + + /** Register a custom property type. */ + static RegisterNewCustomPropType(propType: IPropertyType, displayCtrlName: string, editControlName: string, widgetControlNames: string[]): void; + + /** Register a custom property type, where display and edit controls, and also widgets, are derived from the specified parent property type. */ + static RegisterNewDerivedCustomPropType(propType: IPropertyType, baseTypeName: string): void; + } + + export module PropertyType { + export class String implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + toString(): string; + } + export class LookupTable implements ILookupPropertyType { + constructor(items: any[], id: string, bLimitToList: boolean); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + + } + export class CheckBoxBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class DropDownBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class MultiValuePropType implements IMultiValuePropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + export class HyperLink implements IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bHyperlink: boolean; + DataToLocalized(dataValue: any): string; + GetAddress(dataValue: any): string; + /** Returns string like this: '"http://site.com, Site title"' */ + GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; + toString(): string; + } + + + export class Utils { + static RegisterDisplayControl(name: string, singleton, requiredFunctionNames: string[]); + static RegisterEditControl(name: string, factory: (gridContext: IEditControlGridContext, gridTextInputElement:HTMLElement) => IEditControl, requiredFunctionNames: string[]); + static RegisterWidgetControl(name: string, factory: { (ddContext): IPropertyType; }, requiredFunctionNames: string[]); + + static UpdateDisplayControlForPropType(propTypeName: string, displayControlType: string); + } + } + + export module WidgetControl { + export class Type { + static Demo: string; + static Date: string; + static AddressBook: string; + static Hyperlink: string; + } + } + + export module Internal { + export class DiffTracker { + constructor(objBag, fnGetChange); + ExternalAPI: { + AnyChanges(): boolean; + ChangeKeySliceInfo(): any; + ChangeQuery(): any; + EventSliceInfo(): any; + GetChanges(optStartEvent, optEndEvent, optRecordKeys, bFirstStartEvent: boolean, bStartInclusive: boolean, bEndInclusive: boolean, bIncludeInvalidPropUpdates: boolean, bLastEndEvent: boolean): any; + GetChangesAsJson(changeQuery, optfnPreProcessUpdateForSerialize?): string; + GetUniquePropertyChanges(changeQuery, optfnFilter): any; + RegisterEvent(changeKey: IChangeKey, eventObject): void; + UnregisterEvent(changeKey: IChangeKey, eventObject): void; + }; + Clear(): void; + NotifySynchronizeToChange(changeKey: IChangeKey): void; + NotifyRollbackChange(changeKey: IChangeKey): void; + NotifyVacateChange(changeKey: IChangeKey): void; + } + + export class PropertyUpdate implements IValue { + constructor(data: any, localized: string); + data: any; + localized: string; + } + } + + export interface IEditActorCellContext { + propType:IPropertyType; + originalValue:IValue; + record:IRecord; + column:ColumnInfo; + field:GridField; + fieldKey:string; + cellExpandSpace:{ left:number; top:number; fight:number; bottom:number; }; + SetCurrentValue(value): void; + } + + export interface IEditControlCellContext extends IEditActorCellContext{ + cellWidth: number; + cellHeight: number; + cellStyle: any; //TODO: Determine correct type + cellRect:any; + NotifyExpandControl(): void; + NotifyEditComplete(): void; + Show(element: HTMLElement): void; + Hide(element: HTMLElement): void; + } + + + export module EditControl { + + } + + export interface IEditControl { + SupportedWriteMode?: SP.JsGrid.EditActorWriteType; + SupportedReadMode?: SP.JsGrid.EditActorReadType; + GetCellContext? (): IEditControlCellContext; + GetOriginalValue?():IValue; + SetValue?(value:IValue):void; + Dispose():void; + GetInputElement?():HTMLElement; + Focus?(eventInfo:Sys.UI.DomEvent):void; + BindToCell (cellContext: IEditControlCellContext):void; + OnBeginEdit (eventInfo: Sys.UI.DomEvent):void; + Unbind():void; + OnEndEdit():void; + OnCellMove?():void; + OnValueChanged?(newValue: IValue):void; + IsCurrentlyUsingGridTextInputElement?(): boolean; + SetSize?(width:number, height:number):void; + } + + } + + export module Utilities { + export class Set { + constructor(items?: { [item: string]: number }); + constructor(items?: { [item: number]: number }); + /** Returns true if the set is empty */ + IsEmpty(): boolean; + /** Returns first item in the set */ + First(): any; + /** Returns the underlying collection of items as dictionary. + Items are the keys, and values are always 1. + So the return value may be either { [item: string]: number } or { [item: number]: number } */ + GetCollection(): any; + /** Returns all items from the set as an array */ + ToArray(): any[]; + /** Adds all items from array to the set, and returns the set */ + AddArray(array: any[]): SP.Utilities.Set; + /** Adds an item to the set */ + Add(item: any): any; + /** Removes the specified item from the set and returns the removed item */ + Remove(item: any): any; + /** Clears all the items from set */ + Clear(): SP.Utilities.Set; + /** Returns true if item exists in this set */ + Contains(item: any): boolean; + /** Returns a copy of this set */ + Clone(): SP.Utilities.Set; + /** Returns a set that contains all the items that exist only in one of the sets (this and other), but not in both */ + SymmetricDifference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a set that contains all the items that are in this set but not in the otherSet */ + Difference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains items from this set and otherSet */ + Union(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Adds all items from otherSet to this set, and returns this set */ + UnionWith(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains only items that exist both in this set and the otherSet */ + Intersection(otherSet: SP.Utilities.Set): SP.Utilities.Set; + } + } +} + + + + + +declare module SP { + export class GanttControl { + static WaitForGanttCreation(callack: (control: GanttControl) => void): void; + static Instances: GanttControl[]; + static FnGanttCreationCallback: { (control: GanttControl): void }[]; + + get_Columns():SP.JsGrid.ColumnInfo[]; + } +} From 403894c47328ead23d90b576d564558fda447dd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Va=CC=81clav=20Ostroz=CC=8Cli=CC=81k?= Date: Wed, 20 May 2015 21:54:16 +0200 Subject: [PATCH 023/416] React-router 0.13 support --- react-router/react-router-test.ts | 86 ++--- react-router/react-router.d.ts | 559 +++++++++++++++--------------- 2 files changed, 324 insertions(+), 321 deletions(-) diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index 41b352af3..fa335e934 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -7,7 +7,7 @@ import Router = require('react-router'); // Mixin class NavigationTest { v: T; - + makePath() { var v1: string = this.v.makePath('to'); var v2: string = this.v.makePath('to', {id: 1}); @@ -35,27 +35,27 @@ class NavigationTest { 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}); @@ -63,35 +63,23 @@ class StateTest { } } -class RouteHandlerMixinTest { - v: T; - - getRouteDepth() { - var v1: number = this.v.getRouteDepth(); - } - - createChildRouteHandler() { - var v1: Router.RouteHandler = this.v.createChildRouteHandler({ref: 'hoge'}); - } -} - // Location -class LocationTest { +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(); } @@ -102,11 +90,11 @@ 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)); } @@ -118,7 +106,7 @@ new LocationListenerTest(); // Behavior class ScrollBehaviorTest { v: T; - + updateScrollPosition() { var v1: void = this.v.updateScrollPosition({x: 33, y: 102}, 'scrollTop'); } @@ -130,12 +118,12 @@ 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); @@ -145,12 +133,12 @@ class DefaultRouteTest { 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; @@ -158,15 +146,15 @@ class LinkTest { 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'}); @@ -182,12 +170,12 @@ class LinkTest { 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); @@ -198,13 +186,13 @@ class NotFoundRouteTest { 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, {}); @@ -214,14 +202,14 @@ class RedirectTest { 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); @@ -232,11 +220,7 @@ class RouteTest { class RouteHandlerTest { v: Router.RouteHandler; - - constructor() { - new RouteHandlerMixinTest(); - } - + createElement() { React.createElement(Router.RouteHandler, null); React.createElement(Router.RouteHandler, {}); @@ -247,11 +231,11 @@ class RouteHandlerTest { // History class HistoryTest { v: Router.History; - + length() { var v1: number = this.v.length; } - + back() { var v1: void = this.v.back(); } @@ -261,7 +245,7 @@ class HistoryTest { // Router class CreateTest { v: Router.Router; - + constructor() { // React.createElement() version this.v = Router.create({ @@ -272,7 +256,7 @@ class CreateTest { location: Router.HistoryLocation, scrollBehavior: Router.ImitateBrowserBehavior }); - + // React.createFactory() version this.v = Router.create({ routes: React.createFactory(Router.Route)() @@ -283,7 +267,7 @@ class CreateTest { scrollBehavior: Router.ImitateBrowserBehavior }); } - + run() { this.v.run((Handler) => console.log(Handler)); this.v.run((Handler, state) => console.log(Handler, state)); @@ -299,7 +283,7 @@ class RunTest { 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); diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 58ec9069a..c02892ffe 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -1,278 +1,297 @@ -// Type definitions for React Router 0.12.0 +// Type definitions for React Router 0.13.3 // Project: https://github.com/rackt/react-router -// Definitions by: Yuichi Murata +// Definitions by: Yuichi Murata , Václav Ostrožlík // 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" { + + import React = require("react"); + + // + // Transition + // ---------------------------------------------------------------------- + interface Transition { + path: string; + abortReason: any; + retry(): void; + abort(reason?: any): void; + redirect(to: string, params?: {}, query?: {}): void; + cancel(): void; + from: (transition: Transition, routes: Route[], components?: React.ReactElement[], callback?: (error?: any) => void) => void; + to: (transition: Transition, routes: Route[], params?: {}, query?: {}, callback?: (error?: any) => void) => void; + } + + interface TransitionStaticLifecycle { + willTransitionTo?( + transition: Transition, + params: {}, + query: {}, + callback: Function + ): void; + + willTransitionFrom?( + transition: Transition, + component: React.ReactElement, + callback: Function + ): void; + } + + // + // Route Configuration + // ---------------------------------------------------------------------- + // DefaultRoute + interface DefaultRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface DefaultRoute extends React.ReactElement {} + interface DefaultRouteClass extends React.ComponentClass {} + + // NotFoundRoute + interface NotFoundRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface NotFoundRoute extends React.ReactElement {} + interface NotFoundRouteClass extends React.ComponentClass {} + + // Redirect + interface RedirectProp { + path?: string; + from?: string; + to?: string; + } + interface Redirect extends React.ReactElement {} + interface RedirectClass extends React.ComponentClass {} + + // Route + interface RouteProp { + name?: string; + path?: string; + handler?: React.ComponentClass; + ignoreScrollBehavior?: boolean; + } + interface Route extends React.ReactElement {} + interface RouteClass extends React.ComponentClass {} + + var DefaultRoute: DefaultRouteClass; + var NotFoundRoute: NotFoundRouteClass; + var Redirect: RedirectClass; + var Route: RouteClass; + + interface CreateRouteOptions { + name?: string; + path?: string; + ignoreScrollBehavior?: boolean; + isDefault?: boolean; + isNotFound?: boolean; + onEnter?: (transition: Transition, params: {}, query: {}, callback: Function) => void; + onLeave?: (transition: Transition, wtf: any, callback: Function) => void; + handler?: Function; + parentRoute?: Route; + } + + type CreateRouteCallback = (route: Route) => void; + + function createRoute(callback: CreateRouteCallback): Route; + function createRoute(options: CreateRouteOptions | string, callback: CreateRouteCallback): Route; + function createDefaultRoute(options?: CreateRouteOptions | string): Route; + function createNotFoundRoute(options?: CreateRouteOptions | string): Route; + + interface CreateRedirectOptions extends CreateRouteOptions { + path?: string; + from?: string; + to: string; + params?: {}; + query?: {}; + } + function createRedirect(options: CreateRedirectOptions): Redirect; + function createRoutesFromReactChildren(children: Route): Route[]; + + // + // Components + // ---------------------------------------------------------------------- + // Link + interface LinkProp { + activeClassName?: string; + activeStyle?: {}; + to: string; + params?: {}; + query?: {}; + onClick?: Function; + } + interface Link extends React.ReactElement, Navigation, State { + handleClick(event: any): void; + getHref(): string; + getClassName(): string; + getActiveState(): boolean; + } + interface LinkClass extends React.ComponentClass {} + + // RouteHandler + interface RouteHandlerProp { } + interface RouteHandlerChildContext { + routeDepth: number; + } + interface RouteHandler extends React.ReactElement { + getChildContext(): RouteHandlerChildContext; + getRouteDepth(): number; + createChildRouteHandler(props: {}): RouteHandler; + } + interface RouteHandlerClass extends React.ReactElement {} + + var Link: LinkClass; + var RouteHandler: RouteHandlerClass; + + + // + // Top-Level + // ---------------------------------------------------------------------- + interface Router extends React.ReactElement { + run(callback: RouterRunCallback): void; + } + + interface RouterState { + path: string; + action: string; + pathname: string; + params: {}; + query: {}; + routes: Route[]; + } + + interface RouterCreateOption { + routes: Route; + location?: LocationBase; + scrollBehavior?: ScrollBehaviorBase; + onError?: (error: any) => void; + onAbort?: (error: any) => void; + } + + type RouterRunCallback = (Handler: RouteClass, state: RouterState) => void; + + function create(options: RouterCreateOption): Router; + function run(routes: Route, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + + + // + // Location + // ---------------------------------------------------------------------- + interface LocationBase { + getCurrentPath(): void; + toString(): string; + } + interface Location extends LocationBase { + push(path: string): void; + replace(path: string): void; + pop(): void; + } + + interface LocationListener { + addChangeListener(listener: Function): void; + removeChangeListener(listener: Function): void; + } + + interface HashLocation extends Location, LocationListener { } + interface HistoryLocation extends Location, LocationListener { } + interface RefreshLocation extends Location { } + interface StaticLocation extends LocationBase { } + interface TestLocation extends Location, LocationListener { } + + var HashLocation: HashLocation; + var HistoryLocation: HistoryLocation; + var RefreshLocation: RefreshLocation; + var StaticLocation: StaticLocation; + var TestLocation: TestLocation; + + + // + // 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; + + + // + // 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 State { + getPath(): string; + getRoutes(): Route[]; + getPathname(): string; + getParams(): {}; + getQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } + + var Navigation: Navigation; + var State: State; + + + // + // History + // ---------------------------------------------------------------------- + interface History { + back(): void; + length: number; + } + var History: History; } -declare module 'react-router' { - import Export = ReactRouter; - export = Export; -} -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; - } +declare module "react" { + import ReactRouter = require("react-router"); + + // for DefaultRoute + function createElement( + type: ReactRouter.DefaultRouteClass, + props: ReactRouter.DefaultRouteProp, + ...children: ReactNode[]): ReactRouter.DefaultRoute; + + // for Link + function createElement( + type: ReactRouter.LinkClass, + props: ReactRouter.LinkProp, + ...children: ReactNode[]): ReactRouter.Link; + + // for NotFoundRoute + function createElement( + type: ReactRouter.NotFoundRouteClass, + props: ReactRouter.NotFoundRouteProp, + ...children: ReactNode[]): ReactRouter.NotFoundRoute; + + // for Redirect + function createElement( + type: ReactRouter.RedirectClass, + props: ReactRouter.RedirectProp, + ...children: ReactNode[]): ReactRouter.Redirect; + + // for Route + function createElement( + type: ReactRouter.RouteClass, + props: ReactRouter.RouteProp, + ...children: ReactNode[]): ReactRouter.Route; + + // for RouteHandler + function createElement( + type: ReactRouter.RouteHandlerClass, + props: ReactRouter.RouteHandlerProp, + ...children: ReactNode[]): ReactRouter.RouteHandler; } From 1ec7dac4f93c825f3a90372de6abfe2198343358 Mon Sep 17 00:00:00 2001 From: Sam Albert Date: Tue, 26 May 2015 16:01:50 -0400 Subject: [PATCH 024/416] Updated callback buffer with rest parameters. --- node_zeromq/zmq-tests.ts | 2 +- node_zeromq/zmq.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node_zeromq/zmq-tests.ts b/node_zeromq/zmq-tests.ts index 696a98c13..a62d97a6c 100644 --- a/node_zeromq/zmq-tests.ts +++ b/node_zeromq/zmq-tests.ts @@ -19,7 +19,7 @@ function test3() { var sock = zmq.socket('push'); sock.bindSync('tcp://127.0.0.1:3000'); sock.send(['hello', 'world']); - sock.on('message', function (buffer: Buffer) { + sock.on('message', function (buffer1: Buffer, buffer2: Buffer) { // }); } diff --git a/node_zeromq/zmq.d.ts b/node_zeromq/zmq.d.ts index 8d29e0569..3ab2d1f25 100644 --- a/node_zeromq/zmq.d.ts +++ b/node_zeromq/zmq.d.ts @@ -182,7 +182,7 @@ declare module 'zmq' { * @param eventName {string} * @param callback {Function} */ - on(eventName: string, callback: (buffer: Buffer) => void): void; + on(eventName: string, callback: (...buffer: Buffer[]) => void): void; // Socket Options _fd: any; From ab71290650b4077c498503315396bece131ae488 Mon Sep 17 00:00:00 2001 From: Rodney Lorrimar Date: Thu, 28 May 2015 10:50:54 +0800 Subject: [PATCH 025/416] moment: Include some methods which were added in 2.9.0 --- moment/moment-node.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 13f1b9362..0a89b7066 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; } @@ -276,6 +277,12 @@ declare module moment { isSame(b: Date, granularity: string): boolean; isSame(b: number[], granularity: string): boolean; + isBetween(a: Moment, b: Moment, granularity?: string): boolean; + isBetween(a: string, b: string, granularity?: string): boolean; + isBetween(a: number, b: number, granularity?: string): boolean; + isBetween(a: Date, b: Date, granularity?: string): boolean; + isBetween(a: number[], b: number[], granularity?: string): boolean; + // Deprecated as of 2.8.0. lang(language: string): Moment; lang(reset: boolean): Moment; @@ -412,6 +419,7 @@ declare module moment { invalid(parsingFlags?: Object): Moment; isMoment(): boolean; isMoment(m: any): boolean; + isDate(m: any): boolean; isDuration(): boolean; isDuration(d: any): boolean; From dbbc90296b72294f8099c19e724c37447dca43f3 Mon Sep 17 00:00:00 2001 From: Rodney Lorrimar Date: Thu, 28 May 2015 10:51:22 +0800 Subject: [PATCH 026/416] moment: Tests for 2.9.0 methods --- moment/moment-external-tests.ts | 7 +++++++ moment/moment-tests.ts | 9 +++++++++ 2 files changed, 16 insertions(+) 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-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'); From 8064aa89b0ccf592a507ccd8f5e0389818abb64b Mon Sep 17 00:00:00 2001 From: Rodney Lorrimar Date: Tue, 2 Jun 2015 11:30:14 +0800 Subject: [PATCH 027/416] moment: Use type union for methods with moment-like parameters --- moment/moment-node.d.ts | 59 ++++++----------------------------------- 1 file changed, 8 insertions(+), 51 deletions(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 0a89b7066..eaacb8855 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -216,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; @@ -243,45 +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; - - isBetween(a: Moment, b: Moment, granularity?: string): boolean; - isBetween(a: string, b: string, granularity?: string): boolean; - isBetween(a: number, b: number, granularity?: string): boolean; - isBetween(a: Date, b: Date, granularity?: string): boolean; - isBetween(a: number[], 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; @@ -297,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; From 8f9ff607f0a79e5a976682d00ce156781f9efd19 Mon Sep 17 00:00:00 2001 From: Rodney Lorrimar Date: Sat, 6 Jun 2015 16:26:00 +0800 Subject: [PATCH 028/416] moment: Use type alias for moment-like parameters --- moment/moment-node.d.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index eaacb8855..f491833f9 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -216,8 +216,8 @@ declare module moment { dayOfYear(): number; dayOfYear(d: number): Moment; - from(f: Moment|string|number|Date|number[], suffix?: boolean): string; - to(f: Moment|string|number|Date|number[], suffix?: boolean): string; + from(f: MomentLike, suffix?: boolean): string; + to(f: MomentLike, suffix?: boolean): string; diff(b: Moment): number; diff(b: Moment, unitOfTime: string): number; @@ -240,13 +240,13 @@ declare module moment { isDST(): boolean; isBefore(): boolean; - isBefore(b: Moment|string|number|Date|number[], granularity?: string): boolean; + isBefore(b: MomentLike, granularity?: string): boolean; isAfter(): boolean; - isAfter(b: Moment|string|number|Date|number[], granularity?: string): boolean; + isAfter(b: MomentLike, 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; + isSame(b: MomentLike, granularity?: string): boolean; + isBetween(a: MomentLike, b: MomentLike, granularity?: string): boolean; // Deprecated as of 2.8.0. lang(language: string): Moment; @@ -262,11 +262,11 @@ declare module moment { localeData(): MomentLanguage; // Deprecated as of 2.7.0. - max(date: Moment|string|number|Date|any[]): Moment; + max(date: MomentLike|any[]): Moment; max(date: string, format: string): Moment; // Deprecated as of 2.7.0. - min(date: Moment|string|number|Date|any[]): Moment; + min(date: MomentLike|any[]): Moment; min(date: string, format: string): Moment; get(unit: string): number; @@ -439,6 +439,9 @@ declare module moment { } + // Moment.js automatically converts datetime parameters from a number of types + type MomentLike = Moment | string | number | Date | number[]; + } declare module 'moment' { From 6f0bcac0caf998f1e943d43b7f9bf240c68ba13e Mon Sep 17 00:00:00 2001 From: Rodney Lorrimar Date: Tue, 23 Jun 2015 13:00:22 +0800 Subject: [PATCH 029/416] Revert "moment: Use type alias for moment-like parameters" This reverts commit 8f9ff607f0a79e5a976682d00ce156781f9efd19 which fails to compile on typescript@1.4.1 (however it compiles with typescript@1.5.0-beta). --- moment/moment-node.d.ts | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index f491833f9..eaacb8855 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -216,8 +216,8 @@ declare module moment { dayOfYear(): number; dayOfYear(d: number): Moment; - from(f: MomentLike, suffix?: boolean): string; - to(f: MomentLike, suffix?: boolean): 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; @@ -240,13 +240,13 @@ declare module moment { isDST(): boolean; isBefore(): boolean; - isBefore(b: MomentLike, granularity?: string): boolean; + isBefore(b: Moment|string|number|Date|number[], granularity?: string): boolean; isAfter(): boolean; - isAfter(b: MomentLike, granularity?: string): boolean; + isAfter(b: Moment|string|number|Date|number[], granularity?: string): boolean; - isSame(b: MomentLike, granularity?: string): boolean; - isBetween(a: MomentLike, b: MomentLike, 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; @@ -262,11 +262,11 @@ declare module moment { localeData(): MomentLanguage; // Deprecated as of 2.7.0. - max(date: MomentLike|any[]): Moment; + max(date: Moment|string|number|Date|any[]): Moment; max(date: string, format: string): Moment; // Deprecated as of 2.7.0. - min(date: MomentLike|any[]): Moment; + min(date: Moment|string|number|Date|any[]): Moment; min(date: string, format: string): Moment; get(unit: string): number; @@ -439,9 +439,6 @@ declare module moment { } - // Moment.js automatically converts datetime parameters from a number of types - type MomentLike = Moment | string | number | Date | number[]; - } declare module 'moment' { From 575d43c508d56b5d5fc0aa0ddc2aab93b3a3676e Mon Sep 17 00:00:00 2001 From: Gitgiddy Date: Fri, 26 Jun 2015 09:24:50 -0400 Subject: [PATCH 030/416] Extendable interfaces for require, module.require Node's `require` should implement a new interface `NodeRequire` (rather than direct signature) for specialized extension by other libraries #4740 --- node/node.d.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 0c6b42740..6d73172f8 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -27,23 +27,30 @@ declare function clearInterval(intervalId: NodeJS.Timer): void; declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; -declare var require: { +interface NodeRequireFunction { (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { resolve(id:string): string; cache: any; extensions: any; main: any; -}; +} -declare var module: { +declare var require: NodeRequire; + +interface NodeModule { exports: any; - require(id: string): any; + require: NodeRequireFunction; id: string; filename: string; loaded: boolean; parent: any; children: any[]; -}; +} + +declare var module: NodeModule; // Same as module.exports declare var exports: any; From defc79f8004fa04b39d6c3c1a28bf69ffa7338b3 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Sat, 27 Jun 2015 11:47:09 -0700 Subject: [PATCH 031/416] Add bardjs definitions --- bardjs/bardjs.d.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 bardjs/bardjs.d.ts diff --git a/bardjs/bardjs.d.ts b/bardjs/bardjs.d.ts new file mode 100644 index 000000000..77fc799b1 --- /dev/null +++ b/bardjs/bardjs.d.ts @@ -0,0 +1,30 @@ +// Type definitions for bardjs 0.1.4 +// Project: https://github.com/wardbell/bardjs +// Definitions by: Andrew Archibald +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module bard { + function $httpBackend($provide: angular.auto.IProvideService); + function $q($provide: angular.auto.IProvideService); + function addGlobals(...args: any[]): void; + function appModule(...args: any[]); + function assertFail(message: string): Chai.AssertionError; + function asyncModule(...args: any[]); + function debugging(x); + function fakeLogger($provide: angular.auto.IProvideService): void; + function fakeRouteHelperProvider($provide: angular.auto.IProvideService): void; + function fakeRouteProvider($provide: angular.auto.IProvideService): void; + function fakeStateProvider($provide: angular.auto.IProvideService): void; + function fakeToastr($provide: angular.auto.IProvideService): void; + function inject(...args: any[]): void; + function log(msg); + function mochaRunnerListener(runner: Mocha.IRunner): void; + function mockService(service, config); + function replaceAccentChars(s: string): string; + function verifyNoOutstandingHttpRequests(): void; + function wrapWithDone(callback: Function, done: Function); +} From 79daa85ac468dc65ba208c775e5ef53780279b4f Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Sat, 27 Jun 2015 21:13:51 -0700 Subject: [PATCH 032/416] Add more specific types and comments to bardjs --- bardjs/bardjs.d.ts | 166 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 155 insertions(+), 11 deletions(-) diff --git a/bardjs/bardjs.d.ts b/bardjs/bardjs.d.ts index 77fc799b1..328d5b067 100644 --- a/bardjs/bardjs.d.ts +++ b/bardjs/bardjs.d.ts @@ -7,24 +7,168 @@ /// /// +/** + * Module for bardjs functions + */ declare module bard { - function $httpBackend($provide: angular.auto.IProvideService); - function $q($provide: angular.auto.IProvideService); - function addGlobals(...args: any[]): void; - function appModule(...args: any[]); + /** + * Replaces the ngMock'ed $httpBackend with the real one from ng thus + * restoring the ability to issue AJAX calls to the backend with $http. + * + * Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest). + * Use $rootScope.$apply() for this purpose. + * + * Could restore $q with $qReal in which case don't need to flush. + */ + function $httpBackend($provide: angular.auto.IProvideService): any; + + /** + * Replaces the ngMock'ed $q with the real one from ng thus + * obviating the need to flush $http and $q queues + * at the expense of ability to control $q timing. + */ + function $q($provide: angular.auto.IProvideService): any; + + /** + * Add names of globals to list of OK globals for this mocha spec + * NB: Call this method ONLY if you're using mocha! + * NB: Turn off browser-sync else mocha detects the browser-sync globals + * like ` ___browserSync___` + */ + function addGlobals(...globals: any[]): void; + + /** + * Prepare ngMocked application feature module + * along with faked toastr, routehelper, + * and faked router services. + * Especially useful for controller testing + * Use it as you would the ngMocks#module method + * + * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES! + * Fall back to `angular.mock.module(...)` or just `module(...)` + */ + function appModule(...args: any[]): any; + + /** + * Assert a failure in mocha, without condition + */ function assertFail(message: string): Chai.AssertionError; - function asyncModule(...args: any[]); - function debugging(x); + + /** + * Prepare ngMocked module definition that makes real $http and $q calls + * Also adds fakeLogger to the end of the definition + * Use it as you would the ngMocks#module method + */ + function asyncModule(...args: any[]): any; + + /** + * Get or set bard debugging flag + */ + function debugging(newFlag?: any): boolean; + + /** + * Creates a fake logger to be used in testing + */ function fakeLogger($provide: angular.auto.IProvideService): void; + + /** + * Creates a fake route helper provider to be used in testing + */ function fakeRouteHelperProvider($provide: angular.auto.IProvideService): void; + + /** + * Stub out the $routeProvider so we avoid + * all routing calls, including the default route + * which runs on every test otherwise. + * Make sure this goes before the inject in the spec. + */ function fakeRouteProvider($provide: angular.auto.IProvideService): void; + + /** + * Stub out the $stateProvider so we avoid + * all routing calls, including the default state + * which runs on every test otherwise. + * Make sure this goes before the inject in the spec. + */ function fakeStateProvider($provide: angular.auto.IProvideService): void; + + /** + * Creates a fake toastr to be used in testing + */ function fakeToastr($provide: angular.auto.IProvideService): void; - function inject(...args: any[]): void; - function log(msg); + + /** + * Inject selected services into the windows object during test + * then remove them when test ends with an `afterEach`. + * + * spares us the repetition of creating common service vars and injecting them + * + * Option: the first argument may be the mocha spec context object (`this`) + * It MUST be `this` if you what to check for mocha global leaks. + * Do NOT supply `this` as the first arg if you're not running mocha specs. + * + * remaining inject arguments may take one of 3 forms : + * + * function - This fn will be passed to ngMocks.inject. + * Annotations extracted after inject does its thing. + * [strings] - same string array you'd use to set fn.$inject + * (...string) - string arguments turned into a string array + */ + function inject(context?: any, ...args: string[]): void; + + /** + * Write to console if bard debugging flag is on + */ + function log(message: any): void; + + /** + * Listen to mocha test runner events + * Usage in browser: + * var runner = mocha.run(); + * bard.mochaRunnerListener(runner); + */ function mochaRunnerListener(runner: Mocha.IRunner): void; - function mockService(service, config); - function replaceAccentChars(s: string): string; + + /** + * Mocks out a service with sinon stubbed functions + * that return the values specified in the config + * + * If the config value is `undefined`, + * stub the service method with a dummy that doesn't return a value + * + * If the config value is a function, set service property with it + * + * If a service member is a property, not a function, + * set it with the config value + * If a service member name is not a key in config, + * follow the same logic as above to set its members + * using the config._default value (which is `undefined` if omitted) + * + * If there is a config entry that is NOT a member of the service + * add mocked function to the service using the config value + */ + function mockService(service: any, config: any): any; + + /** + * Replaces the accented characters of many European languages w/ unaccented chars + * Use it in JavaScript string sorts where such characters may be encountered + * Matches the default string comparers of most databases. + * Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name) + * instead of: a.Name < b.Name + */ + function replaceAccentChars(text: string): string; + + /** + * Assert that there are no outstanding HTTP requests after test is complete + * For use with ngMocks; doesn't work for async server integration tests + */ function verifyNoOutstandingHttpRequests(): void; - function wrapWithDone(callback: Function, done: Function); + + /** + * Returns a function that execute a callback function + * (typically a fn making asserts) within a try/catch + * The try/catch then calls the ambient "done" function + * in the appropriate way for both success and failure + */ + function wrapWithDone(callback: Function, done: Function): Function; } From 9d20855e549fd43fcb71221f05e75be0e3e57418 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Sat, 27 Jun 2015 21:30:18 -0700 Subject: [PATCH 033/416] Made more specific comments in bardjs --- bardjs/bardjs.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bardjs/bardjs.d.ts b/bardjs/bardjs.d.ts index 328d5b067..e0288825f 100644 --- a/bardjs/bardjs.d.ts +++ b/bardjs/bardjs.d.ts @@ -67,12 +67,12 @@ declare module bard { function debugging(newFlag?: any): boolean; /** - * Creates a fake logger to be used in testing + * Registers a fake logger service that you can spy on */ function fakeLogger($provide: angular.auto.IProvideService): void; /** - * Creates a fake route helper provider to be used in testing + * Registers a fake route helper provider service that you can spy on */ function fakeRouteHelperProvider($provide: angular.auto.IProvideService): void; @@ -93,7 +93,7 @@ declare module bard { function fakeStateProvider($provide: angular.auto.IProvideService): void; /** - * Creates a fake toastr to be used in testing + * Registers a fake toastr service that you can spy on */ function fakeToastr($provide: angular.auto.IProvideService): void; From 37c762000842cb8152bb64a920e22552f6fc7c14 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 14:45:36 +0100 Subject: [PATCH 034/416] More specific _.flatten type, remove types for non-existent methods --- lodash/lodash-tests.ts | 11 ++-- lodash/lodash.d.ts | 129 ++++++----------------------------------- 2 files changed, 24 insertions(+), 116 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index e0f2b8226..cd84de417 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -239,10 +239,13 @@ result = _([1, 2, 3]).take(function (num) { result = _(foodsOrganic).take('organic').value(); result = _(foodsType).take({ 'type': 'fruit' }).value(); -result = _.flatten([1, [2], [3, [[4]]]]); -result = _.flatten([1, [2], [3, [[4]]]], true); -var result: any -result = _.flatten(stoogesQuotes, 'quotes'); +result = >_.flatten([[1, 2], [3, 4]]); +result = >_.flatten([[1, 2], [3, 4], 5, 6]); +result = >>>_.flatten([1, [2], [3, [[4]]]]); + +result = >_.flatten([1, [2], [[3]]], true); +result = >_.flatten([1, [2], [3, [[4]]]], true); +result = >_.flatten([1, [2], [3, [[false]]]], true); result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index a906b907f..8c265cb8f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -769,123 +769,28 @@ declare module _ { take(whereValue: W): LoDashArrayWrapper; } + interface MaybeNestedList extends List> { } + interface RecursiveList extends List> { } + //_.flatten interface LoDashStatic { /** - * Flattens a nested array (the nesting can be to any depth). If isShallow is truey, the - * array will only be flattened a single level. If a callback is provided each element of - * the array is passed through the callback before flattening. The callback is bound to - * thisArg and invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The array to flatten. - * @param shallow If true then only flatten one level, optional, default = false. - * @return `array` flattened. - **/ - flatten(array: Array, isShallow?: boolean): T[]; + * Flattens a nested array. + * + * @param array The array to flatten. + * @return `array` flattened. + **/ + flatten(array: MaybeNestedList): T[]; /** - * @see _.flatten - **/ - flatten(array: List, isShallow?: boolean): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - whereValue: W): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - isShallow: boolean, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.flatten - **/ - flatten( - array: List, - pluckValue: string): T[]; + * Flattens a nested array. If isDeep is true the array is recursively flattened, otherwise it is only + * flattened a single level. + * + * @param array The array to flatten. + * @param deep Specify a deep flatten. + * @return `array` flattened. + **/ + flatten(array: RecursiveList, isDeep: boolean): T[]; } interface LoDashArrayWrapper { From 36f2158f0c594efabc7b2ce30ae5a34bd042d6bc Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 14:58:39 +0100 Subject: [PATCH 035/416] Fix _().flatten() - remove non-existent methods, small type improvement Previously type was too specific, and thereby often wrong. It's now less specific, but never wrong. --- lodash/lodash-tests.ts | 5 +++-- lodash/lodash.d.ts | 44 ++++-------------------------------------- 2 files changed, 7 insertions(+), 42 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index cd84de417..709151f16 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -247,9 +247,10 @@ result = >_.flatten([1, [2], [[3]]], true); result = >_.flatten([1, [2], [3, [[4]]]], true); result = >_.flatten([1, [2], [3, [[false]]]], true); -result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); +result = <_.LoDashArrayWrapper>_([[1, 2], [3, 4], 5, 6]).flatten(); +result = <_.LoDashArrayWrapper>>>_([1, [2], [3, [[4]]]]).flatten(); + result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); -result = <_.LoDashArrayWrapper>_(stoogesQuotes).flatten('quotes'); result = _.indexOf([1, 2, 3, 1, 2, 3], 2); result = _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 8c265cb8f..c0f0bd5d5 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -795,50 +795,14 @@ declare module _ { interface LoDashArrayWrapper { /** - * @see _.flatten - **/ - flatten(isShallow?: boolean): LoDashArrayWrapper; + * @see _.flatten + **/ + flatten(): LoDashArrayWrapper; /** * @see _.flatten **/ - flatten( - isShallow: boolean, - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - pluckValue: string): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - isShallow: boolean, - whereValue: W): LoDashArrayWrapper; - - /** - * @see _.flatten - **/ - flatten( - whereValue: W): LoDashArrayWrapper; + flatten(isShallow: boolean): LoDashArrayWrapper; } //_.indexOf From ed15e4bd3806d00223f40803a7d13d0d3ada111e Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 1 Jul 2015 16:14:31 +0100 Subject: [PATCH 036/416] Make _.flatten(array, bool) slightly more general --- lodash/lodash.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c0f0bd5d5..e79eb64f8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -790,7 +790,7 @@ declare module _ { * @param deep Specify a deep flatten. * @return `array` flattened. **/ - flatten(array: RecursiveList, isDeep: boolean): T[]; + flatten(array: RecursiveList, isDeep: boolean): List | RecursiveList; } interface LoDashArrayWrapper { From 7a6400a7d4b18de10b1c501955ed665f7af5a989 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Sat, 4 Jul 2015 17:18:50 +0200 Subject: [PATCH 037/416] Improve gulp.watch() --- gulp/gulp-tests.ts | 39 +++++++++++++++++++++++++++++++++++++++ gulp/gulp.d.ts | 42 +++++++++--------------------------------- 2 files changed, 48 insertions(+), 33 deletions(-) diff --git a/gulp/gulp-tests.ts b/gulp/gulp-tests.ts index 7e07f25f7..07a92fc91 100644 --- a/gulp/gulp-tests.ts +++ b/gulp/gulp-tests.ts @@ -1,6 +1,8 @@ /// +/// import gulp = require("gulp"); +import browserSync = require("browser-sync"); var typescript: IGulpPlugin = null; // this would be the TypeScript compiler var jasmine: IGulpPlugin = null; // this would be the jasmine test runner @@ -27,3 +29,40 @@ gulp.task('test', ['compile', 'compile2'], function() }); gulp.task('default', ['compile', 'test']); + + +var opts = {}; + +gulp.watch('*.html', 'compile'); +gulp.watch('*.html', ['compile', 'test']); +gulp.watch('*.html', () => {}); +gulp.watch('*.html', [() => {}, (event) => {}]); +gulp.watch('*.html', ['compile', () => {}]); + +gulp.watch('*.html', opts, 'compile'); +gulp.watch('*.html', opts, ['compile', 'test']); +gulp.watch('*.html', opts, () => {}); +gulp.watch('*.html', opts, [() => {}, (event) => {}]); +gulp.watch('*.html', opts, ['compile', () => {}]); + +gulp.watch(['*.html', '*.ts'], 'compile'); +gulp.watch(['*.html', '*.ts'], ['compile', 'test']); +gulp.watch(['*.html', '*.ts'], () => {}); +gulp.watch(['*.html', '*.ts'], [() => {}, (event) => {}]); +gulp.watch(['*.html', '*.ts'], ['compile', () => {}]); + +gulp.watch(['*.html', '*.ts'], opts, 'compile'); +gulp.watch(['*.html', '*.ts'], opts, ['compile', 'test']); +gulp.watch(['*.html', '*.ts'], opts, () => {}); +gulp.watch(['*.html', '*.ts'], opts, [() => {}, (event) => {}]); +gulp.watch(['*.html', '*.ts'], opts, ['compile', () => {}]); + +var watcher = gulp.watch('*.html', event => { + console.log('Event type: ' + event.type); + console.log('Event path: ' + event.path); +}); + +gulp.task('serve', ['compile'], () => { + var browser = browserSync.create(); + gulp.watch(['*.html', '*.ts'], ['compile', browser.reload]); +}); diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 7ec11def7..d7a0dba57 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -236,45 +236,21 @@ declare module gulp { dest(outFolder:(file:string)=>string, opt?:IDestOptions): NodeJS.ReadWriteStream; - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param tasks names of task(s) to run when a file changes, added with gulp.task() - */ - watch(glob:string, tasks:string[]): EventEmitter; - watch(glob:string[], tasks:string[]): EventEmitter; - /** * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. * * @param glob a single glob or array of globs that indicate which files to watch for changes. * @param opt options, that are passed to the gaze library. - * @param tasks names of task(s) to run when a file changes, added with gulp.task() + * @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with gulp.task(). */ - watch(glob:string, opt:IWatchOptions, tasks:string[]): EventEmitter; - watch(glob:string[], opt:IWatchOptions, tasks:string[]): EventEmitter; - - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param fn a callback or array of callbacks to be called on each change. - */ - watch(glob:string, fn:IWatchCallback): EventEmitter; - watch(glob:string[], fn:IWatchCallback): EventEmitter; - watch(glob:string, fn:IWatchCallback[]): EventEmitter; - watch(glob:string[], fn:IWatchCallback[]): EventEmitter; - - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param opt options, that are passed to the gaze library. - * @param fn a callback or array of callbacks to be called on each change. - */ - watch(glob:string, opt:IWatchOptions, fn:IWatchCallback): EventEmitter; - watch(glob:string, opt:IWatchOptions, fn:IWatchCallback[]): EventEmitter; + watch(glob:string, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string, fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string, opt:IWatchOptions, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string, opt:IWatchOptions, fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string[], fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string[], fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string[], opt:IWatchOptions, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string[], opt:IWatchOptions, fn:(IWatchCallback|string)[]): EventEmitter; } } From 97f251cef19e557391588889493103c15fffde12 Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Sun, 5 Jul 2015 13:16:47 +0900 Subject: [PATCH 038/416] add webvr-api definition --- webvr-api/webvr-api-test.ts | 62 +++++++++++++ webvr-api/webvr-api.d.ts | 175 ++++++++++++++++++++++++++++++++++++ 2 files changed, 237 insertions(+) create mode 100644 webvr-api/webvr-api-test.ts create mode 100644 webvr-api/webvr-api.d.ts diff --git a/webvr-api/webvr-api-test.ts b/webvr-api/webvr-api-test.ts new file mode 100644 index 000000000..df2a72438 --- /dev/null +++ b/webvr-api/webvr-api-test.ts @@ -0,0 +1,62 @@ +/// + +function fieldOfViewToProjectionMatrix(fov: WebVRApi.VRFieldOfView, zNear: number, zFar: number) { + var upTan = Math.tan(fov.upDegrees * Math.PI/180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI/180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + + var out = new Float32Array(16); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = ((upTan - downTan) * yScale * 0.5); + out[10] = -(zNear + zFar) / (zFar - zNear); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = -(2.0 * zFar * zNear) / (zFar - zNear); + out[15] = 0.0; + + return out; +} + +var hmd: HMDVRDevice; +var leftEyeParams = hmd.getEyeParameters("left"); +var rightEyeParams = hmd.getEyeParameters("right"); +var leftEyeRect = leftEyeParams.renderRect; +var rightEyeRect = rightEyeParams.renderRect; + +var canvas: HTMLCanvasElement; +canvas.width = rightEyeRect.x + rightEyeRect.width; +canvas.height = Math.max(leftEyeRect.y + leftEyeRect.height, rightEyeRect.y + rightEyeRect.height); + +var gHMD: WebVRApi.VRDevice; +var gPositionSensor: WebVRApi.VRDevice; + +navigator.getVRDevices().then(function(devices) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof HMDVRDevice) { + gHMD = devices[i]; + break; + } + } + + if (gHMD) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof PositionSensorVRDevice && + devices[i].hardwareUnitId == gHMD.hardwareUnitId) { + gPositionSensor = devices[i]; + break; + } + } + } +}); diff --git a/webvr-api/webvr-api.d.ts b/webvr-api/webvr-api.d.ts new file mode 100644 index 000000000..16918cf30 --- /dev/null +++ b/webvr-api/webvr-api.d.ts @@ -0,0 +1,175 @@ +// Type definitions for WebVR API +// Project: http://mozvr.github.io/webvr-spec/webvr.html +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare type VREye = string; + +declare module WebVRApi { + export interface VRFieldOfViewReadOnly { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfViewInit { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfView extends VRFieldOfViewReadOnly { + constructor(upDegrees:number, rightDegrees:number, downDegrees:number, leftDegrees:number): VRFieldOfView; + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRPositionState { + /** + * Monotonically increasing value that allows the author to determine if position state data been updated from the hardware. + */ + timeStamp: number; + /** + * True if the position attribute is valid. If false position MUST be null. + */ + hasPosition: boolean; + /** + * Position of the sensor at timeStamp as a 3D vector. + */ + position?: GeometryDom.DOMPoint; + /** + * Linear velocity of the sensor at timeStamp. + */ + linearVelocity?: GeometryDom.DOMPoint; + /** + * Linear acceleration of the sensor at timeStamp. + */ + linearAcceleration?: GeometryDom.DOMPoint; + /** + * True if the orientation attribute is valid. If false orientation MUST be null. + */ + hasOrientation: boolean; + /** + * Orientation of the sensor at timeStamp as a quaternion. + */ + orientation?: GeometryDom.DOMPoint; + /** + * Angular velocity of the sensor at timeStamp. + */ + angularVelocity?: GeometryDom.DOMPoint; + /** + * Angular acceleration of the sensor at timeStamp. + */ + angularAcceleration?: GeometryDom.DOMPoint; + } + + export interface VREyeParameters { + /** + * Describes the minimum supported field of view for the eye. + */ + minimumFieldOfView: VRFieldOfView; + /** + * Describes the maximum supported field of view for the eye. + */ + maximumFieldOfView: VRFieldOfView; + /** + * Describes the recommended field of view for the eye. + */ + recommendedFieldOfView: VRFieldOfView; + /** + * Offset from the center of the users head to the eye in meters. + */ + eyeTranslation: GeometryDom.DOMPoint; + /** + * The current field of view for the eye, as specified by setFieldOfView. + */ + currentFieldOfView: VRFieldOfView; + /** + * Describes the viewport of a canvas into which visuals for this eye should be rendered. + */ + renderRect: GeometryDom.DOMRect; + } + + export interface VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + } +} + +declare class HMDVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return the current VREyeParameters for the given eye. + */ + getEyeParameters(whichEye: VREye): WebVRApi.VREyeParameters; + /** + * Set the field of view for both eyes. If + */ + setFieldOfView(leftFOV?: WebVRApi.VRFieldOfViewInit, rightFOV?: WebVRApi.VRFieldOfViewInit, zNear?: number, zFar?: number): void; +} + +declare class PositionSensorVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return a VRPositionState dictionary containing the state of this position sensor state for the current frame (if within a requestAnimationFrame context) or for the previous frame. + */ + getState(): WebVRApi.VRPositionState; + /** + * Return the current instantaneous sensor state. + */ + getImmediateState(): WebVRApi.VRPositionState; + + /** + * Reset this sensor, treating its current position and orientation yaw as the "origin/zero" values. + */ + resetSensor(): void; +} + +interface Navigator { + /** + * Return a Promise which resolves to a list of available VRDevices. + */ + getVRDevices(): Promise>; +} + From c6a507446a0fc58043d1bc12a609b0ac5f9a212e Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:29:19 +0300 Subject: [PATCH 039/416] Fixed couple bugs --- sharepoint/SharePoint.d.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 026658ef8..65e1f63a4 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ // Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -159,6 +159,7 @@ declare class _spPageContextInfo { static currentUICultureName: string; //"ru-RU" static layoutsUrl: string; //"_layouts/15" static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static pageItemId: number; static pagePersonalizationScope: string; //1 static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" @@ -2440,7 +2441,7 @@ declare module SP { get_webId(): SP.Guid; getErrorDetails(): SP.ClientObjectList; uninstall(): SP.GuidResult; - upgrade(appPackageStream: any[]): void; + upgrade(appPackageStream: SP.Base64EncodedByteArray): void; cancelAllJobs(): SP.BooleanResult; install(): SP.GuidResult; getPreviousAppVersion(): SP.App; @@ -2515,8 +2516,8 @@ declare module SP { getByFileName(fileName: string): SP.Attachment; } export class AttachmentCreationInformation extends SP.ClientValueObject { - get_contentStream(): any[]; - set_contentStream(value: any[]): void; + get_contentStream(): SP.Base64EncodedByteArray; + set_contentStream(value: SP.Base64EncodedByteArray): void; get_fileName(): string; set_fileName(value: string): void; get_typeId(): string; @@ -3243,7 +3244,7 @@ declare module SP { boolean, number, currency, - uRL, + URL, computed, threading, guid, @@ -4812,9 +4813,9 @@ declare module SP { getSubwebsForCurrentUser(query: SP.SubwebQuery): SP.WebCollection; getAppInstanceById(appInstanceId: SP.Guid): SP.AppInstance; getAppInstancesByProductId(productId: SP.Guid): SP.ClientObjectList; - loadAndInstallAppInSpecifiedLocale(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadApp(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadAndInstallApp(appPackageStream: any[]): SP.AppInstance; + loadAndInstallAppInSpecifiedLocale(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadApp(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadAndInstallApp(appPackageStream: SP.Base64EncodedByteArray): SP.AppInstance; ensureUser(logonName: string): SP.User; applyTheme(colorPaletteUrl: string, fontSchemeUrl: string, backgroundImageUrl: string, shareGenerated: boolean): void; } From e53377052eb6bbb0307404938e728dd91b804103 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:48:28 +0300 Subject: [PATCH 040/416] Refactored microsoft.ajax.d.ts to compile with SharePoint.d.ts From e0ca94ea1317c51994d7dc1320601f99c127032a Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:49:32 +0300 Subject: [PATCH 041/416] Added spgantt definitions (not finished yet) to SharePoint.d.ts From 14a3909c9171566e377a8cda78ee3f54711e8a5d Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:55:16 +0300 Subject: [PATCH 042/416] Refactored SharePoint.d.ts to TypeScript 1.4 (union types) From 160132fdad7baa693eaf3af1ea31334a462278c3 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:58:09 +0300 Subject: [PATCH 043/416] Added and fixed definitions for dialogs in SharePoint.d.ts From db8c5956c24ee413134e0ffdf9b097c8f799d8b7 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 19:01:31 +0300 Subject: [PATCH 044/416] Backported SharePoint.d.ts changes fom master From 5d139c17006438dfa12c790551808a7980e07c5b Mon Sep 17 00:00:00 2001 From: Moes Date: Mon, 6 Jul 2015 12:23:51 +1000 Subject: [PATCH 045/416] Update jquery.fileuplade.d.ts Extend JQueryFileUpload from JQuery to enable chaining, add JQuerySupport Interface --- jquery.fileupload/jquery.fileupload.d.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/jquery.fileupload/jquery.fileupload.d.ts b/jquery.fileupload/jquery.fileupload.d.ts index 0ac8b98f9..3774cb6e1 100644 --- a/jquery.fileupload/jquery.fileupload.d.ts +++ b/jquery.fileupload/jquery.fileupload.d.ts @@ -5,7 +5,6 @@ /// - // Interface options for the plugin interface JQueryFileInputOptions { @@ -152,13 +151,15 @@ interface JQueryFileInputOptions { } -interface JQueryFileUpload { - +interface JQueryFileUpload extends JQuery { contentType:string; } -interface JQuery -{ +interface JQuery { // Interface to the main method of jQuery File Upload fileupload(settings: JQueryFileInputOptions): JQueryFileUpload; -} \ No newline at end of file +} + +interface JQuerySupport { + fileInput?: boolean; +} From bfcf082b40c4ad008fe36c2d881dc5243ea573a3 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Mon, 6 Jul 2015 15:58:01 -0700 Subject: [PATCH 046/416] Go back to old style of React typings and merge in JSX to both --- react/react-addons-global.d.ts | 2 +- react/react-global.d.ts | 930 +++++++++++++++++++++++++++++++++ react/react-jsx.d.ts | 147 ------ react/react.d.ts | 157 +++++- 4 files changed, 1083 insertions(+), 153 deletions(-) create mode 100644 react/react-global.d.ts delete mode 100644 react/react-jsx.d.ts diff --git a/react/react-addons-global.d.ts b/react/react-addons-global.d.ts index ed6096fa6..508ae0522 100644 --- a/react/react-addons-global.d.ts +++ b/react/react-addons-global.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module React { // diff --git a/react/react-global.d.ts b/react/react-global.d.ts new file mode 100644 index 000000000..3c1a69e43 --- /dev/null +++ b/react/react-global.d.ts @@ -0,0 +1,930 @@ +// Type definitions for React v0.13.1 (internal module) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module React { + // + // React Elements + // ---------------------------------------------------------------------- + + type ReactType = ComponentClass | string; + + interface ReactElement

{ + type: string | ComponentClass

; + props: P; + key: string | number; + ref: string | ((component: Component) => any); + } + + interface ClassicElement

extends ReactElement

{ + type: string | ClassicComponentClass

; + ref: string | ((component: ClassicComponent) => any); + } + + interface DOMElement

extends ClassicElement

{ + type: string; + ref: string | ((component: DOMComponent

) => any); + } + + type HTMLElement = DOMElement; + type SVGElement = DOMElement; + + // + // Factories + // ---------------------------------------------------------------------- + + interface Factory

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

; + } + + interface ClassicFactory

extends Factory

{ + (props?: P, ...children: ReactNode[]): ClassicElement

; + } + + interface DOMFactory

extends ClassicFactory

{ + (props?: P, ...children: ReactNode[]): DOMElement

; + } + + type HTMLFactory = DOMFactory; + type SVGFactory = DOMFactory; + type SVGElementFactory = DOMFactory; + + // + // 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; + + // + // Top Level API + // ---------------------------------------------------------------------- + + function createClass(spec: ComponentSpec): ClassicComponentClass

; + + function createFactory

(type: string): DOMFactory

; + function createFactory

(type: ClassicComponentClass

| string): ClassicFactory

; + function createFactory

(type: ComponentClass

): Factory

; + + function createElement

( + type: string, + props?: P, + ...children: ReactNode[]): DOMElement

; + function createElement

( + type: ClassicComponentClass

| string, + props?: P, + ...children: ReactNode[]): ClassicElement

; + function createElement

( + type: ComponentClass

, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function cloneElement

( + element: DOMElement

, + props?: P, + ...children: ReactNode[]): DOMElement

; + function cloneElement

( + element: ClassicElement

, + props?: P, + ...children: ReactNode[]): ClassicElement

; + function cloneElement

( + element: ReactElement

, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function render

( + element: DOMElement

, + container: Element, + callback?: () => any): DOMComponent

; + function render( + element: ClassicElement

, + container: Element, + callback?: () => any): ClassicComponent; + function render( + element: ReactElement

, + container: Element, + callback?: () => any): Component; + + function unmountComponentAtNode(container: Element): boolean; + function renderToString(element: ReactElement): string; + function renderToStaticMarkup(element: ReactElement): string; + function isValidElement(object: {}): boolean; + function initializeTouchEvents(shouldUseTouch: boolean): void; + + function findDOMNode( + componentOrElement: Component | Element): TElement; + function findDOMNode( + componentOrElement: Component | Element): Element; + + var DOM: ReactDOM; + var PropTypes: ReactPropTypes; + var Children: ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + class Component implements ComponentLifecycle { + constructor(props?: P, context?: any); + setState(f: (prevState: S, props: P) => S, callback?: () => any): void; + setState(state: S, callback?: () => any): void; + forceUpdate(): void; + props: P; + state: S; + context: any; + refs: { + [key: string]: Component + }; + } + + interface ClassicComponent extends Component { + replaceState(nextState: S, callback?: () => any): void; + getDOMNode(): TElement; + getDOMNode(): Element; + isMounted(): boolean; + getInitialState?(): S; + setProps(nextProps: P, callback?: () => any): void; + replaceProps(nextProps: P, callback?: () => any): void; + } + + interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + type HTMLComponent = DOMComponent; + type SVGComponent = DOMComponent; + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + interface ComponentClass

{ + new(props?: P, context?: any): Component; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + defaultProps?: P; + } + + interface ClassicComponentClass

extends ComponentClass

{ + new(props?: P, context?: any): ClassicComponent; + getDefaultProps?(): P; + displayName?: string; + } + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + interface ComponentLifecycle { + componentWillMount?(): void; + componentDidMount?(): void; + componentWillReceiveProps?(nextProps: P, nextContext: any): void; + shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; + componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; + componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; + componentWillUnmount?(): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Mixin; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap + + getDefaultProps?(): P; + getInitialState?(): S; + } + + 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 DragEvent extends SyntheticEvent { + dataTransfer: DataTransfer; + } + + 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 DragEventHandler extends EventHandler {} + 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 {} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface Props { + children?: ReactNode; + key?: string | number; + ref?: string | ((component: T) => any); + } + + interface DOMAttributes extends Props> { + 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?: DragEventHandler; + onDragEnd?: DragEventHandler; + onDragEnter?: DragEventHandler; + onDragExit?: DragEventHandler; + onDragLeave?: DragEventHandler; + onDragOver?: DragEventHandler; + onDragStart?: DragEventHandler; + onDrop?: DragEventHandler; + 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; + }; + } + + // This interface is not complete. Only properties accepting + // unitless numbers are listed here (see CSSProperty.js in React) + interface CSSProperties { + boxFlex?: number; + boxFlexGroup?: number; + columnCount?: number; + flex?: number | string; + flexGrow?: number; + flexShrink?: number; + fontWeight?: number | string; + lineClamp?: number; + lineHeight?: number | string; + opacity?: number; + order?: number; + orphans?: number; + widows?: number; + zIndex?: number; + zoom?: number; + + // SVG-related properties + fillOpacity?: number; + strokeOpacity?: number; + strokeWidth?: number; + } + + interface HTMLAttributes extends DOMAttributes { + ref?: string | ((component: HTMLComponent) => void); + + 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; + formAction?: string; + formEncType?: string; + formMethod?: string; + formNoValidate?: boolean; + formTarget?: string; + frameBorder?: number | string; + headers?: string; + height?: number | string; + hidden?: boolean; + high?: number; + href?: string; + hrefLang?: string; + htmlFor?: string; + httpEquiv?: string; + icon?: string; + id?: string; + label?: string; + lang?: string; + list?: string; + loop?: boolean; + low?: number; + manifest?: string; + marginHeight?: number; + marginWidth?: number; + max?: number | string; + maxLength?: number; + media?: string; + mediaGroup?: string; + method?: string; + min?: number | string; + multiple?: boolean; + muted?: boolean; + name?: string; + noValidate?: boolean; + open?: boolean; + optimum?: number; + 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; + scoped?: boolean; + scrolling?: string; + 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; + unselectable?: boolean; + } + + interface SVGElementAttributes extends HTMLAttributes { + viewBox?: string; + preserveAspectRatio?: string; + } + + interface SVGAttributes extends DOMAttributes { + ref?: string | ((component: SVGComponent) => void); + + cx?: number | string; + cy?: number | string; + d?: string; + dx?: number | string; + dy?: number | string; + fill?: string; + fillOpacity?: number | string; + fontFamily?: string; + fontSize?: number | string; + fx?: number | string; + fy?: number | string; + gradientTransform?: string; + gradientUnits?: string; + markerEnd?: string; + markerMid?: string; + markerStart?: string; + offset?: number | string; + opacity?: number | string; + patternContentUnits?: string; + patternUnits?: string; + points?: string; + preserveAspectRatio?: string; + r?: number | string; + rx?: number | string; + ry?: number | string; + spreadMethod?: string; + stopColor?: string; + stopOpacity?: number | string; + stroke?: string; + strokeDasharray?: string; + strokeLinecap?: string; + strokeOpacity?: number | string; + strokeWidth?: number | string; + textAnchor?: string; + transform?: string; + version?: string; + viewBox?: string; + x1?: number | string; + x2?: number | string; + x?: number | string; + y1?: number | string; + y2?: number | string + y?: number | string; + } + + // + // 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 + svg: SVGElementFactory; + 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; + 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; + } + + // + // 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 JSX { + interface Element extends React.ReactElement { } + interface ElementClass extends React.Component { + render(): JSX.Element; + } + interface ElementAttributesProperty { props: {}; } + + interface IntrinsicElements { + // HTML + a: React.HTMLAttributes; + abbr: React.HTMLAttributes; + address: React.HTMLAttributes; + area: React.HTMLAttributes; + article: React.HTMLAttributes; + aside: React.HTMLAttributes; + audio: React.HTMLAttributes; + b: React.HTMLAttributes; + base: React.HTMLAttributes; + bdi: React.HTMLAttributes; + bdo: React.HTMLAttributes; + big: React.HTMLAttributes; + blockquote: React.HTMLAttributes; + body: React.HTMLAttributes; + br: React.HTMLAttributes; + button: React.HTMLAttributes; + canvas: React.HTMLAttributes; + caption: React.HTMLAttributes; + cite: React.HTMLAttributes; + code: React.HTMLAttributes; + col: React.HTMLAttributes; + colgroup: React.HTMLAttributes; + data: React.HTMLAttributes; + datalist: React.HTMLAttributes; + dd: React.HTMLAttributes; + del: React.HTMLAttributes; + details: React.HTMLAttributes; + dfn: React.HTMLAttributes; + dialog: React.HTMLAttributes; + div: React.HTMLAttributes; + dl: React.HTMLAttributes; + dt: React.HTMLAttributes; + em: React.HTMLAttributes; + embed: React.HTMLAttributes; + fieldset: React.HTMLAttributes; + figcaption: React.HTMLAttributes; + figure: React.HTMLAttributes; + footer: React.HTMLAttributes; + form: React.HTMLAttributes; + h1: React.HTMLAttributes; + h2: React.HTMLAttributes; + h3: React.HTMLAttributes; + h4: React.HTMLAttributes; + h5: React.HTMLAttributes; + h6: React.HTMLAttributes; + head: React.HTMLAttributes; + header: React.HTMLAttributes; + hr: React.HTMLAttributes; + html: React.HTMLAttributes; + i: React.HTMLAttributes; + iframe: React.HTMLAttributes; + img: React.HTMLAttributes; + input: React.HTMLAttributes; + ins: React.HTMLAttributes; + kbd: React.HTMLAttributes; + keygen: React.HTMLAttributes; + label: React.HTMLAttributes; + legend: React.HTMLAttributes; + li: React.HTMLAttributes; + link: React.HTMLAttributes; + main: React.HTMLAttributes; + map: React.HTMLAttributes; + mark: React.HTMLAttributes; + menu: React.HTMLAttributes; + menuitem: React.HTMLAttributes; + meta: React.HTMLAttributes; + meter: React.HTMLAttributes; + nav: React.HTMLAttributes; + noscript: React.HTMLAttributes; + object: React.HTMLAttributes; + ol: React.HTMLAttributes; + optgroup: React.HTMLAttributes; + option: React.HTMLAttributes; + output: React.HTMLAttributes; + p: React.HTMLAttributes; + param: React.HTMLAttributes; + picture: React.HTMLAttributes; + pre: React.HTMLAttributes; + progress: React.HTMLAttributes; + q: React.HTMLAttributes; + rp: React.HTMLAttributes; + rt: React.HTMLAttributes; + ruby: React.HTMLAttributes; + s: React.HTMLAttributes; + samp: React.HTMLAttributes; + script: React.HTMLAttributes; + section: React.HTMLAttributes; + select: React.HTMLAttributes; + small: React.HTMLAttributes; + source: React.HTMLAttributes; + span: React.HTMLAttributes; + strong: React.HTMLAttributes; + style: React.HTMLAttributes; + sub: React.HTMLAttributes; + summary: React.HTMLAttributes; + sup: React.HTMLAttributes; + table: React.HTMLAttributes; + tbody: React.HTMLAttributes; + td: React.HTMLAttributes; + textarea: React.HTMLAttributes; + tfoot: React.HTMLAttributes; + th: React.HTMLAttributes; + thead: React.HTMLAttributes; + time: React.HTMLAttributes; + title: React.HTMLAttributes; + tr: React.HTMLAttributes; + track: React.HTMLAttributes; + u: React.HTMLAttributes; + ul: React.HTMLAttributes; + "var": React.HTMLAttributes; + video: React.HTMLAttributes; + wbr: React.HTMLAttributes; + + // SVG + svg: React.SVGElementAttributes; + + circle: React.SVGAttributes; + defs: React.SVGAttributes; + ellipse: React.SVGAttributes; + g: React.SVGAttributes; + line: React.SVGAttributes; + linearGradient: React.SVGAttributes; + mask: React.SVGAttributes; + path: React.SVGAttributes; + pattern: React.SVGAttributes; + polygon: React.SVGAttributes; + polyline: React.SVGAttributes; + radialGradient: React.SVGAttributes; + rect: React.SVGAttributes; + stop: React.SVGAttributes; + text: React.SVGAttributes; + tspan: React.SVGAttributes; + } +} diff --git a/react/react-jsx.d.ts b/react/react-jsx.d.ts deleted file mode 100644 index 26ee4b220..000000000 --- a/react/react-jsx.d.ts +++ /dev/null @@ -1,147 +0,0 @@ -// Type definitions for React v0.13.1 (JSX support) -// Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft -// Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - -declare module JSX { - interface Element extends React.ReactElement { } - interface ElementClass extends React.Component { } - interface ElementAttributesProperty { props: {}; } - - interface IntrinsicElements { - // HTML - a: React.HTMLAttributes; - abbr: React.HTMLAttributes; - address: React.HTMLAttributes; - area: React.HTMLAttributes; - article: React.HTMLAttributes; - aside: React.HTMLAttributes; - audio: React.HTMLAttributes; - b: React.HTMLAttributes; - base: React.HTMLAttributes; - bdi: React.HTMLAttributes; - bdo: React.HTMLAttributes; - big: React.HTMLAttributes; - blockquote: React.HTMLAttributes; - body: React.HTMLAttributes; - br: React.HTMLAttributes; - button: React.HTMLAttributes; - canvas: React.HTMLAttributes; - caption: React.HTMLAttributes; - cite: React.HTMLAttributes; - code: React.HTMLAttributes; - col: React.HTMLAttributes; - colgroup: React.HTMLAttributes; - data: React.HTMLAttributes; - datalist: React.HTMLAttributes; - dd: React.HTMLAttributes; - del: React.HTMLAttributes; - details: React.HTMLAttributes; - dfn: React.HTMLAttributes; - dialog: React.HTMLAttributes; - div: React.HTMLAttributes; - dl: React.HTMLAttributes; - dt: React.HTMLAttributes; - em: React.HTMLAttributes; - embed: React.HTMLAttributes; - fieldset: React.HTMLAttributes; - figcaption: React.HTMLAttributes; - figure: React.HTMLAttributes; - footer: React.HTMLAttributes; - form: React.HTMLAttributes; - h1: React.HTMLAttributes; - h2: React.HTMLAttributes; - h3: React.HTMLAttributes; - h4: React.HTMLAttributes; - h5: React.HTMLAttributes; - h6: React.HTMLAttributes; - head: React.HTMLAttributes; - header: React.HTMLAttributes; - hr: React.HTMLAttributes; - html: React.HTMLAttributes; - i: React.HTMLAttributes; - iframe: React.HTMLAttributes; - img: React.HTMLAttributes; - input: React.HTMLAttributes; - ins: React.HTMLAttributes; - kbd: React.HTMLAttributes; - keygen: React.HTMLAttributes; - label: React.HTMLAttributes; - legend: React.HTMLAttributes; - li: React.HTMLAttributes; - link: React.HTMLAttributes; - main: React.HTMLAttributes; - map: React.HTMLAttributes; - mark: React.HTMLAttributes; - menu: React.HTMLAttributes; - menuitem: React.HTMLAttributes; - meta: React.HTMLAttributes; - meter: React.HTMLAttributes; - nav: React.HTMLAttributes; - noscript: React.HTMLAttributes; - object: React.HTMLAttributes; - ol: React.HTMLAttributes; - optgroup: React.HTMLAttributes; - option: React.HTMLAttributes; - output: React.HTMLAttributes; - p: React.HTMLAttributes; - param: React.HTMLAttributes; - picture: React.HTMLAttributes; - pre: React.HTMLAttributes; - progress: React.HTMLAttributes; - q: React.HTMLAttributes; - rp: React.HTMLAttributes; - rt: React.HTMLAttributes; - ruby: React.HTMLAttributes; - s: React.HTMLAttributes; - samp: React.HTMLAttributes; - script: React.HTMLAttributes; - section: React.HTMLAttributes; - select: React.HTMLAttributes; - small: React.HTMLAttributes; - source: React.HTMLAttributes; - span: React.HTMLAttributes; - strong: React.HTMLAttributes; - style: React.HTMLAttributes; - sub: React.HTMLAttributes; - summary: React.HTMLAttributes; - sup: React.HTMLAttributes; - table: React.HTMLAttributes; - tbody: React.HTMLAttributes; - td: React.HTMLAttributes; - textarea: React.HTMLAttributes; - tfoot: React.HTMLAttributes; - th: React.HTMLAttributes; - thead: React.HTMLAttributes; - time: React.HTMLAttributes; - title: React.HTMLAttributes; - tr: React.HTMLAttributes; - track: React.HTMLAttributes; - u: React.HTMLAttributes; - ul: React.HTMLAttributes; - "var": React.HTMLAttributes; - video: React.HTMLAttributes; - wbr: React.HTMLAttributes; - - // SVG - svg: React.SVGElementAttributes; - - circle: React.SVGAttributes; - defs: React.SVGAttributes; - ellipse: React.SVGAttributes; - g: React.SVGAttributes; - line: React.SVGAttributes; - linearGradient: React.SVGAttributes; - mask: React.SVGAttributes; - path: React.SVGAttributes; - pattern: React.SVGAttributes; - polygon: React.SVGAttributes; - polyline: React.SVGAttributes; - radialGradient: React.SVGAttributes; - rect: React.SVGAttributes; - stop: React.SVGAttributes; - text: React.SVGAttributes; - tspan: React.SVGAttributes; - } -} diff --git a/react/react.d.ts b/react/react.d.ts index b23a8240e..5fbad0d22 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1,9 +1,9 @@ -// Type definitions for React v0.13.1 (internal and external module) +// Type definitions for React v0.13.1 (external module) // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign +// Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module React { +declare module __React { // // React Elements // ---------------------------------------------------------------------- @@ -48,6 +48,7 @@ declare module React { type HTMLFactory = DOMFactory; type SVGFactory = DOMFactory; + type SVGElementFactory = DOMFactory; // // React Nodes @@ -691,6 +692,7 @@ declare module React { wbr: HTMLFactory; // SVG + svg: SVGElementFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; @@ -705,7 +707,6 @@ declare module React { radialGradient: SVGFactory; rect: SVGFactory; stop: SVGFactory; - svg: SVGFactory; text: SVGFactory; tspan: SVGFactory; } @@ -785,5 +786,151 @@ declare module React { } declare module "react" { - export = React; + export = __React; +} + +declare module JSX { + import React = __React; + + interface Element extends React.ReactElement { } + interface ElementClass extends React.Component { + render(): JSX.Element; + } + interface ElementAttributesProperty { props: {}; } + + interface IntrinsicElements { + // HTML + a: React.HTMLAttributes; + abbr: React.HTMLAttributes; + address: React.HTMLAttributes; + area: React.HTMLAttributes; + article: React.HTMLAttributes; + aside: React.HTMLAttributes; + audio: React.HTMLAttributes; + b: React.HTMLAttributes; + base: React.HTMLAttributes; + bdi: React.HTMLAttributes; + bdo: React.HTMLAttributes; + big: React.HTMLAttributes; + blockquote: React.HTMLAttributes; + body: React.HTMLAttributes; + br: React.HTMLAttributes; + button: React.HTMLAttributes; + canvas: React.HTMLAttributes; + caption: React.HTMLAttributes; + cite: React.HTMLAttributes; + code: React.HTMLAttributes; + col: React.HTMLAttributes; + colgroup: React.HTMLAttributes; + data: React.HTMLAttributes; + datalist: React.HTMLAttributes; + dd: React.HTMLAttributes; + del: React.HTMLAttributes; + details: React.HTMLAttributes; + dfn: React.HTMLAttributes; + dialog: React.HTMLAttributes; + div: React.HTMLAttributes; + dl: React.HTMLAttributes; + dt: React.HTMLAttributes; + em: React.HTMLAttributes; + embed: React.HTMLAttributes; + fieldset: React.HTMLAttributes; + figcaption: React.HTMLAttributes; + figure: React.HTMLAttributes; + footer: React.HTMLAttributes; + form: React.HTMLAttributes; + h1: React.HTMLAttributes; + h2: React.HTMLAttributes; + h3: React.HTMLAttributes; + h4: React.HTMLAttributes; + h5: React.HTMLAttributes; + h6: React.HTMLAttributes; + head: React.HTMLAttributes; + header: React.HTMLAttributes; + hr: React.HTMLAttributes; + html: React.HTMLAttributes; + i: React.HTMLAttributes; + iframe: React.HTMLAttributes; + img: React.HTMLAttributes; + input: React.HTMLAttributes; + ins: React.HTMLAttributes; + kbd: React.HTMLAttributes; + keygen: React.HTMLAttributes; + label: React.HTMLAttributes; + legend: React.HTMLAttributes; + li: React.HTMLAttributes; + link: React.HTMLAttributes; + main: React.HTMLAttributes; + map: React.HTMLAttributes; + mark: React.HTMLAttributes; + menu: React.HTMLAttributes; + menuitem: React.HTMLAttributes; + meta: React.HTMLAttributes; + meter: React.HTMLAttributes; + nav: React.HTMLAttributes; + noscript: React.HTMLAttributes; + object: React.HTMLAttributes; + ol: React.HTMLAttributes; + optgroup: React.HTMLAttributes; + option: React.HTMLAttributes; + output: React.HTMLAttributes; + p: React.HTMLAttributes; + param: React.HTMLAttributes; + picture: React.HTMLAttributes; + pre: React.HTMLAttributes; + progress: React.HTMLAttributes; + q: React.HTMLAttributes; + rp: React.HTMLAttributes; + rt: React.HTMLAttributes; + ruby: React.HTMLAttributes; + s: React.HTMLAttributes; + samp: React.HTMLAttributes; + script: React.HTMLAttributes; + section: React.HTMLAttributes; + select: React.HTMLAttributes; + small: React.HTMLAttributes; + source: React.HTMLAttributes; + span: React.HTMLAttributes; + strong: React.HTMLAttributes; + style: React.HTMLAttributes; + sub: React.HTMLAttributes; + summary: React.HTMLAttributes; + sup: React.HTMLAttributes; + table: React.HTMLAttributes; + tbody: React.HTMLAttributes; + td: React.HTMLAttributes; + textarea: React.HTMLAttributes; + tfoot: React.HTMLAttributes; + th: React.HTMLAttributes; + thead: React.HTMLAttributes; + time: React.HTMLAttributes; + title: React.HTMLAttributes; + tr: React.HTMLAttributes; + track: React.HTMLAttributes; + u: React.HTMLAttributes; + ul: React.HTMLAttributes; + "var": React.HTMLAttributes; + video: React.HTMLAttributes; + wbr: React.HTMLAttributes; + + // SVG + svg: React.SVGElementAttributes; + + circle: React.SVGAttributes; + defs: React.SVGAttributes; + ellipse: React.SVGAttributes; + g: React.SVGAttributes; + line: React.SVGAttributes; + linearGradient: React.SVGAttributes; + mask: React.SVGAttributes; + path: React.SVGAttributes; + pattern: React.SVGAttributes; + polygon: React.SVGAttributes; + polyline: React.SVGAttributes; + radialGradient: React.SVGAttributes; + rect: React.SVGAttributes; + stop: React.SVGAttributes; + text: React.SVGAttributes; + tspan: React.SVGAttributes; + } } From 5a55b05ad98267b8b898c6e5c3436d3123704c5e Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Sun, 5 Jul 2015 13:27:50 +0700 Subject: [PATCH 047/416] Add typings for Atom's first-mate library --- first-mate/.editorconfig | 3 + first-mate/first-mate-tests.ts | 15 +++++ first-mate/first-mate.d.ts | 108 +++++++++++++++++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 first-mate/.editorconfig create mode 100644 first-mate/first-mate-tests.ts create mode 100644 first-mate/first-mate.d.ts diff --git a/first-mate/.editorconfig b/first-mate/.editorconfig new file mode 100644 index 000000000..570211f89 --- /dev/null +++ b/first-mate/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = tab +indent_size = 4 diff --git a/first-mate/first-mate-tests.ts b/first-mate/first-mate-tests.ts new file mode 100644 index 000000000..1a181de4a --- /dev/null +++ b/first-mate/first-mate-tests.ts @@ -0,0 +1,15 @@ +/// + +import firstMate = require('first-mate'); +var GrammarRegistry = firstMate.GrammarRegistry; +var Grammar = firstMate.GrammarRegistry; +type IToken = AtomFirstMate.IToken; +// The import and type aliasing above can be done more concisely in TypeScript 1.5+: +//import { GrammarRegistry, Grammar, IToken } from "first-mate"; + +var registry = new GrammarRegistry({ maxTokensPerLine: 100 }); +var grammar = registry.loadGrammarSync('javascript.json'); +var result = grammar.tokenizeLine('var text = "hello world";'); +result.tokens.forEach((token) => { + console.log("Token text: '" + token.value + "' with scopes: " + token.scopes); +}); diff --git a/first-mate/first-mate.d.ts b/first-mate/first-mate.d.ts new file mode 100644 index 000000000..d780116c2 --- /dev/null +++ b/first-mate/first-mate.d.ts @@ -0,0 +1,108 @@ +// Type definitions for first-mate v4.1.7 +// Project: https://github.com/atom/first-mate/ +// Definitions by: Vadim Macagon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module AtomFirstMate { + type Disposable = AtomEventKit.Disposable; + + interface IToken { + value: string; + scopes: string[]; + } + + /** Result returned by `Grammar.tokenizeLine`. */ + interface TokenizeLineResult { + /** Text that was tokenized. */ + line: string; + tags: any[]; + /** + * This is a dynamic property that will only be available if `Grammar.tokenizeLine` was called + * with `compatibilityMode` set to `true` (the default). + */ + tokens?: IToken[]; + /** + * The tokenized state at the end of the line. This should be passed back into `tokenizeLine` + * when tokenizing the next line in the file/buffer. + */ + ruleStack: Rule[] + } + + /** Instance side of Rule class. */ + interface Rule { + } + + /** Static side of Grammar class. */ + interface GrammarStatic { + prototype: Grammar; + new (registry: GrammarRegistry, options?: any): Grammar; + } + + /** Instance side of Grammar class. */ + interface Grammar { + constructor: GrammarStatic; + onDidUpdate(callback: Function): Disposable; + /** + * Tokenizes all lines in a string. + * + * @param text A string containing one or more lines. + * @return An array of token arrays, one token array per line. + */ + tokenizeLines(text: string): Array>; + /** + * Tokenizes a line of text. + * + * @param line Text to be tokenized. + * @param firstLine Indicates whether `line` is the first line in the file/buffer, + * defaults to `false`. + * @param compatibilityMode `true` by default. + * @return An object containing tokens for the given line. + */ + tokenizeLine( + line: string, ruleStack?: Rule[], firstLine?: boolean, compatibilityMode?: boolean + ): TokenizeLineResult; + } + + /** Grammar that tokenizes lines of text. */ + var Grammar: GrammarStatic; + + /** Static side of GrammarRegistry class. */ + interface GrammarRegistryStatic { + prototype: GrammarRegistry; + new (options?: { maxTokensPerLine: number }): GrammarRegistry; + } + + /** Instance side of GrammarRegistry class. */ + interface GrammarRegistry { + constructor: GrammarRegistryStatic; + + // Event Subscription + + onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable; + onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable; + + // Managing Grammars + + getGrammars(): Grammar[]; + grammarForScopeName(scopeName: string): Grammar; + addGrammar(grammar: Grammar): Disposable; + removeGrammarForScopeName(scopeName: string): Grammar; + readGrammarSync(grammarPath: string): Grammar; + readGrammar(grammarPath: string, callback: (error: Error, grammar: Grammar) => void): void; + loadGrammarSync(grammarPath: string): Grammar; + loadGrammar(grammarPath: string, callback: (error: Error, grammar: Grammar) => void): void; + grammarOverrideForPath(filePath: string): Grammar; + setGrammarOverrideForPath(filePath: string, scopeName: string): Grammar; + clearGrammarOverrides(): void; + selectGrammar(filePath: string, fileContents: string): Grammar; + } + + /** Registry containing one or more grammars. */ + var GrammarRegistry: GrammarRegistryStatic; +} + +declare module 'first-mate' { + export = AtomFirstMate; +} From 3387b8b71553573ec44125b9daf81d9c6e22efa9 Mon Sep 17 00:00:00 2001 From: pafflique Date: Tue, 7 Jul 2015 16:57:09 +0300 Subject: [PATCH 048/416] Collection.add signature fix http://backbonejs.org/#Collection-add - "Returns the added (or preexisting, if duplicate) models." --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5..b9039be35 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -181,8 +181,8 @@ declare module Backbone { comparator(element: TModel): number; comparator(compare: TModel, to?: TModel): number; - add(model: TModel, options?: AddOptions): Collection; - add(models: TModel[], options?: AddOptions): Collection; + add(model: TModel, options?: AddOptions): TModel; + add(models: TModel[], options?: AddOptions): TModel[]; at(index: number): TModel; /** * Get a model from a collection, specified by an id, a cid, or by passing in a model. From 70761a5ae8f624f2ce3517540a93bc68de5f3f4c Mon Sep 17 00:00:00 2001 From: pafflique Date: Tue, 7 Jul 2015 17:11:04 +0300 Subject: [PATCH 049/416] Allow mixed content in Collection.add Valid for TypeScript 1.4 --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index b9039be35..275dba237 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -181,8 +181,8 @@ declare module Backbone { comparator(element: TModel): number; comparator(compare: TModel, to?: TModel): number; - add(model: TModel, options?: AddOptions): TModel; - add(models: TModel[], options?: AddOptions): TModel[]; + add(model: {}|TModel, options?: AddOptions): TModel; + add(models: ({}|TModel)[], options?: AddOptions): TModel[]; at(index: number): TModel; /** * Get a model from a collection, specified by an id, a cid, or by passing in a model. From e850267d120af0863d617be2a7b3e043a36fb800 Mon Sep 17 00:00:00 2001 From: Alexandre BODIN Date: Tue, 7 Jul 2015 18:10:41 +0200 Subject: [PATCH 050/416] Add Object type for tls in server.connection options --- hapi/hapi-8.2.0.d.ts | 2212 ++++++++++++++++++++++++++++++++++++++ hapi/hapi-tests-8.2.0.ts | 99 ++ hapi/hapi.d.ts | 150 +-- 3 files changed, 2386 insertions(+), 75 deletions(-) create mode 100644 hapi/hapi-8.2.0.d.ts create mode 100644 hapi/hapi-tests-8.2.0.ts diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts new file mode 100644 index 000000000..8d3da2620 --- /dev/null +++ b/hapi/hapi-8.2.0.d.ts @@ -0,0 +1,2212 @@ +// Type definitions for hapi 8.2.0 +// Project: http://github.com/spumko/hapi +// Definitions by: Jason Swearingen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//This is a total rewrite of Hakubo's original hapi.d.ts, as it was out of date/incomplete. + + +/// +/// + + + + +declare module "hapi" { + import http = require("http"); + import stream = require("stream"); + import Events = require("events"); + + interface IDictionary { + [key: string]: T; + } + + /** Boom Module for errors. https://github.com/hapijs/boom + * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */ + export interface IBoom extends Error { + /** if true, indicates this is a Boom object instance. */ + isBoom: boolean; + /** convenience bool indicating status code >= 500. */ + isServer: boolean; + /** the error message. */ + message: string; + /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ + output: { + /** the HTTP status code (typically 4xx or 5xx). */ + statusCode: number; + /** an object containing any HTTP headers where each key is a header name and value is the header content. */ + headers: IDictionary; + /** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */ + payload: { + /** the HTTP status code, derived from error.output.statusCode. */ + statusCode: number; + /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ + error: string; + /** the error message derived from error.message. */ + message: string; + }; + }; + /** reformat()rebuilds error.output using the other object properties. */ + reformat(): void; + + } + + /** cache functionality via the "CatBox" module. */ + export interface ICatBoxCacheOptions { + /** a prototype function or catbox engine object. */ + engine: any; + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ + name?: string; + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + } + + /** Any connections configuration server defaults can be included to override and customize the individual connection. */ + export interface ISeverConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ + host?: string; + /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ + address?: string; + /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ + port?: string|number; + /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ + uri?: string; + /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ + listener?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ + statuses: number[]; + }; + /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ + labels?: string|string[]; + /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean; + + } + + export interface IConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: any; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: IRouteAdditionalConfigurationOptions; + state?: IServerState; + } + + /** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ + export interface IServerOptions { + /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). + a configuration object with the following options: + enginea prototype function or catbox engine object. + namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. + sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + other options passed to the catbox strategy used. + an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ + cache?: string|ICatBoxCacheOptions|Array|any; + /** sets the default connections configuration which can be overridden by each connection where: */ + connections?: IConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ + debug?: boolean|{ + /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log: string[]; + /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ + request: string[]; + }; + /** file system related settings*/ + files?: { + /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ + etagsCacheMaxSize?: number; + }; + /** process load monitoring*/ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ + sampleInterval?: number; + }; + + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ + mime?: any; + /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ + minimal?: boolean; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ + plugins?: IDictionary; + + } + + export interface IServerViewCompile { + (template: string, options: any): void; + (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; + } + + export interface IServerViewsAdditionalOptions { + /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ + path?: string; + /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). + */ + partialsPath?: string; + /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ + helpersPath?: string; + /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ + relativeTo?: string; + + /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ + layout?: boolean; + /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ + layoutPath?: string; + /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ + layoutKeywork?: string; + /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ + encoding?: string; + /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ + isCached?: boolean; + /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ + allowAbsolutePaths?: boolean; + /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ + allowInsecureAccess?: boolean; + /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ + compileOptions?: any; + /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ + runtimeOptions?: any; + /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ + contentType?: string; + /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ + compileMode?: string; + /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ + context?: any; + } + + export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { + /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. + * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ + module: { + compile? (template: any, options: any): (context: any, options: any) => void; + compile? (template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; + }; + } + + /**Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods. + */ + export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { + /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ + engines: IDictionary|IServerViewsEnginesOptions; + /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ + defaultExtension?: string; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply { + (err: Error, + result?: string|number|boolean|Buffer|stream.Stream | Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any + ): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; + + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + * The data argument is only used for passing back authentication data and is ignored elsewhere. */ + continue(credentialData?: any): void; + + /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ + file( + /** the file path. */ + path: string, + /** optional settings: */ + options?: { + /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /** specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean|string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed: boolean; + }): void; + /** Concludes the handler activity by returning control over to the router with a templatized view response. + the response flow control rules apply. */ + + view( + /** the template filename and path, relative to the templates path configured via the server views manager. */ + template: string, + /** optional object used by the template to render context-specific result. Defaults to no context {}. */ + context?: {}, + /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ + options?: any): Response; + /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed + The response flow control rules do not apply. */ + close(options?: { + /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ + end?: boolean; + }): void; + /** Proxies the request to an upstream endpoint. + the response flow control rules do not apply. */ + + proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ + options: IProxyHandlerConfig): void; + /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). + he response flow control rules apply. */ + redirect(uri: string): Response; + } + + export interface ISessionHandler { + (request: Request, reply: IReply): void; + } + export interface IRequestHandler { + (request: Request): T; + } + + + export interface IFailAction { + (source: string, error: any, next: () => void): void + } + /** generates a reverse proxy handler */ + export interface IProxyHandlerConfig { + /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ + host?: string; + /** the upstream service port. */ + port?: number; + /** The protocol to use when making a request to the proxied host: + 'http' + 'https'*/ + protocol?: string; + /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ + uri?: string; + /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ + passThrough?: boolean; + /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ + localStatePassThrough?: boolean; + /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ + rejectUnauthorized?: boolean; + /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ + xforward?: boolean; + /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ + redirects?: boolean|number; + /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ + timeout?: number; + /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: + request - is the incoming request object. + callback - is function(err, uri, headers) where: + err - internal error condition. + uri - the absolute proxy URI. + headers - optional object where each key is an HTTP request header and the value is the header content.*/ + mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; + /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ + onResponse?: ( + err: any, + res: http.ServerResponse, + req: Request, + reply: () => void, + settings: IProxyHandlerConfig, + ttl: number + ) => void; + /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ + ttl?: number; + /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ + agent?: http.Agent; + /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ + maxSockets?: boolean|number; + } + /** TODO: fill in joi definition */ + export interface IJoi { + + } + /** a validation function using the signature function(value, options, next) */ + export interface IValidationFunction { + + (/** the object containing the path parameters. */ + value: any, + /** the server validation options. */ + options: any, + /** the callback function called when validation is completed. */ + next: (err: any, value: any) => void): void; + } + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + export interface IRouteFailFunction { + /** a custom error handler function with the signature 'function(request, reply, source, error)` */ + ( + /** - the [request object]. */ + request: Request, + /** the continuation reply interface. */ + reply: IReply, + /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ + source: string, + /** the error object prepared for the client response (including the validation function error under error.data). */ + error: any): void; + } + + /** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ + export interface IRouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. + a string with the name of an authentication strategy registered with server.auth.strategy(). + an object */ + auth?: boolean|string| + { + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + 'required'authentication is required. + 'optional'authentication is optional (must be valid if present). + 'try'same as 'optional' but allows for invalid authentication. */ + mode: string; + /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies: string | Array; + /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: + falseno payload authentication.This is the default value. + 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. + 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ + payload?: string; + /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ + scope?: string|Array|boolean; + /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: + anythe authentication can be on behalf of a user or application.This is the default value. + userthe authentication must be on behalf of a user. + appthe authentication must be on behalf of an application. */ + entity?: string; + }; + /** an object passed back to the provided handler (via this) when called. */ + bind?: any; + /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ + cache?: { + /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: + fault'no privacy flag.This is the default setting. + 'public'mark the response as suitable for public caching. + 'private'mark the response as suitable only for private caching. */ + privacy: string; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ + expiresIn: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ + expiresAt: string; + }; + /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ + cors?: { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ + origin?: Array; + /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ + matchOrigin?: boolean; + /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ + isOriginExposed?: boolean; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ + headers?: string[]; + /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ + methods?: string[]; + /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ + additionalMethods?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ + credentials?: boolean; + /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ + override?: boolean; + }; + /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ + files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ + relativeTo: string; + }; + + /** an alternative location for the route handler option. */ + handler?: ISessionHandler | string | IRouteHandlerConfig; + /** an optional unique identifier used to look up the route using server.lookup(). */ + id?: number; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ + json?: { + /** the replacer function or array.Defaults to no action. */ + replacer?: Function | string[]; + /** number of spaces to indent nested object keys.Defaults to no indentation. */ + space?: number|string; + /** string suffix added after conversion to JSON string.Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ + jsonp?: string; + /** determines how the request payload is processed: */ + payload?: { + /** the type of payload representation requested. The value must be one of: + 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. + 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ + output?: string; + /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + 'application/json' + 'application/x-www-form-urlencoded' + 'application/octet-stream' + 'text/ *' + 'multipart/form-data' */ + parse?: string | boolean; + /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ + timeout?: number; + /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ + uploads?: string; + /** determines how to handle payload parsing errors. Allowed values are: + 'error'return a Bad Request (400) error response. This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action and continue processing the request. */ + failAction?: string; + }; + /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: IDictionary; + /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ + pre?: any[]; + /** validation rules for the outgoing response payload (response body).Can only validate object response: */ + response?: { + /** the default response object validation rules (for all non-error responses) expressed as one of: + trueany payload allowed (no validation performed). This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the response object. + optionsthe server validation options. + next(err)the callback function called when validation is completed. */ + schema: boolean|any; + /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ + status: number; + /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ + sample: number; + /** defines what to do when a response fails validation.Options are: + errorreturn an Internal Server Error (500) error response.This is the default value. + loglog the error but send the response. */ + failAction: string; + /** if true, applies the validation rule changes to the response.Defaults to false. */ + modify: boolean; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options: any; + }; + /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ + security?: boolean| { + /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ + hsts: boolean|number|{ + /** the max- age portion of the header, as a number.Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubdomains flag to the header. */ + includeSubdomains?: boolean; + }; + /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe: { + /** either 'deny', 'sameorigin', or 'allow-from' */ + rule: string; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ + xss: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ + noOpen: boolean; + /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ + noSniff: boolean; + }; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ + parse: boolean; + /** determines how to handle cookie parsing errors.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'report the error but continue processing the request. + 'ignore'take no action. */ + failAction: string; + }; + /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ + validate?: { + /** validation rules for incoming request headers.Values allowed: + * trueany headers allowed (no validation performed).This is the default. + falseno headers allowed (this will cause all valid HTTP requests to fail). + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the request headers. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. + */ + headers?: boolean | IJoi | IValidationFunction; + + + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: + trueany path parameters allowed (no validation performed).This is the default. + falseno path variables allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the path parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + params?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: + trueany query parameters allowed (no validation performed).This is the default. + falseno query parameters allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the query parameters. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + query?: boolean | IJoi | IValidationFunction; + /** validation rules for an incoming request payload (request body).Values allowed: + trueany payload allowed (no validation performed).This is the default. + falseno payload allowed. + a Joi validation object. + a validation function using the signature function(value, options, next) where: + valuethe object containing the payload object. + optionsthe server validation options. + next(err, value)the callback function called when validation is completed. */ + payload?: boolean | IJoi | IValidationFunction; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** determines how to handle invalid requests.Allowed values are: + 'error'return a Bad Request (400) error response.This is the default value. + 'log'log the error but continue processing the request. + 'ignore'take no action. + OR a custom error handler function with the signature 'function(request, reply, source, error)` where: + requestthe request object. + replythe continuation reply interface. + sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). + errorthe error object prepared for the client response (including the validation function error under error.data). */ + failAction?: string | IRouteFailFunction; + /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ + options?: any; + }; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ + server: boolean|number; + /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ + socket: boolean|number; + }; + + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route description used for generating documentation (string). + */ + description?: string; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route notes used for generating documentation (string or array of strings). + */ + notes?: string|string[]; + /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + *route tags used for generating documentation (array of strings). + */ + tags?: string[] + } + /** server.realm http://hapijs.com/api#serverrealm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + }; + */ + export interface IServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ + modifiers: { + /** routes preferences: */ + route: { + /** - the route path prefix used by any calls to server.route() from the server. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + }; + + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: IDictionary; + /** settings overrides */ + settings: { + files: { + relativeTo: any; + }; + bind: any; + } + } + /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ + export interface IServerState { +/** - the cookie name string. */name: string; + +/** - are the optional cookie settings: */options: { +/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; +/** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; +/** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean +/** - the path scope.Defaults to null (no path).*/path: any; +/** - the domain scope.Defaults to null (no domain). */domain: any; + /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization. Options are: + 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON-stringified than encoded using Base64. + 'form' - object value is encoded using the x-www-form-urlencoded method. + 'iron' - Encrypts and sign the value using iron.*/ + encoding: string; +/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { +/** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; +/** - password used for HMAC key generation.*/password: string; + }; +/** - password used for 'iron' encoding.*/password: string; +/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; +/** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; +/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; +/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; +/** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; + }; + } + + export interface IFileHandlerConfig { + /** a path string or function as described above.*/ + path: string; + /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ + filename?: string; + /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: + false - header is not included. This is the default value. + 'attachment' + 'inline'*/ + mode?: boolean| string; + /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ + lookupCompressed: boolean; + } + + /**http://hapijs.com/api#route-handler + Built-in handlers + + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ + export interface IRouteHandlerConfig { + /** generates a static file endpoint for serving a single file. file can be set to: + a relative or absolute file path string (relative paths are resolved based on the route files configuration). + a function with the signature function(request) which returns the relative or absolute file path. + an object with the following options */ + file?: string | IRequestHandler |IFileHandlerConfig; + /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. + listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. + defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ + directory?: { + path: string |Array | IRequestHandler | IRequestHandler>; + index?: boolean; + listing?: boolean; + showHidden?: boolean; + redirectToSlash?: boolean; + lookupCompressed?: boolean; + defaultExtension?: string; + }; + proxy?: IProxyHandlerConfig; + view?: string | { + template: string; + context: { + payload: any; + params: any; + query: any; + pre: any; + } + }; + config?: { + handler: any; + bind: any; + app: any; + plugins: { + [name: string]: any; + }; + pre: Array<() => void>; + validate: { + headers: any; + params: any; + query: any; + payload: any; + errorFields?: any; + failAction?: string | IFailAction; + }; + payload: { + output: { + data: any; + stream: any; + file: any; + }; + parse?: any; + allow?: string|Array; + override?: string; + maxBytes?: number; + uploads?: number; + failAction?: string; + }; + response: { + schema: any; + sample: number; + failAction: string; + }; + cache: { + privacy: string; + expiresIn: number; + expiresAt: number; + }; + auth: string|boolean|{ + mode: string; + strategies: Array; + payload?: boolean|string; + tos?: boolean|string; + scope?: string|Array; + entity: string; + }; + cors?: boolean; + jsonp?: string; + description?: string; + notes?: string|Array; + tags?: Array; + }; + } + /** Route configuration + The route configuration object*/ + export interface IRouteConfiguration { + /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ + path: string; + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ + method: string|string[]; + /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ + vhost?: string; + /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ + handler: ISessionHandler | string | IRouteHandlerConfig; + /** - additional route options.*/ + config?: IRouteAdditionalConfigurationOptions; + } + /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ + export interface IRoute { + + + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string|Array; + /** the [active realm] associated with the route.*/ + realm: IServerRealm; + /** the [route options] object with all defaults applied. */ + settings: IRouteAdditionalConfigurationOptions; + } + + export interface IServerAuthScheme { + /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: + request - the request object. + reply - the reply interface the authentication method must call when done authenticating the request where: + reply(err, response, result) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + result - an object containing: + credentials - the authenticated credentials. + artifacts - optional authentication artifacts. + reply.continue(result) - is called if authentication succeeded where: + result - same object as result above. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var scheme = function (server, options) { + return { + authenticate: function (request, reply) { + var req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + return reply(null, { credentials: { user: 'john' } }); + } + }; + }; + server.auth.scheme('custom', scheme);*/ + authenticate(request: Request, reply: IReply): void; + /** payload(request, reply) - optional function called to authenticate the request payload where: + request - the request object. + reply(err, response) - is called if authentication failed where: + err - any authentication error. + response - any authentication response action such as redirection. Ignored if err is present, otherwise required. + reply.continue() - is called if payload authentication succeeded. + When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ + payload? (request: Request, reply: IReply): void; + /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: + request - the request object. + reply(err, response) - is called if an error occurred where: + err - any authentication error. + response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + reply.continue() - is called if the operation succeeded.*/ + response? (request: Request, reply: IReply): void; + /** an optional object */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ + payload: boolean; + } + } + + + + export interface IServerInject { + (options: { + /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ + method: string; + /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ + url: string; + /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ + headers: IDictionary; + /**- an optional string or buffer containing the request payload (object must be manually converted to a string first). Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ + payload: string|Buffer; + /**an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ + credentials: any; + /**object with options used to simulate client request stream conditions for testing: + error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + end - if false, does not end the stream. Defaults to true.*/ + simulate: { + error: boolean; + close: boolean; + end: boolean; + }; + }, + callback: ( + /**the response object where: + statusCode - the HTTP status code. + headers - an object containing the headers set. + payload - the response payload string. + rawPayload - the raw response payload buffer. + raw - an object with the injection request and response objects: + req - the simulated node request object. + res - the simulated node response object. + result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + request - the request object.*/ + res: { statusCode: number; headers: IDictionary; payload: string; rawPayload: Buffer; raw: { req: http.ClientRequest; res: http.ServerResponse }; result: string; request: Request }) => void + ):void; + + } + + + /** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path.*/ + export interface IConnectionTable { + info: any; + labels: any; + table: IRoute[]; + } + + export interface ICookieSettings { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl?: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure?: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly?: boolean; + /** - the path scope.Defaults to null (no path).*/ + path?: string; + /** - the domain scope.Defaults to null (no domain).*/ + domain?: any; + /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: + request - the request object. + next - the continuation function using the function(err, value) signature.*/ + autoValue?: (request: Request, next: (err: any, value: any) => void) => void; + /** - encoding performs on the provided value before serialization.Options are: + 'none' - no encoding.When used, the cookie value must be a string.This is the default value. + 'base64' - string value is encoded using Base64. + 'base64json' - object value is JSON- stringified than encoded using Base64. + 'form' - object value is encoded using the x- www - form - urlencoded method. */ + encoding?: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: + integrity - algorithm options.Defaults to require('iron').defaults.integrity. + password - password used for HMAC key generation. */ + sign?: { integrity: any; password: string; } + password?: string; + iron?: any; + ignoreErrors?: boolean; + clearInvalid?: boolean; + strictHeader?: boolean; + passThrough?: any; + } + + /** method - the method function with the signature is one of: + function(arg1, arg2, ..., argn, next) where: + arg1, arg2, etc. - the method function arguments. + next - the function called when the method is done with the signature function(err, result, ttl) where: + err - error response if the method failed. + result - the return value. + ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + function(arg1, arg2, ..., argn) where: + arg1, arg2, etc. - the method function arguments. + the callback option is set to false. + the method must returns a value (result, Error, or a promise) or throw an Error.*/ + export interface IServerMethod { + //(): void; + //(next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any): void; + //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; + //(arg1: any, arg2: any): void; + (...args: any[]): void; + + } + /** options - optional configuration: + bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. + cache - the same cache configuration used in server.cache(). + callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ + export interface IServerMethodOptions { + bind?: any; + cache?: ICatBoxCacheOptions; + callback?: boolean; + generateKey?(args: any[]): string; + } + /** Request object + + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + Request events + + The request object supports the following events: + + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the request payload finished reading. The event method signature is function (). + 'disconnect' - emitted when a request errors or aborts unexpectedly. + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + var hash = Crypto.createHash('sha1'); + request.on('peek', function (chunk) { + + hash.update(chunk); + }); + + request.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + request.once('disconnect', function () { + + console.error('request aborted'); + }); + + return reply.continue(); + });*/ + export class Request extends Events.EventEmitter { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** authentication information*/ + auth: { + /** true is the request has been successfully authenticated, otherwise false.*/ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication.*/ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ + artifacts: any; + /** the route authentication mode.*/ + mode: any; + /** the authentication error is failed and mode set to 'try'.*/ + error: any; + /** an object used by the ['cookie' authentication scheme] https://github.com/hapijs/hapi-auth-cookie */ + session: any + }; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ + domain: any; + /** the raw request headers (references request.raw.headers).*/ + headers: IDictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: number; + /** request information */ + info: { + /** request reception timestamp. */ + received: number; + /** request response timestamp (0 is not responded yet). */ + responded: number; + /** remote client IP address. */ + + remoteAddress: string; + /** remote client port. */ + remotePort: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com').*/ + hostname: string; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ + params: IDictionary; + /** an array containing all the path params values in the order they appeared in the path.*/ + paramsArray: string[]; + /** the request URI's path component. */ + path: string; + /** the request payload based on the route payload.output and payload.parse settings.*/ + payload: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ + plugins: any; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ + pre: IDictionary; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ + response: Response; + /**preResponses - same as pre but represented as the response object created by the pre method.*/ + preResponses: any; + /**an object containing the query parameters.*/ + query: any; + /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ + raw: { + req: http.ClientRequest; + res: http.ServerResponse; + }; + /** the route public interface.*/ + route: IRoute; + /** the server object. */ + server: Server; + /** Special key reserved for plugins implementing session support. Plugins utilizing this key must check for null value to ensure there is no conflict with another similar server. */ + session: any; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: any; + /** complex object contining details on the url */ + url: { + /** null when i tested */ + auth: any; + /** null when i tested */ + hash: any; + /** null when i tested */ + host: any; + /** null when i tested */ + hostname: any; + href: string; + path: string; + /** path without search*/ + pathname: string; + /** null when i tested */ + port: any; + /** null when i tested */ + protocol: any; + /** querystring parameters*/ + query: IDictionary; + /** querystring parameters as a string*/ + search: string; + /** null when i tested */ + slashes: any; + }; + /** request.setUrl(url) + + Available only in 'onRequest' extension methods. + + Changes the request URI before the router begins processing the request where: + + url - the new request path value. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + });*/ + setUrl(url: string): void; + /** request.setMethod(method) + + Available only in 'onRequest' extension methods. + + Changes the request method before the router begins processing the request where: + + method - is the request HTTP method (e.g. 'GET'). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onRequest', function (request, reply) { + + // Change all requests to 'GET' + request.setMethod('GET'); + return reply.continue(); + });*/ + setMethod(method: string): void; + /** request.log(tags, [data, [timestamp]]) + + Always available. + + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.on('request', function (request, event, tags) { + + if (tags.error) { + console.log(event); + } + }); + + var handler = function (request, reply) { + + request.log(['test', 'error'], 'Test event'); + return reply(); + }; + */ + log( + /** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ + tags: string|string[], + /** an optional message string or object with the application data being logged.*/ + data?: string, + /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ + timestamp?: number): void; + /** request.getLog([tags], [internal]) + + Always available. + + Returns an array containing the events matching any of the tags specified (logical OR) + request.getLog(); + request.getLog('error'); + request.getLog(['error', 'auth']); + request.getLog(['error'], true); + request.getLog(false);*/ + + getLog( + /** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ + tags?: string, + /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ + internal?: boolean): string[]; + + /** request.tail([name]) + + Available until immediately after the 'response' event is emitted. + + Adds a request tail which has to complete before the request lifecycle is complete where: + + name - an optional tail name used for logging purposes. + Returns a tail function which must be called when the tail activity is completed. + + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + + When all tails completed, the server emits a 'tail' event. + + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + var get = function (request, reply) { + + var dbTail = request.tail('write to database'); + + db.save('key', 'value', function () { + + dbTail(); + }); + + return reply('Success!'); + }; + + server.route({ method: 'GET', path: '/', handler: get }); + + server.on('tail', function (request) { + + console.log('Request completed including db activity'); + });*/ + tail( + /** an optional tail name used for logging purposes.*/ + name?: string): Function; + } + /** Response events + + The response object supports the following events: + + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + var Crypto = require('crypto'); + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + + server.ext('onPreResponse', function (request, reply) { + + var response = request.response; + if (response.isBoom) { + return reply(); + } + + var hash = Crypto.createHash('sha1'); + response.on('peek', function (chunk) { + + hash.update(chunk); + }); + + response.once('finish', function () { + + console.log(hash.digest('hex')); + }); + + return reply.continue(); + });*/ + export class Response extends Events.EventEmitter { + /** the HTTP response status code. Defaults to 200 (except for errors).*/ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ + headers: IDictionary; + /** the value provided using the reply interface.*/ + source: any; + /** a string indicating the type of source with available values: + 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + 'buffer' - a Buffer. + 'view' - a view generated with reply.view(). + 'file' - a file generated with reply.file() of via the directory handler. + 'stream' - a Stream. + 'promise' - a Promise object. */ + variety: string; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: any; + /** settings - response handling flags: + charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. + encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. + passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. + stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. + ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. + varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ + settings: { + charset: string; + encoding: string; + passThrough: boolean; + stringify: any; + ttl: number; + varyEtag: boolean; + } + + /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + length - the header value. Must match the actual payload size.*/ + bytes(length: number): void; + /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ + charset(charset: string): void; + + /** sets the HTTP status code where: + statusCode - the HTTP status code.*/ + code(statusCode: number): void; + /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ + created(uri: string): void; + + + /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ + encoding(encoding: string): void; + + /** etag(tag, options) - sets the representation entity tag where: + tag - the entity tag string without the double-quote. + options - optional settings where: + weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ + etag(tag: string, options: { + weak: boolean; vary: boolean; + }): void; + + /**header(name, value, options) - sets an HTTP header where: + name - the header name. + value - the header value. + options - optional settings where: + append - if true, the value is appended to any existing header value using separator. Defaults to false. + separator - string used as separator when appending to an exiting value. Defaults to ','. + override - if false, the header value is not set if an existing value present. Defaults to true.*/ + header(name: string, value: string, options?: { + append: boolean; + separator: string; + override: boolean; + }): void; + + /** location(uri) - sets the HTTP 'Location' header where: + uri - an absolute or relative URI used as the 'Location' header value.*/ + location(uri: string): void; + + /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: + uri - an absolute or relative URI used to redirect the client to another resource. */ + redirect(uri: string): void; + + /** replacer(method) - sets the JSON.stringify() replacer argument where: + method - the replacer function or array. Defaults to none.*/ + replacer(method: Function| Array): void; + + /** spaces(count) - sets the JSON.stringify() space argument where: + count - the number of spaces to indent nested object keys. Defaults to no indentation. */ + spaces(count: number): void; + /**state(name, value, [options]) - sets an HTTP cookie where: + name - the cookie name. + value - the cookie value. If no encoding is defined, must be a string. + options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ + state(name: string, value: string, options?: any): void; + + } + + + + /** Server http://hapijs.com/api#server + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + Server events + The server object inherits from Events.EventEmitter and emits the following events: + 'log' - events logged with server.log() and server events generated internally by the framework. + 'start' - emitted when the server is started using server.start(). + 'stop' - emitted when the server is stopped using server.stop(). + 'request' - events generated by request.log(). Does not include any internally generated events. + 'request-internal' - request events generated internally by the framework (multiple events per request). + 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. + 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. + 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. + Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. + MORE EVENTS HERE: http://hapijs.com/api#server-events*/ + export class Server extends Events.EventEmitter { + + constructor(options?: IServerOptions); + /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + var Hapi = require('hapi'); + server = new Hapi.Server(); + server.app.key = 'value'; + var handler = function (request, reply) { + return reply(request.server.app.key); + }; */ + app: any; + /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + var server = new Hapi.Server(); + server.connection({ port: 80, labels: 'a' }); + server.connection({ port: 8080, labels: 'b' }); + // server.connections.length === 2 + var a = server.select('a'); + // a.connections.length === 1*/ + connections: Array; + /** When the server contains exactly one connection, info is an object containing information about the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // server.info.port === 80 + server.connection({ port: 8080 }); + // server.info === null + // server.connections[1].info.port === 8080 + */ + info: { + /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ + id: string; + /** - the connection creation timestamp.*/ + created: number; + /** - the connection start timestamp (0 when stopped).*/ + started: number; + /** the connection port based on the following rules: + the configured port value before the server has been started. + the actual port assigned when no port is configured or set to 0 after the server has been started.*/ + port: number; + + /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ + host: string; + /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ + address: string; + /** - the protocol used: + 'http' - HTTP. + 'https' - HTTPS. + 'socket' - UNIX domain socket or Windows named pipe.*/ + protocol: string; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ + uri: string; + }; + /** An object containing the process load metrics (when load.sampleInterval is enabled): + rss - RSS memory usage. + var Hapi = require('hapi'); + var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); + console.log(server.load.rss);*/ + load: { + /** - event loop delay milliseconds.*/ + eventLoopDelay: number; + /** - V8 heap usage.*/ + heapUsed: number; + }; + /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + When the server contains more than one connection, each server.connections array member provides its own connection.listener. + var Hapi = require('hapi'); + var SocketIO = require('socket.io'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var io = SocketIO.listen(server.listener); + io.sockets.on('connection', function(socket) { + socket.emit({ msg: 'welcome' }); + });*/ + listener: http.Server; + + /** server.methods + An object providing access to the server methods where each server method name is an object property. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.method('add', function (a, b, next) { + return next(null, a + b); + }); + server.methods.add(1, 2, function (err, result) { + // result === 3 + });*/ + methods: IDictionary; + + /** server.mime + Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + var Hapi = require('hapi'); + var options = { + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } + }; + var server = new Hapi.Server(options); + // server.mime.path('code.js').type === 'application/javascript' + // server.mime.path('file.npm').type === 'node/module'*/ + mime: any; + /**server.plugins + An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + exports.register = function (server, options, next) { + server.expose('key', 'value'); + // server.plugins.example.key === 'value' + return next(); + }; + exports.register.attributes = { + name: 'example' + };*/ + plugins: IDictionary; + /** server.realm + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: + route - routes preferences: + prefix - the route path prefix used by any calls to server.route() from the server. + vhost - the route virtual host settings used by any calls to server.route() from the server. + plugin - the active plugin name (empty string if at the server root). + plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. + settings - settings overrides: + files.relativeTo + bind + The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). + exports.register = function (server, options, next) { + console.log(server.realm.modifiers.route.prefix); + return next(); + };*/ + realm: IServerRealm; + + /** server.root + The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ + root: Server; + /** server.settings + The server configuration object after defaults applied. + var Hapi = require('hapi'); + var server = new Hapi.Server({ + app: { + key: 'value' + } + }); + // server.settings.app === { key: 'value' }*/ + settings: IServerOptions; + + /** server.version + The hapi module version number. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + // server.version === '8.0.0'*/ + version: string; + + /** server.after(method, [dependencies]) + Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: + after - the method with signature function(plugin, next) where: + server - server object the after() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error which is returned back via the server.start() callback. + dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.after(function () { + // Perform some pre-start logic + }); + server.start(function (err) { + // After method already executed + }); + server.auth.default(options)*/ + after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string|string[]): void; + + auth: { + /** server.auth.default(options) + Sets a default strategy which is applied to every route where: + options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. + The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. + The default auth strategy configuration can be accessed via connection.auth.settings.default. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + });*/ + default(options: string):void; + /** server.auth.scheme(name, scheme) + Registers an authentication scheme where: + name - the scheme name. + scheme - the method implementing the scheme with signature function(server, options) where: + server - a reference to the server object the scheme is added to. + options - optional scheme settings used to instantiate a strategy.*/ + scheme(name: string, + /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. + n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + server = new Hapi.Server(); + server.connection({ port: 80 }); + scheme = function (server, options) { + urn { + authenticate: function (request, reply) { + req = request.raw.req; + var authorization = req.headers.authorization; + if (!authorization) { + return reply(Boom.unauthorized(null, 'Custom')); + } + urn reply(null, { credentials: { user: 'john' } }); + } + }; + }; + */ + scheme: (server: Server, options: any) => IServerAuthScheme): void; + + /** server.auth.strategy(name, scheme, [mode], [options]) + Registers an authentication strategy where: + name - the strategy name. + scheme - the scheme name (must be previously registered using server.auth.scheme()). + mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. + options - scheme options based on the scheme requirements. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + handler: function (request, reply) { + return reply(request.auth.credentials.user); + } + } + });*/ + strategy(name: string, scheme: any, mode?: boolean, options?: any):void; + + /** server.auth.test(strategy, request, next) + Tests a request against an authentication strategy where: + strategy - the strategy name registered with server.auth.strategy(). + request - the request object. + next - the callback function with signature function(err, credentials) where: + err - the error if authentication failed. + credentials - the authentication credentials object if authentication was successful. + Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.auth.scheme('custom', scheme); + server.auth.strategy('default', 'custom'); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.server.auth.test('default', request, function (err, credentials) { + if (err) { + return reply({ status: false }); + } + return reply({ status: true, user: credentials.name }); + }); + } + });*/ + test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; + }; + /** server.bind(context) + Sets a global context used as the default bind object when adding a route or an extension where: + context - the object used to bind this in handler and extension methods. + When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + var handler = function (request, reply) { + return reply(this.message); + }; + exports.register = function (server, options, next) { + var bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler: handler }); + return next(); + };*/ + bind(context: any): void; + + + /** server.cache(options) + Provisions a cache segment within the server cache facility where: + options - catbox policy configuration where: + expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + staleTimeout - number of milliseconds to wait before checking if an item is stale. + generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. + cache - the cache name configured in 'server.cache`. Defaults to the default cache. + segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. + shared - if true, allows multiple cache provisions to share the same segment. Default to false. + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); + cache.set('norway', { capital: 'oslo' }, null, function (err) { + cache.get('norway', function (err, value, cached, log) { + // value === { capital: 'oslo' }; + }); + });*/ + cache(options: ICatBoxCacheOptions): void; + + /** server.connection([options]) + Adds an incoming server connection + Returns a server object with the new connection selected. + Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). + Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); + var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); + // server.connections.length === 2 + // web.connections.length === 1 + // admin.connections.length === 1 */ + connection(options: ISeverConnectionOptions): Server; + /** server.decorate(type, property, method) + Extends various framework interfaces with custom methods where: + type - the interface being decorated. Supported types: + 'reply' - adds methods to the reply interface. + 'server' - adds methods to the Server object. + property - the object decoration key name. + method - the extension function. + Note that decorations apply to the entire server and all its connections regardless of current selection. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.decorate('reply', 'success', function () { + return this.response({ status: 'ok' }); + }); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + return reply.success(); + } + });*/ + decorate(type: string, property: string, method: Function):void; + + /** server.dependency(dependencies, [after]) + Used within a plugin to declares a required dependency on other plugins where: + dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. + after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + server - the server the dependency() method was called on. + next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + err - internal error condition, which is returned back via the server.start() callback. + exports.register = function (server, options, next) { + server.dependency('yar', after); + return next(); + }; + var after = function (server, next) { + // Additional plugin registration logic + return next(); + };*/ + dependency(dependencies: string|string[], after?: (server: Server, next: (err: any) => void) => void): void; + + + /** server.expose(key, value) + Used within a plugin to expose a property via server.plugins[name] where: + key - the key assigned (server.plugins[name][key]). + value - the value assigned. + exports.register = function (server, options, next) { + server.expose('util', function () { console.log('something'); }); + return next(); + };*/ + expose(key: string, value: any): void; + + /** server.expose(obj) + Merges a deep copy of an object into to the existing content of server.plugins[name] where: + obj - the object merged into the exposed properties container. + exports.register = function (server, options, next) { + server.expose({ util: function () { console.log('something'); } }); + return next(); + };*/ + expose(obj: any): void; + + /** server.ext(event, method, [options]) + Registers an extension function in one of the available extension points where: + event - the event name. + method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: + request - the request object. + reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + this - the object provided via options.bind or the current active context set with server.bind(). + options - an optional object with the following: + before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + bind - a context object passed back to the provided method (via this) when called. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.ext('onRequest', function (request, reply) { + // Change all requests to '/test' + request.setUrl('/test'); + return reply.continue(); + }); + var handler = function (request, reply) { + return reply({ status: 'ok' }); + }; + server.route({ method: 'GET', path: '/test', handler: handler }); + server.start(); + // All requests will get routed to '/test'*/ + ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string|string[]; after: string|string[]; bind?: any }): void; + + /** server.handler(name, method) + Registers a new handler type to be used in routes where: + name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. + method - the function used to generate the route handler using the signature function(route, options) where: + route - the route public interface object. + options - the configuration object provided in the handler config. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + // Defines new handler for routes on this server + server.handler('test', function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }); + server.route({ + method: 'GET', + path: '/', + handler: { test: { msg: 'test' } } + }); + server.start(); + The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ host: 'localhost', port: 8000 }); + var handler = function (route, options) { + return function (request, reply) { + return reply('new handler: ' + options.msg); + } + }; + // Change the default payload processing for this handler + handler.defaults = { + payload: { + output: 'stream', + parse: false + } + }; + server.handler('test', handler);*/ + handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + var handler = function (request, reply) { + return reply('Success!'); + }; + server.route({ method: 'GET', path: '/', handler: handler }); + server.inject('/', function (res) { + console.log(res.result); + }); + */ + inject: IServerInject; + + /** server.log(tags, [data, [timestamp]]) + Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + data - an optional message string or object with the application data being logged. + timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('log', function (event, tags) { + if (tags.error) { + console.log(event); + } + }); + server.log(['test', 'error'], 'Test event');*/ + log(tags: string|string[], data?: string|any, timestamp?: number): void; + /**server.lookup(id) + When the server contains exactly one connection, looks up a route configuration where: + id - the route identifier as set in the route options. + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.lookup('root'); + When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ + lookup(id: string): IRoute; + /** server.match(method, path, [host]) + When the server contains exactly one connection, looks up a route configuration where: + method - the HTTP method (e.g. 'GET', 'POST'). + path - the requested path (must begin with '/'). + host - optional hostname (to match against routes with vhost). + returns the route public interface object if found, otherwise null. + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { return reply(); }, + id: 'root' + } + }); + var route = server.match('get', '/'); + When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ + match(method: string, path: string, host?: string): IRoute; + + + + + /** server.method(name, method, [options]) + Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + Methods are registered via server.method(name, method, [options]) + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Simple arguments + var add = function (a, b, next) { + return next(null, a + b); + }; + server.method('sum', add, { cache: { expiresIn: 2000 } }); + server.methods.sum(4, 5, function (err, result) { + console.log(result); + }); + // Object argument + var addArray = function (array, next) { + var sum = 0; + array.forEach(function (item) { + sum += item; + }); + return next(null, sum); + }; + server.method('sumObj', addArray, { + cache: { expiresIn: 2000 }, + generateKey: function (array) { + return array.join(','); + } + }); + server.methods.sumObj([5, 6], function (err, result) { + console.log(result); + }); + // Synchronous method with cache + var addSync = function (a, b) { + return a + b; + }; + server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); + server.methods.sumSync(4, 5, function (err, result) { + console.log(result); + }); */ + method( + /** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ + name: string, + method: IServerMethod, + options?: IServerMethodOptions):void; + + + /**server.method(methods) + Registers a server method function as described in server.method() using a configuration object where: + methods - an object or an array of objects where each one contains: + name - the method name. + method - the method function. + options - optional settings. + var add = function (a, b, next) { + next(null, a + b); + }; + server.method({ + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000 + } + } + });*/ + method(methods: { + name: string; method: IServerMethod; options?: IServerMethodOptions + }| Array<{ + name: string; method: IServerMethod; options?: IServerMethodOptions + }>):void; + /**server.path(relativeTo) + Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + relativeTo - the path prefix added to any relative file path starting with '.'. + Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + exports.register = function (server, options, next) { + server.path(__dirname + '../static'); + server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); + next(); + };*/ + path(relativeTo: string): void; + /**server.register(plugins, [options], callback) + Registers a plugin where: + plugins - an object or array of objects where each one is either: + a plugin registration function. + an object with the following: + register - the plugin registration function. + options - optional options passed to the registration function when called. + options - optional registration options (different from the options passed to the registration function): + select - a string or array of string labels used to pre-select connections for plugin registration. + routes - modifiers applied to each route added by the plugin: + prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + callback - the callback function with signature function(err) where: + err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + server.register({ + register: require('plugin_name'), + options: { + message: 'hello' + } + }, function (err) { + if (err) { + console.log('Failed loading plugin'); + } + });*/ + register(plugins: any|any[], options: { + select: string|string[]; + routes: { + prefix: string; vhost?: string|string[] + }; + } + , callback: (err: any) => void):void; + + register(plugins: any|any[], callback: (err: any) => void):void; + + /**server.render(template, context, [options], callback) + Utilizes the server views manager to render a template where: + template - the template filename and path, relative to the views manager templates path (path or relativeTo). + context - optional object used by the template to render context-specific result. Defaults to no context ({}). + options - optional object used to override the views manager configuration. + callback - the callback function with signature function (err, rendered, config) where: + err - the rendering error if any. + rendered - the result view string. + config - the configuration used to render the template. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.views({ + engines: { html: require('handlebars') }, + path: __dirname + '/templates' + }); + var context = { + title: 'Views Example', + message: 'Hello, World' + }; + server.render('hello', context, function (err, rendered, config) { + console.log(rendered); + });*/ + render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void):void; + /** server.route(options) + Adds a connection route where: + options - a route configuration object or an array of configuration objects. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); + server.route([ + { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, + { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } + ]);*/ + route(options: IRouteConfiguration):void; + route(options: IRouteConfiguration[]):void; + /**server.select(labels) + Selects a subset of the server's connections where: + labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, labels: ['a', 'b'] }); + server.connection({ port: 8080, labels: ['a', 'c'] }); + server.connection({ port: 8081, labels: ['b', 'c'] }); + var a = server.select('a'); // 80, 8080 + var ac = a.select('c'); // 8080*/ + select(labels: string|string[]): void; + /** server.start([callback]) + Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: + callback - optional callback when server startup is completed or failed with the signature function(err) where: + err - any startup error condition. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.start(function (err) { + console.log('Server started at: ' + server.info.uri); + });*/ + start(callback?: (err: any) => void): void; + /** server.state(name, [options]) + HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions + State defaults can be modified via the server connections.routes.state configuration option. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + // Set cookie definition + server.state('session', { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: true, + path: '/', + encoding: 'base64json' + }); + // Set state in route handler + var handler = function (request, reply) { + var session = request.state.session; + if (!session) { + session = { user: 'joe' }; + } + session.last = Date.now(); + return reply('Success').state('session', session); + }; + Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.on('request-internal', function (request, event, tags) { + if (tags.error && tags.state) { + console.error(event); + } + }); */ + state(name: string, options?: ICookieSettings): void; + + /** server.stop([options], [callback]) + Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + options - optional object with: + timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80 }); + server.stop({ timeout: 60 * 1000 }, function () { + console.log('Server stopped'); + });*/ + stop(options?: { timeout: number }, callback?: () => void): void; + /**server.table([host]) + Returns a copy of the routing table where: + host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + The return value is an array where each item is an object containing: + info - the connection.info the connection the table was generated for. + labels - the connection labels. + table - an array of routes where each route contains: + settings - the route config with defaults applied. + method - the HTTP method in lower case. + path - the route path. + Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.table(); + When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.connection({ port: 80, host: 'example.com' }); + server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); + var table = server.connections[0].table(); + //[ + // { + // method: 'get', + // path: '/example', + // settings: { ... } + // } + //] + */ + table(host?: any): IConnectionTable; + + /**server.views(options) + Initializes the server views manager + var Hapi = require('hapi'); + var server = new Hapi.Server(); + server.views({ + engines: { + html: require('handlebars'), + jade: require('jade') + }, + path: '/static/templates' + }); + When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ + views(options: IServerViewsConfiguration): void; + + } +} \ No newline at end of file diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts new file mode 100644 index 000000000..11ad81d2d --- /dev/null +++ b/hapi/hapi-tests-8.2.0.ts @@ -0,0 +1,99 @@ +/// + +import Hapi = require("hapi"); + +// Create a server with a host and port +var server = new Hapi.Server(); +server.connection({ + host: "localhost", + port: 8000, +}); + +// Add plugins +var plugin: any = { + register: function (plugin: Object, options: Object, next: Function) { + next(); + } +}; + +plugin.register.attributes = { + name: "test", + version: "1.0.0" +}; + +// optional options parameter +server.register({}, function (err) {}); + +// optional options.routes.vhost parameter +server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); + +//server.pack.register(plugin, (err: Object) => { +// if (err) { throw err; } +//}); + +//server.pack.register([plugin], (err: Object) => { +// if (err) { throw err; } +//}); + +// Add server method +var add = function (a: number, b: number, next: (err: any, result?: any, ttl?: number) => void) { + next(null, a + b); +}; + +server.method("sum", add);//, { cache: { expiresIn: 2000 } }); + +server.methods["sum"](4, 5, (err: any, result: any) => { + console.log(result); +}); + +var addArray = function (array: Array, next: (err: any, result?: any, ttl?: number) => void) { + var sum: number = 0; + array.forEach((item: number) => { + sum += item; + }); + next(null, sum); +}; + +server.method("sumObj", addArray, { + //cache: { expiresIn: 2000 }, + generateKey: (array: Array) => { + return array.join(','); + } +}); + +server.methods["sumObj"]([5, 6], (err: any, result: any) => { + console.log(result); +}); + +// Add the route +server.route({ + method: 'GET', + path: '/hello', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world'); + } +}); + +server.route([{ + method: 'GET', + path: '/hello2', + handler: function (request: Hapi.Request, reply: Function) { + reply('hello world2'); + } +}]); + +// config.validate parameters should be optional +server.route([{ + method: 'GET', + path: '/hello2', + handler: function(request: Hapi.Request, reply: Function) { + reply('hello world2'); + }, + config: { + validate: { + } + } +}]); + +// Start the server +server.start(); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 8d3da2620..04b9416c7 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 8.2.0 +// Type definitions for hapi 8.8.0 // Project: http://github.com/spumko/hapi // Definitions by: Jason Swearingen // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -83,7 +83,7 @@ declare module "hapi" { /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ labels?: string|string[]; /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: boolean; + tls?: boolean|Object; } @@ -209,7 +209,7 @@ declare module "hapi" { /**Initializes the server views manager var Hapi = require('hapi'); var server = new Hapi.Server(); - + server.views({ engines: { html: require('handlebars'), @@ -229,8 +229,8 @@ declare module "hapi" { /** Concludes the handler activity by setting a response and returning control over to the framework where: erran optional error response. resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ export interface IReply { (err: Error, @@ -241,7 +241,7 @@ declare module "hapi" { /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ (result: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; - /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. + /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -384,7 +384,7 @@ declare module "hapi" { an object */ auth?: boolean|string| { - /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: + /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: 'required'authentication is required. 'optional'authentication is optional (must be valid if present). 'try'same as 'optional' but allows for invalid authentication. */ @@ -569,7 +569,7 @@ declare module "hapi" { */ headers?: boolean | IJoi | IValidationFunction; - + /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: trueany path parameters allowed (no validation performed).This is the default. falseno path variables allowed. @@ -634,8 +634,8 @@ declare module "hapi" { tags?: string[] } /** server.realm http://hapijs.com/api#serverrealm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), - the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), + the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). exports.register = function (server, options, next) { @@ -716,9 +716,9 @@ declare module "hapi" { lookupCompressed: boolean; } - /**http://hapijs.com/api#route-handler + /**http://hapijs.com/api#route-handler Built-in handlers - + The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ export interface IRouteHandlerConfig { /** generates a static file endpoint for serving a single file. file can be set to: @@ -815,7 +815,7 @@ declare module "hapi" { export interface IRouteConfiguration { /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ path: string; - /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). + /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ method: string|string[]; /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ @@ -828,7 +828,7 @@ declare module "hapi" { /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ export interface IRoute { - + /** the route HTTP method. */ method: string; /** the route path. */ @@ -853,8 +853,8 @@ declare module "hapi" { artifacts - optional authentication artifacts. reply.continue(result) - is called if authentication succeeded where: result - same object as result above. - When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. - .If the err returned by the reply() method includes a message, no additional strategies will be attempted. + When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. + .If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. var server = new Hapi.Server(); server.connection({ port: 80 }); @@ -1014,12 +1014,12 @@ declare module "hapi" { generateKey?(args: any[]): string; } /** Request object - + The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. Request events - + The request object supports the following events: - + 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). 'finish' - emitted when the request payload finished reading. The event method signature is function (). 'disconnect' - emitted when a request errors or aborts unexpectedly. @@ -1027,25 +1027,25 @@ declare module "hapi" { var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + var hash = Crypto.createHash('sha1'); request.on('peek', function (chunk) { - + hash.update(chunk); }); - + request.once('finish', function () { - + console.log(hash.digest('hex')); }); - + request.once('disconnect', function () { - + console.error('request aborted'); }); - + return reply.continue(); });*/ export class Request extends Events.EventEmitter { @@ -1157,64 +1157,64 @@ declare module "hapi" { slashes: any; }; /** request.setUrl(url) - + Available only in 'onRequest' extension methods. - + Changes the request URI before the router begins processing the request where: - + url - the new request path value. var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + // Change all requests to '/test' request.setUrl('/test'); return reply.continue(); });*/ setUrl(url: string): void; /** request.setMethod(method) - + Available only in 'onRequest' extension methods. - + Changes the request method before the router begins processing the request where: - + method - is the request HTTP method (e.g. 'GET'). var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onRequest', function (request, reply) { - + // Change all requests to 'GET' request.setMethod('GET'); return reply.continue(); });*/ setMethod(method: string): void; /** request.log(tags, [data, [timestamp]]) - + Always available. - + Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - + data - an optional message string or object with the application data being logged. timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - + var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.on('request', function (request, event, tags) { - + if (tags.error) { console.log(event); } }); - + var handler = function (request, reply) { - + request.log(['test', 'error'], 'Test event'); return reply(); }; @@ -1227,9 +1227,9 @@ declare module "hapi" { /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ timestamp?: number): void; /** request.getLog([tags], [internal]) - + Always available. - + Returns an array containing the events matching any of the tags specified (logical OR) request.getLog(); request.getLog('error'); @@ -1244,38 +1244,38 @@ declare module "hapi" { internal?: boolean): string[]; /** request.tail([name]) - + Available until immediately after the 'response' event is emitted. - + Adds a request tail which has to complete before the request lifecycle is complete where: - + name - an optional tail name used for logging purposes. Returns a tail function which must be called when the tail activity is completed. - + Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - + When all tails completed, the server emits a 'tail' event. - + var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + var get = function (request, reply) { - + var dbTail = request.tail('write to database'); - + db.save('key', 'value', function () { - + dbTail(); }); - + return reply('Success!'); }; - + server.route({ method: 'GET', path: '/', handler: get }); - + server.on('tail', function (request) { - + console.log('Request completed including db activity'); });*/ tail( @@ -1283,34 +1283,34 @@ declare module "hapi" { name?: string): Function; } /** Response events - + The response object supports the following events: - + 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). var Crypto = require('crypto'); var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 80 }); - + server.ext('onPreResponse', function (request, reply) { - + var response = request.response; if (response.isBoom) { return reply(); } - + var hash = Crypto.createHash('sha1'); response.on('peek', function (chunk) { - + hash.update(chunk); }); - + response.once('finish', function () { - + console.log(hash.digest('hex')); }); - + return reply.continue(); });*/ export class Response extends Events.EventEmitter { @@ -1412,7 +1412,7 @@ declare module "hapi" { /** Server http://hapijs.com/api#server - rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). Server events The server object inherits from Events.EventEmitter and emits the following events: 'log' - events logged with server.log() and server events generated internally by the framework. @@ -1734,7 +1734,7 @@ declare module "hapi" { cache(options: ICatBoxCacheOptions): void; /** server.connection([options]) - Adds an incoming server connection + Adds an incoming server connection Returns a server object with the new connection selected. Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. @@ -1872,8 +1872,8 @@ declare module "hapi" { }; server.handler('test', handler);*/ handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; - /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. - Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. + /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. + Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). var Hapi = require('hapi'); @@ -2209,4 +2209,4 @@ declare module "hapi" { views(options: IServerViewsConfiguration): void; } -} \ No newline at end of file +} From 2f7754dceb349d4d1058bd4c11f144e6d9013536 Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Tue, 7 Jul 2015 17:49:06 -0400 Subject: [PATCH 051/416] Fixes contains searching keys instead of values on objects, also adds "includes" alias. --- lodash/lodash-tests.ts | 9 +++++++-- lodash/lodash.d.ts | 38 +++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c7e6bf024..0c73066c5 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -363,14 +363,19 @@ result = _.at(['moe', 'larry', 'curly'], 0, 2); result = _.contains([1, 2, 3], 1); result = _.contains([1, 2, 3], 1, 2); -result = _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); +result = _.contains({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.contains('curly', 'ur'); result = _.include([1, 2, 3], 1); result = _.include([1, 2, 3], 1, 2); -result = _.include({ 'name': 'moe', 'age': 40 }, 'moe'); +result = _.include({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.include('curly', 'ur'); +result = _.includes([1, 2, 3], 1); +result = _.includes([1, 2, 3], 1, 2); +result = _.includes({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); +result = _.includes('curly', 'ur'); + result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return Math.floor(num); }); result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return this.floor(num); }, Math); result = <_.Dictionary>_.countBy(['one', 'two', 'three'], 'length'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index b4eaf7509..21bd2357f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2198,11 +2198,11 @@ declare module _ { /** * @see _.contains * @param dictionary The dictionary to iterate over. - * @param key The key in the dictionary to search for. + * @param value The value in the dictionary to search for. **/ contains( dictionary: Dictionary, - key: string, + value: T, fromIndex?: number): boolean; /** @@ -2236,7 +2236,7 @@ declare module _ { **/ include( dictionary: Dictionary, - key: string, + value: T, fromIndex?: number): boolean; /** @@ -2246,6 +2246,38 @@ declare module _ { searchString: string, targetString: string, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + collection: Array, + target: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + collection: List, + target: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + dictionary: Dictionary, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + searchString: string, + targetString: string, + fromIndex?: number): boolean; } //_.countBy From 9436ac816b62aebb13ceb2c3ab8397898832789c Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Tue, 7 Jul 2015 18:07:52 -0400 Subject: [PATCH 052/416] Remove includes from sequelize definition, since it's in lodash's now. --- sequelize/sequelize.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 85d473f28..1bb6be593 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -2703,7 +2703,6 @@ declare module "sequelize" } interface Lodash extends _.LoDashStatic { - includes(str: string, needle: string): boolean; camelizeIf(str: string, condition: boolean): string; camelizeIf(str: string, condition: any): string; underscoredIf(str: string, condition: boolean): string; @@ -2785,4 +2784,4 @@ declare module "sequelize" var sequelize: sequelize.SequelizeStatic; export = sequelize; -} \ No newline at end of file +} From 5ce60e032b7b5523876f8269a2c4b25edeaa02ba Mon Sep 17 00:00:00 2001 From: Steven Salat Date: Tue, 7 Jul 2015 17:42:10 -0700 Subject: [PATCH 053/416] Updating jquery.autosize to the new API in 3.0.7 --- jquery.autosize/jquery.autosize-tests.ts | 13 +++++++++++++ jquery.autosize/jquery.autosize.d.ts | 24 +++++++++++------------- 2 files changed, 24 insertions(+), 13 deletions(-) create mode 100755 jquery.autosize/jquery.autosize-tests.ts diff --git a/jquery.autosize/jquery.autosize-tests.ts b/jquery.autosize/jquery.autosize-tests.ts new file mode 100755 index 000000000..df4aef5b2 --- /dev/null +++ b/jquery.autosize/jquery.autosize-tests.ts @@ -0,0 +1,13 @@ +/// + +// from a NodeList +autosize(document.querySelectorAll('textarea')); + +// from a single Node +autosize(document.querySelector('textarea')); + +// from a jQuery collection +autosize($('textarea')); + +// from a single element +autosize(document.getElementById('my-textarea')); \ No newline at end of file diff --git a/jquery.autosize/jquery.autosize.d.ts b/jquery.autosize/jquery.autosize.d.ts index 5b9f9adfb..508677b4a 100644 --- a/jquery.autosize/jquery.autosize.d.ts +++ b/jquery.autosize/jquery.autosize.d.ts @@ -1,21 +1,19 @@ -// Type definitions for jquery.autosize (un-versioned) +// Type definitions for jquery.autosize 3.0.7 // Project: http://www.jacklmoore.com/autosize/ // Definitions by: Aaron T. King // Definitions: https://github.com/borisyankov/DefinitelyTyped /// - -interface AutosizeOptions { - className?: string; - append?: string; - callback?: Function; +declare module autosize { + interface AutosizeStatic { + (el: Element): void; + (el: NodeList): void; + (el: JQuery): void; + } } -interface Autosize { - (): JQuery; - (options: AutosizeOptions): JQuery; -} +declare var autosize: autosize.AutosizeStatic; -interface JQuery { - autosize: Autosize; -} \ No newline at end of file +declare module 'autosize' { + export = autosize; +} From 30c4a6ea1297b1c18bafbe0284d653f7dfa4a213 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 17:39:45 +0900 Subject: [PATCH 054/416] Support Options#excludeSwitches --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 73ea8561e..cbe4db926 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -14,6 +14,7 @@ function TestChromeOptions() { options = options.addArguments("a", "b", "c"); options = options.addExtensions("a", "b", "c"); + options = options.excludeSwitches("a", "b", "c"); options = options.detachDriver(true); options = options.setChromeBinaryPath("path"); options = options.setChromeLogFile("logfile"); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c4af933c9..c48f16af0 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -62,6 +62,16 @@ declare module chrome { addArguments(...var_args: string[]): Options; + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with "--". + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + /** * Add additional extensions to install when launching Chrome. Each extension * should be specified as the path to the packed CRX file, or a Buffer for an From 6c8a0d02aa4f8e7725543a1b853b490826d3b361 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 17:53:08 +0900 Subject: [PATCH 055/416] Add Options#setPerfLoggingPrefs --- .../selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index cbe4db926..4a08523c2 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -20,6 +20,7 @@ function TestChromeOptions() { options = options.setChromeLogFile("logfile"); options = options.setLocalState("state"); options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({enableNetwork: true, enablePage: true, enableTimeline: true, tracingCategories: "category", bufferUsageReportingInterval: 1000}); options = options.setProxy({ proxyType: "proxyType" }); options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c48f16af0..40a6bf216 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -33,6 +33,14 @@ declare module chrome { prefs?: any; } + interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; + } + /** * Class for managing ChromeDriver specific options. */ @@ -124,6 +132,32 @@ declare module chrome { */ setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + /** * Sets preferences for the "Local State" file in Chrome's user data From a766e1aef7c282c9ec9cc84a8daf31874496b5c2 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:06:56 +0900 Subject: [PATCH 056/416] add Options#android* --- .../selenium-webdriver-tests.ts | 6 ++ selenium-webdriver/selenium-webdriver.d.ts | 63 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4a08523c2..c74369302 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -19,6 +19,12 @@ function TestChromeOptions() { options = options.setChromeBinaryPath("path"); options = options.setChromeLogFile("logfile"); options = options.setLocalState("state"); + options = options.androidActivity("com.example.Activity"); + options = options.androidDeviceSerial("emulator-5554"); + options = options.androidChrome(); + options = options.androidPackage("com.android.chrome"); + options = options.androidProcess("com.android.chrome"); + options = options.androidUseRunningApp(true); options = options.setLoggingPrefs(new webdriver.logging.Preferences()); options = options.setPerfLoggingPrefs({enableNetwork: true, enablePage: true, enableTimeline: true, tracingCategories: "category", bufferUsageReportingInterval: 1000}); options = options.setProxy({ proxyType: "proxyType" }); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 40a6bf216..25d22a7bd 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -168,6 +168,69 @@ declare module chrome { setLocalState(state: any): Options; + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + /** * Sets the path to Chrome's log file. This path should exist on the machine * that will launch Chrome. From 11daee6f62a67e3aed8a13739dd032ccef84cc3f Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:14:21 +0900 Subject: [PATCH 057/416] Sort asserting order to following the definition --- selenium-webdriver/selenium-webdriver-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c74369302..13f42c6f8 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -39,13 +39,13 @@ function TestServiceBuilder() { builder = new chrome.ServiceBuilder("exe"); var anything: any = builder.build(); - builder = builder.enableVerboseLogging(); + builder = builder.usingPort(8080); builder = builder.loggingTo("path"); + builder = builder.enableVerboseLogging(); builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath("path"); builder = builder.setStdio("config"); builder = builder.setStdio(["A", "B"]); - builder = builder.setUrlBasePath("path"); - builder = builder.usingPort(8080); builder = builder.withEnvironment({ "A": "a", "B": "b" }); } From 666442816f16c1cb2296f11443a3e44d2dd5f7d0 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 18:15:18 +0900 Subject: [PATCH 058/416] Add ServiceBuilder#setAdbPort --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 13f42c6f8..4ad2a7be6 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -40,6 +40,7 @@ function TestServiceBuilder() { var anything: any = builder.build(); builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); builder = builder.loggingTo("path"); builder = builder.enableVerboseLogging(); builder = builder.setNumHttpThreads(5); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 25d22a7bd..3950f7814 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -296,6 +296,17 @@ declare module chrome { usingPort(port: number): ServiceBuilder; + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + /** * Sets the path of the log file the driver should log to. If a log file is * not specified, the driver will log to stderr. From 14b919fedf43a0e6c1f16545c2aaf45fe76d7d23 Mon Sep 17 00:00:00 2001 From: joswhite Date: Wed, 8 Jul 2015 16:09:35 -0600 Subject: [PATCH 059/416] Add disconnect method See https://github.com/Automattic/socket.io-client/issues/737 - "v1.2.0. You can stop reconnection by calling disconnect method now." --- socket.io-client/socket.io-client.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index c5d783764..c51665d49 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -27,6 +27,7 @@ declare module SocketIOClient { emit(event: string, ...args: any[]): Socket; listeners(event: string): Function[]; hasListeners(event: string): boolean; + disconnect(): void; connected: boolean; } From 1fe53244ac52a292dc5ac2bb9cf7f243b7b639e4 Mon Sep 17 00:00:00 2001 From: afromogli Date: Thu, 9 Jul 2015 10:06:47 +0200 Subject: [PATCH 060/416] Update typings for globalize.d.ts. Only added typings for Number module (since it is the one we are using in our project). --- globalize/globalize-tests.ts | 6 +- globalize/globalize.d.ts | 129 ++++------------------------------- 2 files changed, 17 insertions(+), 118 deletions(-) diff --git a/globalize/globalize-tests.ts b/globalize/globalize-tests.ts index 3d599a611..a5d25037d 100644 --- a/globalize/globalize-tests.ts +++ b/globalize/globalize-tests.ts @@ -1,6 +1,6 @@ /// -Globalize.culture("fr"); +/*Globalize.culture("fr"); console.log(Globalize.culture().name); Globalize.culture("fr-FR"); @@ -66,7 +66,7 @@ Globalize.format(new Date(2012, 1, 20), 'd'); Globalize.format(new Date(2012, 1, 20), 'D'); -Globalize.cultures[ "default" ] = { +Globalize.load[ "default" ] = { name: "English", englishName: "English", nativeName: "English", @@ -132,4 +132,4 @@ Globalize.cultures[ "default" ] = { } }, messages: {} -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 4510e38cb..f4ebd7697 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -1,125 +1,24 @@ // Type definitions for Globalize // Project: https://github.com/jquery/globalize -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Aram Taieb +// Definitions: https://github.com/afromogli/DefinitelyTyped - -interface GlobalizePercent { - pattern: string[]; - decimals: number; - groupSizes: number[]; - //",": string; - //".": string; - symbol: string; -} - -interface GlobalizeCurrency { - pattern: string[]; - decimals: number; - groupSizes: number[]; - //",": string; - //".": string; - symbol: string; -} - -interface GlobalizeNumberFormat { - pattern: string[]; - decimals: string; - //",": string; - //".": string; - groupSizes: number[]; - //"+": string; - //"-": string; - NaN: string; - negativeInfinity: string; - positiveInfinity: string; - percent: GlobalizePercent; - currency: GlobalizeCurrency; -} - -interface GlobalizeEra { - name: string; - start: any; - offset: number; -} - -interface GlobalizeDays { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; -} - -interface GlobalizeMonths { - names: string[]; - namesAbbr: string[]; -} - -interface GlobalizePatterns { - d: string; - D: string; - t: string; - T: string; - f: string; - F: string; - M: string; - Y: string; - S: string; -} - -interface GlobalizeCalendar { - name: string; - // "/": string, - // ":": string, - firstDay: number; - days: GlobalizeDays; - months: GlobalizeMonths; - AM: string[]; - PM: string[]; - eras: GlobalizeEra[]; - twoDigitYearMax: number; - patterns: GlobalizePatterns; -} - -interface GlobalizeCalendars { - standard: GlobalizeCalendar; -} - -interface GlobalizeCulture { - name: string; - englishName: string; - nativeName: string; - isRTL: boolean; - language: string; - numberFormat: GlobalizeNumberFormat; - calendar: GlobalizeCalendar; - calendars: GlobalizeCalendars; - messages: any; -} -interface GlobalizeCultures { - [index: number]: GlobalizeCulture; +interface NumberFormatterOptions { + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + round?: string; + useGrouping?: boolean; } interface GlobalizeStatic { - cultures: GlobalizeCultures; - init(cultureSelector: string): GlobalizeStatic; - cultureSelector: string; + load(jsonData: any); + locale(locale: string); - culture(): GlobalizeCulture; - culture(cultureSelector: string): GlobalizeCulture; - culture(cultureSelector: string[]): GlobalizeCulture; - - addCultureInfo(cultureName: string, baseCultureName: string, info: Object): void; - addCultureInfo(cultureName: string, info: Object): void; - addCultureInfo(info: Object): void; - findClosestCulture(cultureSelector: string): GlobalizeStatic; - format(value: number, format: string, cultureSelector?: string): string; - format(value: Date, format: string, cultureSelector?: string): string; - localize(key: string, cultureSelector?: string): string; - - parseDate(value: string, format?: string, cultureSelector?: string): Date; - parseDate(value: string, formats?: string[], cultureSelector?: string): Date; - parseInt(value: string, radix?: number, cultureSelector?: string): number; - parseFloat(value: string, radix?: number, cultureSelector?: string): number; + numberFormatter(options?: NumberFormatterOptions): (value: number) => string; + formatNumber(value, options?: NumberFormatterOptions): string; } declare var Globalize: GlobalizeStatic; From 0229392d7c05ea47c84e6c5cd9c125939460ce4c Mon Sep 17 00:00:00 2001 From: Sean Templeton Date: Thu, 9 Jul 2015 11:34:37 -0600 Subject: [PATCH 061/416] fix(mixpanel): Made identifiy id parameter optional --- mixpanel/mixpanel.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mixpanel/mixpanel.d.ts b/mixpanel/mixpanel.d.ts index 8c8420658..8db3b34a4 100644 --- a/mixpanel/mixpanel.d.ts +++ b/mixpanel/mixpanel.d.ts @@ -26,7 +26,7 @@ interface Mixpanel unregister(propertyName:string):void; - identify(id:string):void; + identify(id?:string):void; get_distinct_id():string; From ad21a10ba76af3ecca3cf733bafef8605eabb471 Mon Sep 17 00:00:00 2001 From: Anthony Guo Date: Tue, 7 Jul 2015 14:14:34 -0700 Subject: [PATCH 062/416] codemirror.d.ts: Changed the Doc class type to an interface, and exposed the CodeMirror.Pos constructor This allows the user to extend the definition for the CodeMirror.Doc interface over multiple files. It also allows for instantiating new CodeMirror.Position type objects using "new CodeMirror.Pos(...)" --- codemirror/codemirror.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 65692cf1c..8584b6a2b 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -7,6 +7,8 @@ declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfig declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare module CodeMirror { + export var Doc : CodeMirror.Doc; + export var Pos: CodeMirror.Position; export var Pass: any; function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; @@ -387,8 +389,8 @@ declare module CodeMirror { getTextArea(): HTMLTextAreaElement; } - class Doc { - constructor (text: string, mode?: any, firstLineNumber?: number); + interface Doc { + new (text: string, mode?: any, firstLineNumber?: number): Doc; /** Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n"). */ getValue(seperator?: string): string; @@ -616,6 +618,7 @@ declare module CodeMirror { } interface Position { + new (line: number, ch: number): Position; ch: number; line: number; } From cd5de37f831e63982d0b47d3684f37bbb3410b31 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:17:37 +0200 Subject: [PATCH 063/416] Added definitions for v1.3.5 of the socket.io lib --- .../legacy/socket.io-client-1.2.0.d.ts | 45 + socket.io-client/socket.io-client.d.ts | 665 ++++++++++++- socket.io/legacy/socket.io-1.2.0.d.ts | 96 ++ socket.io/socket.io.d.ts | 877 ++++++++++++++++-- 4 files changed, 1578 insertions(+), 105 deletions(-) create mode 100644 socket.io-client/legacy/socket.io-client-1.2.0.d.ts create mode 100644 socket.io/legacy/socket.io-1.2.0.d.ts diff --git a/socket.io-client/legacy/socket.io-client-1.2.0.d.ts b/socket.io-client/legacy/socket.io-client-1.2.0.d.ts new file mode 100644 index 000000000..c5d783764 --- /dev/null +++ b/socket.io-client/legacy/socket.io-client-1.2.0.d.ts @@ -0,0 +1,45 @@ +// Type definitions for socket.io-client 1.2.0 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var io: SocketIOClientStatic; + +declare module 'socket.io-client' { + export = io; +} + +interface SocketIOClientStatic { + (host: string, details?: any): SocketIOClient.Socket; + (details?: any): SocketIOClient.Socket; + connect(host: string, details?: any): SocketIOClient.Socket; + connect(details?: any): SocketIOClient.Socket; + protocol: number; + Socket: { new (...args: any[]): SocketIOClient.Socket }; + Manager: SocketIOClient.ManagerStatic; +} + +declare module SocketIOClient { + interface Socket { + on(event: string, fn: Function): Socket; + once(event: string, fn: Function): Socket; + off(event?: string, fn?: Function): Socket; + emit(event: string, ...args: any[]): Socket; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + connected: boolean; + } + + interface ManagerStatic { + (url: string, opts: any): SocketIOClient.Manager; + new (url: string, opts: any): SocketIOClient.Manager; + } + + interface Manager { + reconnection(v: boolean): Manager; + reconnectionAttempts(v: boolean): Manager; + reconnectionDelay(v: boolean): Manager; + reconnectionDelayMax(v: boolean): Manager; + timeout(v: boolean): Manager; + } +} diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index c5d783764..7e15773e6 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -1,45 +1,650 @@ -// Type definitions for socket.io-client 1.2.0 +// Type definitions for socket.io-client 1.3.5 // Project: http://socket.io/ -// Definitions by: PROGRE +// Definitions by: divillysausages // Definitions: https://github.com/borisyankov/DefinitelyTyped declare var io: SocketIOClientStatic; declare module 'socket.io-client' { - export = io; + export = io; } interface SocketIOClientStatic { - (host: string, details?: any): SocketIOClient.Socket; - (details?: any): SocketIOClient.Socket; - connect(host: string, details?: any): SocketIOClient.Socket; - connect(details?: any): SocketIOClient.Socket; - protocol: number; - Socket: { new (...args: any[]): SocketIOClient.Socket }; - Manager: SocketIOClient.ManagerStatic; + + /** + * Looks up an existing 'Manager' for multiplexing. If the user summons: + * 'io( 'http://localhost/a' );' + * 'io( 'http://localhost/b' );' + * + * We reuse the existing instance based on the same scheme/port/host, and + * we initialize sockets for each namespace. If autoConnect isn't set to + * false in the options, then we'll automatically connect + * @param uri The uri that we'll connect to, including the namespace, where '/' is the default one (e.g. http://localhost:4000/somenamespace) + * @opts Any connect options that we want to pass along + * @return A Socket object + */ + ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * Auto-connects to the window location and defalt namespace. + * E.g. window.protocol + '//' + window.host + ':80/' + * @opts Any connect options that we want to pass along + * @return A Socket object + */ + ( opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * @see the default constructor (io(uri, opts)) + */ + connect( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * @see the default constructor (io(opts)) + */ + connect( opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * The socket.io protocol revision number this client works with + * @default 4 + */ + protocol: number; + + /** + * Socket constructor - exposed for the standalone build + */ + Socket: SocketIOClient.Socket; + + /** + * Manager constructor - exposed for the standalone build + */ + Manager: SocketIOClient.ManagerStatic; } declare module SocketIOClient { - interface Socket { - on(event: string, fn: Function): Socket; - once(event: string, fn: Function): Socket; - off(event?: string, fn?: Function): Socket; - emit(event: string, ...args: any[]): Socket; - listeners(event: string): Function[]; - hasListeners(event: string): boolean; - connected: boolean; - } + + /** + * The base emiter class, used by Socket and Manager + */ + interface Emitter { + /** + * Adds a listener for a particular event. Calling multiple times will add + * multiple listeners + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on the + * event in question + * @return This Emitter + */ + on( event: string, fn: Function ):Emitter; + + /** + * @see on( event, fn ) + */ + addEventListener( event: string, fn: Function ):Emitter; + + /** + * Adds a listener for a particular event that will be invoked + * a single time before being automatically removed + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on + * the event in question + * @return This Emitter + */ + once( event: string, fn: Function ):Emitter; + + /** + * Removes a listener for a particular type of event. This will either + * remove a specific listener, or all listeners for this type of event + * @param event The event that we want to remove the listener of + * @param fn The function to remove, or null if we want to remove all functions + * @return This Emitter + */ + off( event: string, fn?: Function ):Emitter; + + /** + * @see off( event, fn ) + */ + removeListener( event: string, fn?: Function ):Emitter; + + /** + * @see off( event, fn ) + */ + removeEventListener( event: string, fn?: Function ):Emitter; + + /** + * Removes all event listeners on this object + * @return This Emitter + */ + removeAllListeners():Emitter; + + /** + * Emits 'event' with the given args + * @param event The event that we want to emit + * @param args Optional arguments to emit with the event + * @return Emitter + */ + emit( event: string, ...args: any[] ):Emitter; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + + /** + * Returns if we have listeners for a particular event + * @param event The event that we want to check if we've listeners for + * @return True if we have listeners for this event, false otherwise + */ + hasListeners( event: string ):boolean; + } + + /** + * The Socket static interface + */ + interface SocketStatic { + + /** + * Creates a new Socket, used for communicating with a specific namespace + * @param io The Manager that's controlling this socket + * @param nsp The namespace that this socket is for (@default '/') + * @return A new Socket + */ + ( io: SocketIOClient.Manager, nsp: string ): Socket; + + /** + * Creates a new Socket, used for communicating with a specific namespace + * @param io The Manager that's controlling this socket + * @param nsp The namespace that this socket is for (@default '/') + * @return A new Socket + */ + new ( url: string, opts: any ): SocketIOClient.Manager; + } + + /** + * The Socket that we use to connect to a Namespace on the server + */ + interface Socket extends Emitter { + + /** + * The Manager that's controller this socket + */ + io: SocketIOClient.Manager; + + /** + * The namespace that this socket is for + * @default '/' + */ + nsp: string; + + /** + * Are we currently connected? + * @default false + */ + connected: boolean; + + /** + * Are we currently disconnected? + * @default true + */ + disconnected: boolean; + + /** + * Opens our socket so that it connects. If the 'autoConnect' option for io is + * true (default), then this is called automatically when the Socket is created + */ + open(): Socket; + + /** + * @see open(); + */ + connect(): Socket; + + /** + * Sends a 'message' event + * @param args Any optional arguments that we want to send + * @see emit + * @return This Socket + */ + send( ...args: any[] ):Socket; + + /** + * An override of the base emit. If the event is one of: + * connect + * connect_error + * connect_timeout + * disconnect + * error + * reconnect + * reconnect_attempt + * reconnect_failed + * reconnect_error + * reconnecting + * then the event is emitted normally. Otherwise, if we're connected, the + * event is sent. Otherwise, it's buffered. + * + * If the last argument is a function, then it will be called + * as an 'ack' when the response is received. The parameter(s) of the + * ack will be whatever data is returned from the event + * @param event The event that we're emitting + * @param args Optional arguments to send with the event + * @return This Socket + */ + emit( event: string, ...args: any[] ):Socket; + + /** + * Disconnects the socket manually + * @return This Socket + */ + close():Socket; + + /** + * @see close() + */ + disconnect():Socket; + } - interface ManagerStatic { - (url: string, opts: any): SocketIOClient.Manager; - new (url: string, opts: any): SocketIOClient.Manager; - } + /** + * The Manager static interface + */ + interface ManagerStatic { + /** + * Creates a new Manager + * @param uri The URI that we're connecting to (e.g. http://localhost:4000) + * @param opts Any connection options that we want to use (and pass to engine.io) + * @return A Manager + */ + ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Manager; + + /** + * Creates a new Manager with the default URI (window host) + * @param opts Any connection options that we want to use (and pass to engine.io) + */ + ( opts: SocketIOClient.ConnectOpts ):SocketIOClient.Manager; + + /** + * @see default constructor + */ + new ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Manager; + + /** + * @see default constructor + */ + new ( opts: SocketIOClient.ConnectOpts ):SocketIOClient.Manager; + } - interface Manager { - reconnection(v: boolean): Manager; - reconnectionAttempts(v: boolean): Manager; - reconnectionDelay(v: boolean): Manager; - reconnectionDelayMax(v: boolean): Manager; - timeout(v: boolean): Manager; - } + /** + * The Manager class handles all the Namespaces and Sockets that we're using + */ + interface Manager extends Emitter { + + /** + * All the namespaces currently controlled by this Manager, and the Sockets + * that we're using to communicate with them + */ + nsps: { [namespace:string]: Socket }; + + /** + * The connect options that we used when creating this Manager + */ + opts: SocketIOClient.ConnectOpts; + + /** + * The state of the Manager. Either 'closed', 'opening', or 'open' + */ + readyState: string; + + /** + * The URI that this manager is for (host + port), e.g. 'http://localhost:4000' + */ + uri: string; + + /** + * The currently connected sockets + */ + connected: Socket[]; + + /** + * If we should auto connect (also used when creating Sockets). Set via the + * opts object + */ + autoConnect: boolean; + + /** + * Gets if we should reconnect automatically + * @default true + */ + reconnection(): boolean; + + /** + * Sets if we should reconnect automatically + * @param v True if we should reconnect automatically, false otherwise + * @default true + * @return This Manager + */ + reconnection( v: boolean ): Manager; + + /** + * Gets the number of reconnection attempts we should try before giving up + * @default Infinity + */ + reconnectionAttempts(): number; + + /** + * Sets the number of reconnection attempts we should try before giving up + * @param v The number of attempts we should do before giving up + * @default Infinity + * @return This Manager + */ + reconnectionAttempts( v: number ): Manager; + + /** + * Gets the delay in milliseconds between each reconnection attempt + * @default 1000 + */ + reconnectionDelay(): number; + + /** + * Sets the delay in milliseconds between each reconnection attempt + * @param v The delay in milliseconds + * @default 1000 + * @return This Manager + */ + reconnectionDelay( v: number ): Manager; + + /** + * Gets the max reconnection delay in milliseconds between each reconnection + * attempt + * @default 5000 + */ + reconnectionDelayMax(): number; + + /** + * Sets the max reconnection delay in milliseconds between each reconnection + * attempt + * @param v The max reconnection dleay in milliseconds + * @return This Manager + */ + reconnectionDelayMax( v: number ): Manager; + + /** + * Gets the randomisation factor used in the exponential backoff jitter + * when reconnecting + * @default 0.5 + */ + randomizationFactor(): number; + + /** + * Sets the randomisation factor used in the exponential backoff jitter + * when reconnecting + * @param The reconnection randomisation factor + * @default 0.5 + * @return This Manager + */ + randomizationFactor( v: number ): Manager; + + /** + * Gets the timeout in milliseconds for our connection attempts + * @default 20000 + */ + timeout(): number; + + /** + * Sets the timeout in milliseconds for our connection attempts + * @param The connection timeout milliseconds + * @return This Manager + */ + timeout(v: boolean): Manager; + + /** + * Sets the current transport socket and opens our connection + * @param fn An optional callback to call when our socket has either opened, or + * failed. It can take one optional parameter of type Error + * @return This Manager + */ + open( fn?: (err?: any) => void ): Manager; + + /** + * @see open( fn ); + */ + connect( fn?: (err?: any) => void ): Manager; + + /** + * Creates a new Socket for the given namespace + * @param nsp The namespace that this Socket is for + * @return A new Socket, or if one has already been created for this namespace, + * an existing one + */ + socket( nsp: string ): Socket; + } + + /** + * Options we can pass to the socket when connecting + */ + interface ConnectOpts { + + /** + * Should we force a new Manager for this connection? + * @default false + */ + forceNew?: boolean; + + /** + * Should we multiplex our connection (reuse existing Manager) ? + * @default true + */ + multiplex?: boolean; + + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/socket.io' + */ + path?: string; + + /** + * Should we allow reconnections? + * @default true + */ + reconnection?: boolean; + + /** + * How many reconnection attempts should we try? + * @default Infinity + */ + reconnectionAttempts?: boolean; + + /** + * The time delay in milliseconds between reconnection attempts + * @default 1000 + */ + reconnectionDelay?: number; + + /** + * The max time delay in milliseconds between reconnection attempts + * @default 5000 + */ + reconnectionDelayMax?: number; + + /** + * Used in the exponential backoff jitter when reconnecting + * @default 0.5 + */ + randomizationFactor?: number; + + /** + * The timeout in milliseconds for our connection attempt + * @default 20000 + */ + timeout?: number; + + /** + * Should we automically connect? + * @default true + */ + autoConnect?: boolean; + + /** + * The host that we're connecting to. Set from the URI passed when connecting + */ + host?: string; + + /** + * The hostname for our connection. Set from the URI passed when connecting + */ + hostname?: string; + + /** + * If this is a secure connection. Set from the URI passed when connecting + */ + secure?: boolean; + + /** + * The port for our connection. Set from the URI passed when connecting + */ + port?: string; + + /** + * Any query parameters in our uri. Set from the URI passed when connecting + */ + query?: Object; + + /** + * `http.Agent` to use, defaults to `false` (NodeJS only) + */ + agent?: string|boolean; + + /** + * Whether the client should try to upgrade the transport from + * long-polling to something better. + * @default true + */ + upgrade?: boolean; + + /** + * Forces JSONP for polling transport. + */ + forceJSONP?: boolean; + + /** + * Determines whether to use JSONP when necessary for polling. If + * disabled (by settings to false) an error will be emitted (saying + * "No transports available") if no other transports are available. + * If another transport is available for opening a connection (e.g. + * WebSocket) that transport will be used instead. + * @default true + */ + jsonp?: boolean; + + /** + * Forces base 64 encoding for polling transport even when XHR2 + * responseType is available and WebSocket even if the used standard + * supports binary. + */ + forceBase64?: boolean; + + /** + * Enables XDomainRequest for IE8 to avoid loading bar flashing with + * click sound. default to `false` because XDomainRequest has a flaw + * of not sending cookie. + * @default false + */ + enablesXDR?: boolean; + + /** + * The param name to use as our timestamp key + * @default 't' + */ + timestampParam?: string; + + /** + * Whether to add the timestamp with each transport request. Note: this + * is ignored if the browser is IE or Android, in which case requests + * are always stamped + * @default false + */ + timestampRequests?: boolean; + + /** + * A list of transports to try (in order). Engine.io always attempts to + * connect directly with the first one, provided the feature detection test + * for it passes. + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * The port the policy server listens on + * @default 843 + */ + policyPost?: number; + + /** + * If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will + * initially try websocket. A connection attempt following a transport error + * will use the normal upgrade process. It is recommended you turn this on + * only when using SSL/TLS connections, or if you know that your network does + * not block websockets. + * @default false + */ + rememberUpgrade?: boolean; + + /** + * Are we only interested in transports that support binary? + */ + onlyBinaryUpgrades?: boolean; + + /** + * (SSL) Certificate, Private key and CA certificates to use for SSL. + * Can be used in Node.js client environment to manually specify + * certificate information. + */ + pfx?: string; + + /** + * (SSL) Private key to use for SSL. Can be used in Node.js client + * environment to manually specify certificate information. + */ + key?: string; + + /** + * (SSL) A string or passphrase for the private key or pfx. Can be + * used in Node.js client environment to manually specify certificate + * information. + */ + passphrase?: string + + /** + * (SSL) Public x509 certificate to use. Can be used in Node.js client + * environment to manually specify certificate information. + */ + cert?: string; + + /** + * (SSL) An authority certificate or array of authority certificates to + * check the remote host against.. Can be used in Node.js client + * environment to manually specify certificate information. + */ + ca?: string|string[]; + + /** + * (SSL) A string describing the ciphers to use or exclude. Consult the + * [cipher format list] + * (http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for + * details on the format.. Can be used in Node.js client environment to + * manually specify certificate information. + */ + ciphers?: string; + + /** + * (SSL) If true, the server certificate is verified against the list of + * supplied CAs. An 'error' event is emitted if verification fails. + * Verification happens at the connection level, before the HTTP request + * is sent. Can be used in Node.js client environment to manually specify + * certificate information. + */ + rejectUnauthorized?: boolean; + + } } diff --git a/socket.io/legacy/socket.io-1.2.0.d.ts b/socket.io/legacy/socket.io-1.2.0.d.ts new file mode 100644 index 000000000..3f3c042fe --- /dev/null +++ b/socket.io/legacy/socket.io-1.2.0.d.ts @@ -0,0 +1,96 @@ +// Type definitions for socket.io 1.2.0 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'socket.io' { + var server: SocketIOStatic; + + export = server; +} + +interface SocketIOStatic { + (): SocketIO.Server; + (srv: any, opts?: any): SocketIO.Server; + (port: number, opts?: any): SocketIO.Server; + (opts: any): SocketIO.Server; + + listen: SocketIOStatic; +} + +declare module SocketIO { + interface Server { + serveClient(v: boolean): Server; + path(v: string): Server; + adapter(v: any): Server; + origins(v: string): Server; + sockets: Namespace; + attach(srv: any, opts?: any): Server; + attach(port: number, opts?: any): Server; + listen(srv: any, opts?: any): Server; + listen(port: number, opts?: any): Server; + bind(srv: any): Server; + onconnection(socket: any): Server; + of(nsp: string): Namespace; + emit(name: string, ...args: any[]): Socket; + use(fn: Function): Namespace; + + on(event: 'connection', listener: (socket: Socket) => void): Namespace; + on(event: 'connect', listener: (socket: Socket) => void): Namespace; + on(event: string, listener: Function): Namespace; + } + + interface Namespace extends NodeJS.EventEmitter { + name: string; + connected: { [id: string]: Socket }; + use(fn: Function): Namespace; + in(room: string): Namespace; + + on(event: 'connection', listener: (socket: Socket) => void): Namespace; + on(event: 'connect', listener: (socket: Socket) => void): Namespace; + on(event: string, listener: Function): Namespace; + } + + interface Socket { + rooms: string[]; + client: Client; + conn: any; + request: any; + id: string; + handshake: { + headers: any; + time: string; + address: any; + xdomain: boolean; + secure: boolean; + issued: number; + url: string; + query: any; + }; + + emit(name: string, ...args: any[]): Socket; + join(name: string, fn?: Function): Socket; + leave(name: string, fn?: Function): Socket; + to(room: string): Socket; + in(room: string): Socket; + send(...args: any[]): Socket; + write(...args: any[]): Socket; + + on(event: string, listener: Function): Socket; + once(event: string, listener: Function): Socket; + removeListener(event: string, listener: Function): Socket; + removeAllListeners(event: string): Socket; + broadcast: Socket; + volatile: Socket; + connected: boolean; + disconnect(close?: boolean): Socket; + } + + interface Client { + conn: any; + request: any; + id: string; + } +} diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index 3f3c042fe..045e0007a 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -1,96 +1,823 @@ -// Type definitions for socket.io 1.2.0 +// Type definitions for socket.io 1.3.5 // Project: http://socket.io/ -// Definitions by: PROGRE +// Definitions by: divillysausages // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module 'socket.io' { - var server: SocketIOStatic; + var server: SocketIOStatic; - export = server; + export = server; } interface SocketIOStatic { - (): SocketIO.Server; - (srv: any, opts?: any): SocketIO.Server; - (port: number, opts?: any): SocketIO.Server; - (opts: any): SocketIO.Server; + /** + * Default Server constructor + */ + (): SocketIO.Server; + + /** + * Creates a new Server + * @param srv The HTTP server that we're going to bind to + * @param opts An optional parameters object + */ + (srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param port A port to bind to, as a number, or a string + * @param An optional parameters object + */ + (port: string|number, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param A parameters object + */ + (opts: SocketIO.ServerOptions): SocketIO.Server; + /** + * Backwards compatibility + * @see io().listen() + */ listen: SocketIOStatic; } declare module SocketIO { - interface Server { - serveClient(v: boolean): Server; - path(v: string): Server; - adapter(v: any): Server; - origins(v: string): Server; - sockets: Namespace; - attach(srv: any, opts?: any): Server; - attach(port: number, opts?: any): Server; - listen(srv: any, opts?: any): Server; - listen(port: number, opts?: any): Server; - bind(srv: any): Server; - onconnection(socket: any): Server; - of(nsp: string): Namespace; - emit(name: string, ...args: any[]): Socket; - use(fn: Function): Namespace; + + interface Server { + + /** + * A dictionary of all the namespaces currently on this Server + */ + nsps: {[namespace: string]: Namespace}; + + /** + * The default '/' Namespace + */ + sockets: Namespace; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Server; + + /** + * Server request verification function, that checks for allowed origins + * @param req The http.IncomingMessage request + * @param fn The callback to be called. It should take one parameter, err, + * which will be null if there was no problem, and one parameter, success, + * of type boolean + */ + checkRequest( req:any, fn:( err: any, success: boolean ) => void ):void; + + /** + * Gets whether we're serving the client.js file or not + * @default true + */ + serveClient(): boolean; + + /** + * Sets whether we're serving the client.js file or not + * @param v True if we want to serve the file, false otherwise + * @default true + * @return This Server + */ + serveClient( v: boolean ): Server; + + /** + * Gets the client serving path + * @default '/socket.io' + */ + path(): string; + + /** + * Sets the client serving path + * @param v The path to serve the client file on + * @default '/socket.io' + * @return This Server + */ + path( v: string ): Server; + + /** + * Gets the adapter that we're going to use for handling rooms + * @default typeof Adapter + */ + adapter(): any; + + /** + * Sets the adapter (class) that we're going to use for handling rooms + * @param v The class for the adapter to create + * @default typeof Adapter + * @return This Server + */ + adapter( v: any ): Server; + + /** + * Gets the allowed origins for requests + * @default "*:*" + */ + origins(): string; + + /** + * Sets the allowed origins for requests + * @param v The allowed origins, in host:port form + * @default "*:*" + * return This Server + */ + origins( v: string ): Server; + + /** + * Attaches socket.io to a server + * @param srv The http.Server that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( srv: any, opts?: ServerOptions ): Server; + + /** + * Attaches socket.io to a port + * @param port The port that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( port: number, opts?: ServerOptions ): Server; + + /** + * @see attach( srv, opts ) + */ + listen( srv: any, opts?: ServerOptions ): Server; + + /** + * @see attach( port, opts ) + */ + listen( port: number, opts?: ServerOptions ): Server; + + /** + * Binds socket.io to an engine.io intsance + * @param src The Engine.io (or compatible) server to bind to + * @return This Server + */ + bind( srv: any ): Server; + + /** + * Called with each incoming connection + * @param socket The Engine.io Socket + * @return This Server + */ + onconnection( socket: any ): Server; + + /** + * Looks up/creates a Namespace + * @param nsp The name of the NameSpace to look up/create. Should start + * with a '/' + * @return The Namespace + */ + of( nsp: string ): Namespace; + + /** + * Closes the server connection + */ + close():void; - on(event: 'connection', listener: (socket: Socket) => void): Namespace; - on(event: 'connect', listener: (socket: Socket) => void): Namespace; - on(event: string, listener: Function): Namespace; - } + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return The default '/' Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @return The default '/' Namespace + */ + on( event: string, listener: Function ): Namespace; + + /** + * Targets a room when emitting to the default '/' Namespace + * @param room The name of the room that we're targeting + * @return The default '/' Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket, on the default '/' Namespace + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return The default '/' Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Emits an event to the default Namespace + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return The default '/' Namespace + */ + emit( event: string, ...args: any[]): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return The default '/' Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + } + + /** + * Options to pass to our server when creating it + */ + interface ServerOptions { + + /** + * The path to server the client file to + * @default '/socket.io' + */ + path?: string; + + /** + * Should we serve the client file? + * @default true + */ + serveClient?: boolean; + + /** + * The adapter to use for handling rooms. NOTE: this should be a class, + * not an object + * @default typeof Adapter + */ + adapter?: Adapter; + + /** + * Accepted origins + * @default '*:*' + */ + origins?: string; + + /** + * How many milliseconds without a pong packed to consider the connection closed (engine.io) + * @default 60000 + */ + pingTimeout?: number; + + /** + * How many milliseconds before sending a new ping packet (keep-alive) (engine.io) + * @default 25000 + */ + pingInterval?: number; + + /** + * How many bytes or characters a message can be when polling, before closing the session + * (to avoid Dos) (engine.io) + * @default 10E7 + */ + maxHttpBufferSize?: number; + + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn( err, success ), where success is a boolean + * value where false means that the request is rejected, and err is an error code (engine.io) + * @default null + */ + allowRequest?: (request:any, callback: (err: number, success: boolean) => void) => void; + + /** + * Transports to allow connections to (engine.io) + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * Whether to allow transport upgrades (engine.io) + * @default true + */ + allowUpgrades?: boolean; + + /** + * parameters of the WebSocket permessage-deflate extension (see ws module). + * Set to false to disable (engine.io) + * @default true + */ + perMessageDeflate?: Object|boolean; + + /** + * Parameters of the http compression for the polling transports (see zlib). + * Set to false to disable, or set an object with parameter "threshold:number" + * to only compress data if the byte size is above this value (1024) (engine.io) + * @default true|1024 + */ + httpCompression?: Object|boolean; + + /** + * Name of the HTTP cookie that contains the client sid to send as part of + * handshake response headers. Set to false to not send one (engine.io) + * @default "io" + */ + cookie?: string|boolean; + } - interface Namespace extends NodeJS.EventEmitter { - name: string; - connected: { [id: string]: Socket }; - use(fn: Function): Namespace; - in(room: string): Namespace; + /** + * The Namespace, sandboxed environments for sockets, each connection + * to a Namespace requires a new Socket + */ + interface Namespace extends NodeJS.EventEmitter { + + /** + * The name of the NameSpace + */ + name: string; + + /** + * The controller Server for this Namespace + */ + server: Server; + + /** + * A list of all the Sockets connected to this Namespace + */ + sockets: Socket[]; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + connected: { [id: string]: Socket }; + + /** + * The Adapter that we're using to handle dealing with rooms etc + */ + adapter: Adapter; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return This Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Targets a room when emitting + * @param room The name of the room that we're targeting + * @return This Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return This Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; - on(event: 'connection', listener: (socket: Socket) => void): Namespace; - on(event: 'connect', listener: (socket: Socket) => void): Namespace; - on(event: string, listener: Function): Namespace; - } + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return This Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @ This Namespace + */ + on( event: string, listener: Function ): Namespace; + } - interface Socket { - rooms: string[]; - client: Client; - conn: any; - request: any; - id: string; - handshake: { - headers: any; - time: string; - address: any; - xdomain: boolean; - secure: boolean; - issued: number; - url: string; - query: any; - }; + /** + * The socket, which handles our connection for a namespace. NOTE: while + * we technically extend NodeJS.EventEmitter, we're not putting it here + * as we have a problem with the emit() event (as it's overridden with a + * different return) + */ + interface Socket { + + /** + * The namespace that this socket is for + */ + nsp: Namespace; + + /** + * The Server that our namespace is in + */ + server: Server; + + /** + * The Adapter that we use to handle our rooms + */ + adapter: Adapter; + + /** + * The unique ID for this Socket. Regenerated at every connection. This is + * also the name of the room that the Socket automatically joins on connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The Client associated with this Socket + */ + client: Client; + + /** + * The underlying Engine.io Socket instance + */ + conn: { + + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + }; + + /** + * The list of rooms that this Socket is currently in + */ + rooms: string[]; + + /** + * Is the Socket currently connected? + */ + connected: boolean; + + /** + * Is the Socket currently disconnected? + */ + disconnected: boolean; + + /** + * The object used when negociating the handshake + */ + handshake: { + /** + * The headers passed along with the request. e.g. 'host', + * 'connection', 'accept', 'referer', 'cookie' + */ + headers: any; + + /** + * The current time, as a string + */ + time: string; + + /** + * The remote address of the connection request + */ + address: string; + + /** + * Is this a cross-domain request? + */ + xdomain: boolean; + + /** + * Is this a secure request? + */ + secure: boolean; + + /** + * The timestamp for when this was issued + */ + issued: number; + + /** + * The request url + */ + url: string; + + /** + * Any query string parameters in the request url + */ + query: any; + }; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Socket; + + /** + * Sets the 'volatile' flag when emitting an event. Volatile messages are + * messages that can be dropped because of network issues and the like. Use + * for high-volume/real-time messages where you don't need to receive *all* + * of them + */ + volatile: Socket; + + /** + * Sets the 'broadcast' flag when emitting an event. Broadcasting an event + * will send it to all the other sockets in the namespace except for yourself + */ + broadcast: Socket; + + /** + * Emits an event to this client. If the 'broadcast' flag was set, this will + * emit to all other clients, except for this one + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return This Socket + */ + emit( event: string, ...args: any[]): Socket; + + /** + * Targets a room when broadcasting + * @param room The name of the room that we're targeting + * @return This Socket + */ + to( room: string ): Socket; + + /** + * @see to( room ) + */ + in( room: string ): Socket; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + */ + send( ...args: any[] ): Socket; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Socket; + + /** + * Joins a room. You can join multiple rooms, and by default, on connection, + * you join a room with the same name as your ID + * @param name The name of the room that we want to join + * @param fn An optional callback to call when we've joined the room. It should + * take an optional parameter, err, of a possible error + * @return This Socket + */ + join( name: string, fn?: ( err?: any ) => void ): Socket; + + /** + * Leaves a room + * @param name The name of the room to leave + * @param fn An optional callback to call when we've left the room. It should + * take on optional parameter, err, of a possible error + */ + leave( name: string, fn?: Function ): Socket; + + /** + * Leaves all the rooms that we've joined + */ + leaveAll(): void; + + /** + * Disconnects this Socket + * @param close If true, also closes the underlying connection + * @return This Socket + */ + disconnect( close: boolean ): Socket; + + /** + * Adds a listener for a particular event. Calling multiple times will add + * multiple listeners + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on the + * event in question + * @return This Socket + */ + on( event: string, fn: Function ): Socket; + + /** + * @see on( event, fn ) + */ + addListener( event: string, fn: Function ): Socket; + + /** + * Adds a listener for a particular event that will be invoked + * a single time before being automatically removed + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on + * the event in question + * @return This Socket + */ + once( event: string, fn: Function ): Socket; + + /** + * Removes a listener for a particular type of event. This will either + * remove a specific listener, or all listeners for this type of event + * @param event The event that we want to remove the listener of + * @param fn The function to remove, or null if we want to remove all functions + * @return This Socket + */ + removeListener( event: string, fn?: Function ): Socket; + + /** + * Removes all event listeners on this object + * @return This Socket + */ + removeAllListeners(): Socket; + + /** + * Sets the maximum number of listeners this instance can have + * @param n The max number of listeners we can add to this emitter + * @return This Socket + */ + setMaxListeners( n: number ): Socket; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + } + + /** + * The interface used when dealing with rooms etc + */ + interface Adapter extends NodeJS.EventEmitter { + + /** + * The namespace that this adapter is for + */ + nsp: Namespace; + + /** + * A dictionary of all the rooms that we have in this namespace, each room + * a dictionary of all the sockets currently in that room + */ + rooms: {[room: string]: {[id: string]: boolean }}; + + /** + * A dictionary of all the socket ids that we're dealing with, and all + * the rooms that the socket is currently in + */ + sids: {[id: string]: {[room: string]: boolean}}; + + /** + * Adds a socket to a room. If the room doesn't exist, it's created + * @param id The ID of the socket to add + * @param room The name of the room to add the socket to + * @param callback An optional callback to call when the socket has been + * added. It should take an optional parameter, error, if there was a problem + */ + add( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from a room. If there are no more sockets in the room, + * the room is deleted + * @param id The ID of the socket that we're removing + * @param room The name of the room to remove the socket from + * @param callback An optional callback to call when the socket has been + * removed. It should take on optional parameter, error, if there was a problem + */ + del( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from all the rooms that it's joined + * @param id The ID of the socket that we're removing + */ + delAll( id: string ):void; + + /** + * Broadcasts a packet + * @param packet The packet to broadcast + * @param opts Any options to send along: + * - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets + * - except: A list of Socket IDs to exclude + * - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast') + */ + broadcast( packet: any, opts: { rooms?: string[], except?: string[], flags?: {[flag: string]: boolean} } ):void; + } - emit(name: string, ...args: any[]): Socket; - join(name: string, fn?: Function): Socket; - leave(name: string, fn?: Function): Socket; - to(room: string): Socket; - in(room: string): Socket; - send(...args: any[]): Socket; - write(...args: any[]): Socket; - - on(event: string, listener: Function): Socket; - once(event: string, listener: Function): Socket; - removeListener(event: string, listener: Function): Socket; - removeAllListeners(event: string): Socket; - broadcast: Socket; - volatile: Socket; - connected: boolean; - disconnect(close?: boolean): Socket; - } - - interface Client { - conn: any; - request: any; - id: string; - } + /** + * The client behind each socket (can have multiple sockets) + */ + interface Client { + /** + * The Server that this client belongs to + */ + server: Server; + + /** + * The underlying Engine.io Socket instance + */ + conn: { + + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + }; + + /** + * The ID for this client. Regenerated at every connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The list of sockets currently connect via this client (i.e. to different + * namespaces) + */ + sockets: Socket[]; + + /** + * A dictionary of all the namespaces for this client, with the Socket that + * deals with that namespace + */ + nsps: {[nsp: string]: Socket}; + } } From 812ed1d1a8c8f15007234fb64262f4101b115565 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:31:56 +0200 Subject: [PATCH 064/416] Fixed bad link to node.d.ts in the legacy file --- socket.io/legacy/socket.io-1.2.0.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/socket.io/legacy/socket.io-1.2.0.d.ts b/socket.io/legacy/socket.io-1.2.0.d.ts index 3f3c042fe..92f037319 100644 --- a/socket.io/legacy/socket.io-1.2.0.d.ts +++ b/socket.io/legacy/socket.io-1.2.0.d.ts @@ -3,7 +3,7 @@ // Definitions by: PROGRE // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module 'socket.io' { var server: SocketIOStatic; From 9c47c6a65a0542267bb1a7abd1ef602e6d052d97 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:33:48 +0200 Subject: [PATCH 065/416] Added the test files for the legacy socket.io code --- .../legacy/socket.io-client-1.2.0-tests.ts | 57 +++++++ socket.io/legacy/socket.io-1.2.0-tests.ts | 145 ++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 socket.io-client/legacy/socket.io-client-1.2.0-tests.ts create mode 100644 socket.io/legacy/socket.io-1.2.0-tests.ts diff --git a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts new file mode 100644 index 000000000..803a9c786 --- /dev/null +++ b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts @@ -0,0 +1,57 @@ +/// + +function testUsingWithNodeHTTPServer() { + var socket = io('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithExpress() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithTheExpressFramework() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testRestrictingYourselfToANamespace() { + var chat = io.connect('http://localhost/chat') + , news = io.connect('http://localhost/news'); + + chat.on('connect', function () { + chat.emit('hi!'); + }); + + news.on('news', function () { + news.emit('woot'); + }); +} + +function testSendingAndGettingData() { + var socket = io(); + socket.on('connect', function () { + socket.emit('ferret', 'tobi', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var socket = io('http://localhost/'); + socket.on('connect', function () { + socket.emit('hi'); + + socket.on('message', function (msg: any) { + }); + }); +} diff --git a/socket.io/legacy/socket.io-1.2.0-tests.ts b/socket.io/legacy/socket.io-1.2.0-tests.ts new file mode 100644 index 000000000..442e67775 --- /dev/null +++ b/socket.io/legacy/socket.io-1.2.0-tests.ts @@ -0,0 +1,145 @@ +import socketIO = require('socket.io'); + +function testUsingWithNodeHTTPServer() { + var app = require('http').createServer(handler); + var io = socketIO(app); + var fs = require('fs'); + + app.listen(80); + + function handler(req: any, res: any) { + fs.readFile(__dirname + '/index.html', + function (err: any, data: any) { + if (err) { + res.writeHead(500); + return res.end('Error loading index.html'); + } + + res.writeHead(200); + res.end(data); + }); + } + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithExpress() { + var app = require('express')(); + var server = require('http').Server(app); + var io = socketIO(server); + + server.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithTheExpressFramework() { + var app = require('express').createServer(); + var io = socketIO(app); + + app.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testSendingAndReceivingEvents() { + var io = socketIO(80); + + io.on('connection', function (socket) { + io.emit('this', { will: 'be received by everyone' }); + + socket.on('private message', function (from: any, msg: any) { + console.log('I received a private message by ', from, ' saying ', msg); + }); + + socket.on('disconnect', function () { + io.sockets.emit('user disconnected'); + }); + }); +} + +function testRestrictingYourselfToANamespace() { + var io = socketIO.listen(80); + var chat = io + .of('/chat') + .on('connection', function (socket) { + socket.emit('a message', { + that: 'only' + , '/chat': 'will get' + }); + chat.emit('a message', { + everyone: 'in' + , '/chat': 'will get' + }); + }); + + var news = io + .of('/news') + .on('connection', function (socket) { + socket.emit('item', { news: 'item' }); + }); +} + +function testSendingVolatileMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + var tweets = setInterval(function () { + socket.volatile.emit('bieber tweet', {}); + }, 100); + + socket.on('disconnect', function () { + clearInterval(tweets); + }); + }); +} + +function testSendingAndGettingData() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('ferret', function (name: any, fn: any) { + fn('woot'); + }); + }); +} + +function testBroadcastingMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.broadcast.emit('user connected'); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('message', function () { }); + socket.on('disconnect', function () { }); + }); +} From 9c07a9d60257a8e1631aee74184617c2eeca401d Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:39:25 +0200 Subject: [PATCH 066/416] Added the correct paths for the definition files in the tests --- socket.io-client/legacy/socket.io-client-1.2.0-tests.ts | 2 +- socket.io/legacy/socket.io-1.2.0-tests.ts | 2 ++ socket.io/socket.io-tests.ts | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts index 803a9c786..3ad8db95f 100644 --- a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts +++ b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts @@ -1,4 +1,4 @@ -/// +/// function testUsingWithNodeHTTPServer() { var socket = io('http://localhost'); diff --git a/socket.io/legacy/socket.io-1.2.0-tests.ts b/socket.io/legacy/socket.io-1.2.0-tests.ts index 442e67775..93899d0d9 100644 --- a/socket.io/legacy/socket.io-1.2.0-tests.ts +++ b/socket.io/legacy/socket.io-1.2.0-tests.ts @@ -1,3 +1,5 @@ +/// + import socketIO = require('socket.io'); function testUsingWithNodeHTTPServer() { diff --git a/socket.io/socket.io-tests.ts b/socket.io/socket.io-tests.ts index 442e67775..93899d0d9 100644 --- a/socket.io/socket.io-tests.ts +++ b/socket.io/socket.io-tests.ts @@ -1,3 +1,5 @@ +/// + import socketIO = require('socket.io'); function testUsingWithNodeHTTPServer() { From 6169c072eae80fc02e31bc8bd0a2baf3fc4549cb Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sun, 12 Jul 2015 00:04:42 +0200 Subject: [PATCH 067/416] Added the "id" parameter to the client Socket object --- socket.io-client/socket.io-client.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index 7e15773e6..42d366412 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -177,6 +177,12 @@ declare module SocketIOClient { */ nsp: string; + /** + * The ID of the socket; matches the server ID and is set when we're connected, and cleared + * when we're disconnected + */ + id: string; + /** * Are we currently connected? * @default false From c5a352c7d33c53c28080defb0d6e45605f8b79ea Mon Sep 17 00:00:00 2001 From: Robert Baker Date: Sat, 11 Jul 2015 20:18:06 -0700 Subject: [PATCH 068/416] fixed palette def. Don't know how that wasn't in there when I versioned it. --- angular-material/angular-material-0.9.0.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-material/angular-material-0.9.0.d.ts b/angular-material/angular-material-0.9.0.d.ts index 06c1ecf25..1383b0beb 100644 --- a/angular-material/angular-material-0.9.0.d.ts +++ b/angular-material/angular-material-0.9.0.d.ts @@ -150,8 +150,8 @@ declare module angular.material { A400?: string; A700?: string; contrastDefaultColor?: string; - contrastDarkColors?: string; - contrastStrongLightColors?: string; + contrastDarkColors?: string|string[]; + contrastLightColors?: string|string[]; } interface MDThemeHues { From 31117051dd39895115a42836e966edbec69da24d Mon Sep 17 00:00:00 2001 From: "Dylan R. E. Moonfire" Date: Sun, 12 Jul 2015 01:58:34 -0500 Subject: [PATCH 069/416] Type definitions for Natural 0.2.1 --- natural/natural-tests.ts | 262 +++++++++++++++++++++++++++++++++++++++ natural/natural.d.ts | 182 +++++++++++++++++++++++++++ 2 files changed, 444 insertions(+) create mode 100644 natural/natural-tests.ts create mode 100644 natural/natural.d.ts diff --git a/natural/natural-tests.ts b/natural/natural-tests.ts new file mode 100644 index 000000000..22ba29c5a --- /dev/null +++ b/natural/natural-tests.ts @@ -0,0 +1,262 @@ +// Type definitions for Natural 0.2.1 +// Project: https://github.com/NaturalNode/natural +// Definitions by: Dylan R. E. Moonfire +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +import natural = require('natural'); + +// Tokenizers +var tokenizer = new natural.WordTokenizer(); +console.log(tokenizer.tokenize("your dog has fleas.")); + +tokenizer = new natural.TreebankWordTokenizer(); +console.log(tokenizer.tokenize("my dog hasn't any fleas.")); +// [ 'my', 'dog', 'has', 'n\'t', 'any', 'fleas', '.' ] + +tokenizer = new natural.RegexpTokenizer({pattern: /\-/}); +console.log(tokenizer.tokenize("flea-dog")); +// [ 'flea', 'dog' ] + +tokenizer = new natural.WordPunctTokenizer(); +console.log(tokenizer.tokenize("my dog hasn't any fleas.")); +// [ 'my', 'dog', 'hasn', '\'', 't', 'any', 'fleas', '.' ] + +// String Distance +console.log(natural.JaroWinklerDistance("dixon","dicksonx")) +console.log(natural.JaroWinklerDistance('not', 'same')); + +console.log(natural.LevenshteinDistance("ones","onez")); +console.log(natural.LevenshteinDistance('one', 'one')); + +console.log(natural.LevenshteinDistance("ones","onez", { + insertion_cost: 1, + deletion_cost: 1, + substitution_cost: 1 +})); + +console.log(natural.DiceCoefficient('thing', 'thing')); +console.log(natural.DiceCoefficient('not', 'same')); + +// Stemmers +console.log(natural.PorterStemmer.stem("words")); // stem a single word +console.log(natural.PorterStemmerRu.stem("падший")); +console.log(natural.PorterStemmerEs.stem("jugaría")); +console.log(natural.PorterStemmerFa.stem("jugaría")); +console.log(natural.PorterStemmerFr.stem("jugaría")); +console.log(natural.PorterStemmerIt.stem("jugaría")); +console.log(natural.PorterStemmerNo.stem("jugaría")); +console.log(natural.PorterStemmerPt.stem("jugaría")); + +// Classifiers +var classifier = new natural.BayesClassifier(); + +classifier.addDocument('i am long qqqq', 'buy'); +classifier.addDocument('buy the q\'s', 'buy'); +classifier.addDocument('short gold', 'sell'); +classifier.addDocument('sell gold', 'sell'); + +classifier.train(); +console.log(classifier.classify('i am short silver')); +console.log(classifier.classify('i am long copper')); +console.log(classifier.getClassifications('i am long copper')); +classifier.addDocument(['sell', 'gold'], 'sell'); +classifier.events.on('trainedWithDocument', function (obj: any) { + console.log(obj); +}); +classifier.save('classifier.json', function(err, classifier) { + // the classifier is saved to the classifier.json file! +}); +natural.BayesClassifier.load('classifier.json', null, function(err, classifier) { + console.log(classifier.classify('long SUNW')); + console.log(classifier.classify('short SUNW')); +}); +var classifier = new natural.BayesClassifier(); +classifier.addDocument(['sell', 'gold'], 'sell'); +classifier.addDocument(['buy', 'silver'], 'buy'); +var raw = JSON.stringify(classifier); +var restoredClassifier = natural.BayesClassifier.restore(JSON.parse(raw)); +console.log(restoredClassifier.classify('i should sell that')); + +// Phonetics +var metaphone = natural.Metaphone, soundEx = natural.SoundEx; + +var wordA = 'phonetics'; +var wordB = 'fonetix'; +if(metaphone.compare(wordA, wordB)) + console.log('they sound alike!'); +console.log(metaphone.process('phonetics')); +console.log(metaphone.process('phonetics', 3)); +var dm = natural.DoubleMetaphone; + +var encodings = dm.process('Matrix'); +console.log(encodings[0]); +console.log(encodings[1]); +if(soundEx.compare(wordA, wordB)) + console.log('they sound alike!'); + +// Inflectors +var nounInflector = new natural.NounInflector(); +console.log(nounInflector.pluralize('radius')); +console.log(nounInflector.singularize('beers')); +var countInflector = natural.CountInflector; +console.log(countInflector.nth(1)); +console.log(countInflector.nth(111)); +var verbInflector = new natural.PresentVerbInflector(); +console.log(verbInflector.singularize('become')); +console.log(verbInflector.pluralize('becomes')); +var NGrams = natural.NGrams; +console.log(NGrams.bigrams('some words here')); +console.log(NGrams.bigrams(['some', 'words', 'here'])); +console.log(NGrams.trigrams('some other words here')); +console.log(NGrams.trigrams(['some', 'other', 'words', 'here'])); +console.log(NGrams.ngrams('some other words here for you', 4)); +console.log(NGrams.ngrams(['some', 'other', 'words', 'here', 'for', + 'you'], 4)); +console.log(NGrams.ngrams('some other words here for you', 4, '[start]', '[end]')); +console.log(NGrams.ngrams('some other words here for you', 4, null, '[end]')); +var NGramsZH = natural.NGramsZH; +console.log(NGramsZH.bigrams('中文测试')); +console.log(NGramsZH.bigrams(['中', '文', '测', '试'])); +console.log(NGramsZH.trigrams('中文测试')); +console.log(NGramsZH.trigrams(['中', '文', '测', '试'])); +console.log(NGramsZH.ngrams('一个中文测试', 4)); +console.log(NGramsZH.ngrams(['一', '个', '中', '文', '测', + '试'], 4)); +var TfIdf = natural.TfIdf, + tfidf = new TfIdf(); + +tfidf.addDocument('this document is about node.'); +tfidf.addDocument('this document is about ruby.'); +tfidf.addDocument('this document is about ruby and node.'); +tfidf.addDocument('this document is about node. it has node examples'); + +console.log('node --------------------------------'); +tfidf.tfidfs('node', function(i, measure) { + console.log('document #' + i + ' is ' + measure); +}); + +console.log('ruby --------------------------------'); +tfidf.tfidfs('ruby', function(i, measure) { + console.log('document #' + i + ' is ' + measure); +}); +console.log(tfidf.tfidf('node', 0)); +console.log(tfidf.tfidf('node', 1)); +var tfidf = new TfIdf(); +tfidf.addFileSync('data_files/one.txt'); +tfidf.addFileSync('data_files/two.txt'); +tfidf.addDocument('this document is about node.'); +tfidf.addDocument('this document is about ruby.'); +tfidf.addDocument('this document is about ruby and node.'); + +tfidf.tfidfs('node ruby', function(i, measure) { + console.log('document #' + i + ' is ' + measure); +}); +tfidf.addDocument(['document', 'about', 'node']); +tfidf.addDocument(['document', 'about', 'ruby']); +tfidf.addDocument(['document', 'about', 'ruby', 'node']); +tfidf.addDocument(['document', 'about', 'node', 'node', 'examples']); + +tfidf.tfidfs(['node', 'ruby'], function(i, measure) { + console.log('document #' + i + ' is ' + measure); +}); +tfidf.listTerms(0 /*document index*/).forEach(function(item) { + console.log(item.term + ': ' + item.tfidf); +}); +var tfidf = new TfIdf(); +tfidf.addDocument('document one', 'un'); +tfidf.addDocument('document Two', 'deux'); +var s = JSON.stringify(tfidf); +// save "s" to disk, database or otherwise + +// assuming you pulled "s" back out of storage. +var tfidf = new TfIdf(JSON.parse(s)); + +// Tries +var Trie = natural.Trie; + +var trie = new Trie(); + +// Add one string at a time +trie.addString("test"); + +// Or add many strings +trie.addStrings(["string1", "string2", "string3"]); +console.log(trie.contains("test")); // true +console.log(trie.contains("asdf")); // false +console.log(trie.findPrefix("tester")); // ['test', 'er'] +console.log(trie.findPrefix("string4")); // [null, '4'] +console.log(trie.findPrefix("string3")); // ['string3', ''] +trie.addString("tes"); +trie.addString("est"); +console.log(trie.findMatchesOnPath("tester")); // ['tes', 'test']; +console.log(trie.keysWithPrefix("string")); // ["string1", "string2", "string3"] +trie.contains("TEST"); // false + +var ciTrie = new Trie(false); +ciTrie.addString("test"); +ciTrie.contains("TEsT"); // true + +// Digraph + +var EdgeWeightedDigraph = natural.EdgeWeightedDigraph; +var digraph = new EdgeWeightedDigraph(); +digraph.add(5,4,0.35); +digraph.add(5,1,0.32); +digraph.add(1,3,0.29); +digraph.add(6,2,0.40); +digraph.add(3,6,0.52); +digraph.add(6,4,0.93); +console.log(digraph.v()); +console.log(digraph.e()); + +// ShortestPathTree + +var ShortestPathTree = natural.ShortestPathTree; +var spt = new ShortestPathTree(digraph, 5); +console.log(spt.getDistTo(4)); +console.log(spt.hasDistTo(4)); +console.log(spt.hasDistTo(5)); +console.log(spt.pathTo(4)); + +var ShortestPathTree = natural.ShortestPathTree; +var spt = new ShortestPathTree(digraph, 5); +console.log(spt.getDistTo(4)); +console.log(spt.hasDistTo(4)); +console.log(spt.hasDistTo(5)); +console.log(spt.pathTo(4)); + +// WordNet + +var wordnet = new natural.WordNet(); + +wordnet.lookup('node', function(results) { + results.forEach(function(result) { + console.log('------------------------------------'); + console.log(result.synsetOffset); + console.log(result.pos); + console.log(result.lemma); + console.log(result.synonyms); + console.log(result.pos); + console.log(result.gloss); + }); +}); +var wordnet = new natural.WordNet(); + +wordnet.get(4424418, 'n', function(result) { + console.log('------------------------------------'); + console.log(result.lemma); + console.log(result.pos); + console.log(result.gloss); + console.log(result.synonyms); +}); +var wordnet = new natural.WordNet('/my/wordnet/dict'); + +// Spellcheck + +var corpus = ['something', 'soothing']; +var spellcheck = new natural.Spellcheck(corpus); +spellcheck.isCorrect('cat'); // false +spellcheck.getCorrections('soemthing', 1); // ['something'] +spellcheck.getCorrections('soemthing', 2); // ['something', 'soothing'] diff --git a/natural/natural.d.ts b/natural/natural.d.ts new file mode 100644 index 000000000..d559f3801 --- /dev/null +++ b/natural/natural.d.ts @@ -0,0 +1,182 @@ +// Type definitions for Natural 0.2.1 +// Project: https://github.com/NaturalNode/natural +// Definitions by: Dylan R. E. Moonfire +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "natural" { + import events = require("events"); + + class WordTokenizer { + tokenize(text: string): string[]; + } + class AggressiveTokenizer { + tokenize(text: string): string[]; + } + class TreebankWordTokenizer { + tokenize(text: string): string[]; + } + interface RegexTokenizerOptions { + pattern: RegExp; + discardEmpty?: boolean; + } + class RegexpTokenizer { + constructor(options: RegexTokenizerOptions); + tokenize(text: string): string[]; + } + class WordPunctTokenizer { + tokenize(text: string): string[]; + } + + function JaroWinklerDistance(s1: string, s2: string, dt?: number): number; + function LevenshteinDistance(source: string, target: string, options?: any): number; + function DiceCoefficient(str1: string, str2: string): number; + + interface Stemmer { + stem(token: string): string; + } + var PorterStemmer: { + stem(token: string): string; + } + var PorterStemmerRu: { + stem(token: string): string; + } + var PorterStemmerEs: { + stem(token: string): string; + } + var PorterStemmerFa: { + stem(token: string): string; + } + var PorterStemmerFr: { + stem(token: string): string; + } + var PorterStemmerIt: { + stem(token: string): string; + } + var PorterStemmerNo: { + stem(token: string): string; + } + var PorterStemmerPt: { + stem(token: string): string; + } + + interface BayesClassifierCallback { (err: any, classifier: any): void } + class BayesClassifier { + events: events.EventEmitter; + addDocument(text: string, stem: string): void; + addDocument(text: string[], stem: string): void; + train(): void; + classify(observation: string): string; + getClassifications(observation: string): string[]; + save(filename: string, callback: BayesClassifierCallback): void; + static load(filename: string, stemmer: Stemmer, callback: BayesClassifierCallback): void; + static restore(classifier: any, stemmer?: Stemmer): BayesClassifier; + } + + var Metaphone: { + compare(stringA: string, stringB: string): boolean; + process(token: string, maxLength?: number): string; + }; + var SoundEx: { + compare(stringA: string, stringB: string): boolean; + process(token: string, maxLength?: number): string; + }; + var DoubleMetaphone: { + compare(stringA: string, stringB: string): boolean; + process(token: string, maxLength?: number): string[]; + }; + + class NounInflector { + pluralize(token: string): string; + singularize(token: string): string; + } + var CountInflector: { + nth(i: number): string; + } + class PresentVerbInflector { + pluralize(token: string): string; + singularize(token: string): string; + } + var NGrams: { + bigrams(sequence: string, startSymbol?: string, endSymbol?: string): string[][]; + bigrams(sequence: string[], startSymbol?: string, endSymbol?: string): string[][]; + trigrams(sequence: string, startSymbol?: string, endSymbol?: string): string[][]; + trigrams(sequence: string[], startSymbol?: string, endSymbol?: string): string[][]; + ngrams(sequence: string, n: number, startSymbol?: string, endSymbol?: string): string[][]; + ngrams(sequence: string[], n: number, startSymbol?: string, endSymbol?: string): string[][]; + } + var NGramsZH: { + bigrams(sequence: string, startSymbol?: string, endSymbol?: string): string[][]; + bigrams(sequence: string[], startSymbol?: string, endSymbol?: string): string[][]; + trigrams(sequence: string, startSymbol?: string, endSymbol?: string): string[][]; + trigrams(sequence: string[], startSymbol?: string, endSymbol?: string): string[][]; + ngrams(sequence: string, n: number, startSymbol?: string, endSymbol?: string): string[][]; + ngrams(sequence: string[], n: number, startSymbol?: string, endSymbol?: string): string[][]; + } + + interface TfIdfCallback { (i: number, measure: number): void } + interface TfIdfTerm { + term: string; + tfidf: number; + } + class TfIdf { + constructor(deserialized?: any); + addDocument(document: string, key?: string, restoreCache?: boolean): void; + addDocument(document: string[], key?: string, restoreCache?: boolean): void; + addFileSync(path: string, encoding?: string, key?: string, restoreCache?: boolean): void; + tfidf(terms: string, d: number): void; + tfidfs(terms: string, callback: TfIdfCallback): void; + tfidfs(terms: string[], callback: TfIdfCallback): void; + listTerms(d: number): TfIdfTerm[]; + } + + class Trie { + constructor(caseSensitive?: boolean); + addString(text: string): boolean; + addStrings(strings: string[]): void; + contains(token: string): boolean; + findPrefix(text: string): string[]; + findMatchesOnPath(text: string): string[]; + keysWithPrefix(text: string): string[]; + } + + class EdgeWeightedDigraph { + add(start: number, end: number, weight: number): void; + v(): number; + e(): number; + } + class ShortestPathTree { + constructor(diagraph: EdgeWeightedDigraph, startVertex: number); + getDistTo(vertex: number): number; + hasDistTo(vertex: number): boolean; + pathTo(vertex: number): number[]; + } + class LongestPathTree { + constructor(diagraph: EdgeWeightedDigraph, startVertex: number); + getDistTo(vertex: number): number; + hasDistTo(vertex: number): boolean; + pathTo(vertex: number): number[]; + } + + interface WordNetLookupResults { + synsetOffset: number; + pos: string; + lemma: string; + synonyms: string[]; + gloss: string; + } + interface WordNetLookupCallback { (results: WordNetLookupResults[]): void } + interface WordNetGetCallback { (results: WordNetLookupResults): void } + class WordNet { + constructor(filename?: string); + lookup(word: string, callback: WordNetLookupCallback): void; + get(synsetOffset: number, pos: string, callback: WordNetGetCallback): void; + } + + class Spellcheck { + constructor(wordlist: string[]); + isCorrect(word: string): boolean; + getCorrections(word: string, maxDistance?: number): string[]; + } +} From 476a231fe363f420b240315aced714a89c0a1c2e Mon Sep 17 00:00:00 2001 From: Kern Handa Date: Sun, 12 Jul 2015 01:14:28 -0700 Subject: [PATCH 070/416] Add typings for contextjs 2.1.1 --- contextjs/contextjs-tests.ts | 16 ++++++++++++++++ contextjs/contextjs.d.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 contextjs/contextjs-tests.ts create mode 100644 contextjs/contextjs.d.ts diff --git a/contextjs/contextjs-tests.ts b/contextjs/contextjs-tests.ts new file mode 100644 index 000000000..7d54e80e6 --- /dev/null +++ b/contextjs/contextjs-tests.ts @@ -0,0 +1,16 @@ +import context = require("contextjs"); + +context.init(); + +context.settings({compress: true}); + +context.attach('#test', [ + {header: 'header 1'}, + {divider: true}, + {text:'foobar', submenu: [ + {text:'sub1'}, + {text:'sub2'} + ]} +]); + +context.destroy('#test'); diff --git a/contextjs/contextjs.d.ts b/contextjs/contextjs.d.ts new file mode 100644 index 000000000..7d1ebb21e --- /dev/null +++ b/contextjs/contextjs.d.ts @@ -0,0 +1,33 @@ +// Type definitions for contextjs 2.1.1 +// Project: https://github.com/jakiestfu/Context.js +// Definitions by: Kern Handa +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "contextjs" { + interface MenuObject { + action?: (e: Event) => void; + divider?: boolean; + header?: string; + href?: string; + subMenu?: MenuObject[]; + target?: string; + text?: string; + } + + interface InitSettings { + above?: string | boolean; + compress?: boolean; + fadeSpeed?: number; + filter?: (e: Element) => void; + preventDoubleContext?: boolean; + } + + module context { + function init(settings?: InitSettings): void; + function destroy(selector: any): void; + function attach(selector: any, menuObjects: MenuObject[]): void; + function settings(settings: InitSettings): void; + } + + export = context; +} From 4ca5b84c2342d04a36f54a3be4870499809ab54f Mon Sep 17 00:00:00 2001 From: Yuichi Murata Date: Sun, 12 Jul 2015 21:27:57 +0900 Subject: [PATCH 071/416] Fix some issues of #4410/issuecomment-110341203 --- react-router/react-router-test.ts | 60 +++++++++++++++++++++++++++++++ react-router/react-router.d.ts | 58 ++++++++++-------------------- 2 files changed, 78 insertions(+), 40 deletions(-) diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index fa335e934..85180cf9e 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -328,3 +328,63 @@ class TransitionTest { }; } } + + +// Context +class ContextTest { + v: Router.Context + + makePath() { + var v1: string = this.v.makePath('home'); + var v2: string = this.v.makePath('home', {p1: 1}); + var v3: string = this.v.makePath('home', {p1: 1}, {q1: 1}); + } + + makeHref() { + var v1: string = this.v.makeHref('home'); + var v2: string = this.v.makeHref('home', {p1: 1}); + var v3: string = this.v.makeHref('home', {p1: 1}, {q1: 1}); + } + + transitionTo() { + var v1: void = this.v.transitionTo('home'); + var v2: void = this.v.transitionTo('home', {p1: 1}); + var v3: void = this.v.transitionTo('home', {p1: 1}, {q1: 1}); + } + + replaceWith() { + var v1: void = this.v.replaceWith('home'); + var v2: void = this.v.replaceWith('home', {p1: 1}); + var v3: void = this.v.replaceWith('home', {p1: 1}, {q1: 1}); + } + + goBack() { + var v: void = this.v.goBack(); + } + + getCurrentPath() { + var v: string = this.v.getCurrentPath(); + } + + getCurrentRoutes() { + var v: Router.Route[] = this.v.getCurrentRoutes(); + } + + getCurrentPathname() { + var v: string = this.v.getCurrentPathname(); + } + + getCurrentParams() { + var v: {} = this.v.getCurrentParams(); + } + + getCurrentQuery() { + var v: {} = this.v.getCurrentQuery(); + } + + isActive() { + var v1: boolean = this.v.isActive('home'); + var v2: boolean = this.v.isActive('home', {p1: 1}); + var v3: boolean = this.v.isActive('home', {p1: 1}, {q1: 1}); + } +} diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index c02892ffe..6a005d967 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -140,7 +140,7 @@ declare module "react-router" { getRouteDepth(): number; createChildRouteHandler(props: {}): RouteHandler; } - interface RouteHandlerClass extends React.ReactElement {} + interface RouteHandlerClass extends React.ComponentClass {} var Link: LinkClass; var RouteHandler: RouteHandlerClass; @@ -253,45 +253,23 @@ declare module "react-router" { length: number; } var History: History; -} -declare module "react" { - import ReactRouter = require("react-router"); - - // for DefaultRoute - function createElement( - type: ReactRouter.DefaultRouteClass, - props: ReactRouter.DefaultRouteProp, - ...children: ReactNode[]): ReactRouter.DefaultRoute; - - // for Link - function createElement( - type: ReactRouter.LinkClass, - props: ReactRouter.LinkProp, - ...children: ReactNode[]): ReactRouter.Link; - - // for NotFoundRoute - function createElement( - type: ReactRouter.NotFoundRouteClass, - props: ReactRouter.NotFoundRouteProp, - ...children: ReactNode[]): ReactRouter.NotFoundRoute; - - // for Redirect - function createElement( - type: ReactRouter.RedirectClass, - props: ReactRouter.RedirectProp, - ...children: ReactNode[]): ReactRouter.Redirect; - - // for Route - function createElement( - type: ReactRouter.RouteClass, - props: ReactRouter.RouteProp, - ...children: ReactNode[]): ReactRouter.Route; - - // for RouteHandler - function createElement( - type: ReactRouter.RouteHandlerClass, - props: ReactRouter.RouteHandlerProp, - ...children: ReactNode[]): ReactRouter.RouteHandler; + // + // Context + // ---------------------------------------------------------------------- + interface Context { + 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; + + getCurrentPath(): string; + getCurrentRoutes(): Route[]; + getCurrentPathname(): string; + getCurrentParams(): {}; + getCurrentQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } } From c09238ca0892e167aa4f85a6826788969662636e Mon Sep 17 00:00:00 2001 From: Yuichi Murata Date: Sun, 12 Jul 2015 21:36:30 +0900 Subject: [PATCH 072/416] Change an indent width of react-router/react-router.d.ts to 4 spaces that is general style in TypeScript --- react-router/react-router.d.ts | 454 ++++++++++++++++----------------- 1 file changed, 227 insertions(+), 227 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 6a005d967..a54805815 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -7,269 +7,269 @@ declare module "react-router" { - import React = require("react"); + import React = require("react"); - // - // Transition - // ---------------------------------------------------------------------- - interface Transition { - path: string; - abortReason: any; - retry(): void; - abort(reason?: any): void; - redirect(to: string, params?: {}, query?: {}): void; - cancel(): void; - from: (transition: Transition, routes: Route[], components?: React.ReactElement[], callback?: (error?: any) => void) => void; - to: (transition: Transition, routes: Route[], params?: {}, query?: {}, callback?: (error?: any) => void) => void; - } + // + // Transition + // ---------------------------------------------------------------------- + interface Transition { + path: string; + abortReason: any; + retry(): void; + abort(reason?: any): void; + redirect(to: string, params?: {}, query?: {}): void; + cancel(): void; + from: (transition: Transition, routes: Route[], components?: React.ReactElement[], callback?: (error?: any) => void) => void; + to: (transition: Transition, routes: Route[], params?: {}, query?: {}, callback?: (error?: any) => void) => void; + } - interface TransitionStaticLifecycle { - willTransitionTo?( - transition: Transition, - params: {}, - query: {}, - callback: Function - ): void; + interface TransitionStaticLifecycle { + willTransitionTo?( + transition: Transition, + params: {}, + query: {}, + callback: Function + ): void; - willTransitionFrom?( - transition: Transition, - component: React.ReactElement, - callback: Function - ): void; - } + willTransitionFrom?( + transition: Transition, + component: React.ReactElement, + callback: Function + ): void; + } - // - // Route Configuration - // ---------------------------------------------------------------------- - // DefaultRoute - interface DefaultRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface DefaultRoute extends React.ReactElement {} - interface DefaultRouteClass extends React.ComponentClass {} + // + // Route Configuration + // ---------------------------------------------------------------------- + // DefaultRoute + interface DefaultRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface DefaultRoute extends React.ReactElement {} + interface DefaultRouteClass extends React.ComponentClass {} - // NotFoundRoute - interface NotFoundRouteProp { - name?: string; - handler: React.ComponentClass; - } - interface NotFoundRoute extends React.ReactElement {} - interface NotFoundRouteClass extends React.ComponentClass {} + // NotFoundRoute + interface NotFoundRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface NotFoundRoute extends React.ReactElement {} + interface NotFoundRouteClass extends React.ComponentClass {} - // Redirect - interface RedirectProp { - path?: string; - from?: string; - to?: string; - } - interface Redirect extends React.ReactElement {} - interface RedirectClass extends React.ComponentClass {} + // Redirect + interface RedirectProp { + path?: string; + from?: string; + to?: string; + } + interface Redirect extends React.ReactElement {} + interface RedirectClass extends React.ComponentClass {} - // Route - interface RouteProp { - name?: string; - path?: string; - handler?: React.ComponentClass; - ignoreScrollBehavior?: boolean; - } - interface Route extends React.ReactElement {} - interface RouteClass extends React.ComponentClass {} + // Route + interface RouteProp { + name?: string; + path?: string; + handler?: React.ComponentClass; + ignoreScrollBehavior?: boolean; + } + interface Route extends React.ReactElement {} + interface RouteClass extends React.ComponentClass {} - var DefaultRoute: DefaultRouteClass; - var NotFoundRoute: NotFoundRouteClass; - var Redirect: RedirectClass; - var Route: RouteClass; + var DefaultRoute: DefaultRouteClass; + var NotFoundRoute: NotFoundRouteClass; + var Redirect: RedirectClass; + var Route: RouteClass; - interface CreateRouteOptions { - name?: string; - path?: string; - ignoreScrollBehavior?: boolean; - isDefault?: boolean; - isNotFound?: boolean; - onEnter?: (transition: Transition, params: {}, query: {}, callback: Function) => void; - onLeave?: (transition: Transition, wtf: any, callback: Function) => void; - handler?: Function; - parentRoute?: Route; - } + interface CreateRouteOptions { + name?: string; + path?: string; + ignoreScrollBehavior?: boolean; + isDefault?: boolean; + isNotFound?: boolean; + onEnter?: (transition: Transition, params: {}, query: {}, callback: Function) => void; + onLeave?: (transition: Transition, wtf: any, callback: Function) => void; + handler?: Function; + parentRoute?: Route; + } - type CreateRouteCallback = (route: Route) => void; + type CreateRouteCallback = (route: Route) => void; - function createRoute(callback: CreateRouteCallback): Route; - function createRoute(options: CreateRouteOptions | string, callback: CreateRouteCallback): Route; - function createDefaultRoute(options?: CreateRouteOptions | string): Route; - function createNotFoundRoute(options?: CreateRouteOptions | string): Route; + function createRoute(callback: CreateRouteCallback): Route; + function createRoute(options: CreateRouteOptions | string, callback: CreateRouteCallback): Route; + function createDefaultRoute(options?: CreateRouteOptions | string): Route; + function createNotFoundRoute(options?: CreateRouteOptions | string): Route; - interface CreateRedirectOptions extends CreateRouteOptions { - path?: string; - from?: string; - to: string; - params?: {}; - query?: {}; - } - function createRedirect(options: CreateRedirectOptions): Redirect; - function createRoutesFromReactChildren(children: Route): Route[]; + interface CreateRedirectOptions extends CreateRouteOptions { + path?: string; + from?: string; + to: string; + params?: {}; + query?: {}; + } + function createRedirect(options: CreateRedirectOptions): Redirect; + function createRoutesFromReactChildren(children: Route): Route[]; - // - // Components - // ---------------------------------------------------------------------- - // Link - interface LinkProp { - activeClassName?: string; - activeStyle?: {}; - to: string; - params?: {}; - query?: {}; - onClick?: Function; - } - interface Link extends React.ReactElement, Navigation, State { - handleClick(event: any): void; - getHref(): string; - getClassName(): string; - getActiveState(): boolean; - } - interface LinkClass extends React.ComponentClass {} + // + // Components + // ---------------------------------------------------------------------- + // Link + interface LinkProp { + activeClassName?: string; + activeStyle?: {}; + to: string; + params?: {}; + query?: {}; + onClick?: Function; + } + interface Link extends React.ReactElement, Navigation, State { + handleClick(event: any): void; + getHref(): string; + getClassName(): string; + getActiveState(): boolean; + } + interface LinkClass extends React.ComponentClass {} - // RouteHandler - interface RouteHandlerProp { } - interface RouteHandlerChildContext { - routeDepth: number; - } - interface RouteHandler extends React.ReactElement { - getChildContext(): RouteHandlerChildContext; - getRouteDepth(): number; - createChildRouteHandler(props: {}): RouteHandler; - } - interface RouteHandlerClass extends React.ComponentClass {} + // RouteHandler + interface RouteHandlerProp { } + interface RouteHandlerChildContext { + routeDepth: number; + } + interface RouteHandler extends React.ReactElement { + getChildContext(): RouteHandlerChildContext; + getRouteDepth(): number; + createChildRouteHandler(props: {}): RouteHandler; + } + interface RouteHandlerClass extends React.ComponentClass {} - var Link: LinkClass; - var RouteHandler: RouteHandlerClass; + var Link: LinkClass; + var RouteHandler: RouteHandlerClass; - // - // Top-Level - // ---------------------------------------------------------------------- - interface Router extends React.ReactElement { - run(callback: RouterRunCallback): void; - } + // + // Top-Level + // ---------------------------------------------------------------------- + interface Router extends React.ReactElement { + run(callback: RouterRunCallback): void; + } - interface RouterState { - path: string; - action: string; - pathname: string; - params: {}; - query: {}; - routes: Route[]; - } + interface RouterState { + path: string; + action: string; + pathname: string; + params: {}; + query: {}; + routes: Route[]; + } - interface RouterCreateOption { - routes: Route; - location?: LocationBase; - scrollBehavior?: ScrollBehaviorBase; - onError?: (error: any) => void; - onAbort?: (error: any) => void; - } + interface RouterCreateOption { + routes: Route; + location?: LocationBase; + scrollBehavior?: ScrollBehaviorBase; + onError?: (error: any) => void; + onAbort?: (error: any) => void; + } - type RouterRunCallback = (Handler: RouteClass, state: RouterState) => void; + type RouterRunCallback = (Handler: RouteClass, state: RouterState) => void; - function create(options: RouterCreateOption): Router; - function run(routes: Route, callback: RouterRunCallback): Router; - function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + function create(options: RouterCreateOption): Router; + function run(routes: Route, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; - // - // Location - // ---------------------------------------------------------------------- - interface LocationBase { - getCurrentPath(): void; - toString(): string; - } - interface Location extends LocationBase { - push(path: string): void; - replace(path: string): void; - pop(): void; - } + // + // Location + // ---------------------------------------------------------------------- + interface LocationBase { + getCurrentPath(): void; + toString(): string; + } + interface Location extends LocationBase { + push(path: string): void; + replace(path: string): void; + pop(): void; + } - interface LocationListener { - addChangeListener(listener: Function): void; - removeChangeListener(listener: Function): void; - } + interface LocationListener { + addChangeListener(listener: Function): void; + removeChangeListener(listener: Function): void; + } - interface HashLocation extends Location, LocationListener { } - interface HistoryLocation extends Location, LocationListener { } - interface RefreshLocation extends Location { } - interface StaticLocation extends LocationBase { } - interface TestLocation extends Location, LocationListener { } + interface HashLocation extends Location, LocationListener { } + interface HistoryLocation extends Location, LocationListener { } + interface RefreshLocation extends Location { } + interface StaticLocation extends LocationBase { } + interface TestLocation extends Location, LocationListener { } - var HashLocation: HashLocation; - var HistoryLocation: HistoryLocation; - var RefreshLocation: RefreshLocation; - var StaticLocation: StaticLocation; - var TestLocation: TestLocation; + var HashLocation: HashLocation; + var HistoryLocation: HistoryLocation; + var RefreshLocation: RefreshLocation; + var StaticLocation: StaticLocation; + var TestLocation: TestLocation; - // - // Behavior - // ---------------------------------------------------------------------- - interface ScrollBehaviorBase { - updateScrollPosition(position: { x: number; y: number; }, actionType: string): void; - } - interface ImitateBrowserBehavior extends ScrollBehaviorBase { } - interface ScrollToTopBehavior extends ScrollBehaviorBase { } + // + // 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; + var ImitateBrowserBehavior: ImitateBrowserBehavior; + var ScrollToTopBehavior: ScrollToTopBehavior; - // - // 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; - } + // + // 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 State { - getPath(): string; - getRoutes(): Route[]; - getPathname(): string; - getParams(): {}; - getQuery(): {}; - isActive(to: string, params?: {}, query?: {}): boolean; - } + interface State { + getPath(): string; + getRoutes(): Route[]; + getPathname(): string; + getParams(): {}; + getQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } - var Navigation: Navigation; - var State: State; + var Navigation: Navigation; + var State: State; - // - // History - // ---------------------------------------------------------------------- - interface History { - back(): void; - length: number; - } - var History: History; + // + // History + // ---------------------------------------------------------------------- + interface History { + back(): void; + length: number; + } + var History: History; - // - // Context - // ---------------------------------------------------------------------- - interface Context { - 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; + // + // Context + // ---------------------------------------------------------------------- + interface Context { + 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; - getCurrentPath(): string; - getCurrentRoutes(): Route[]; - getCurrentPathname(): string; - getCurrentParams(): {}; - getCurrentQuery(): {}; - isActive(to: string, params?: {}, query?: {}): boolean; - } + getCurrentPath(): string; + getCurrentRoutes(): Route[]; + getCurrentPathname(): string; + getCurrentParams(): {}; + getCurrentQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } } From 2d6ddd55ba09893b9aef85bb07086384b511eba1 Mon Sep 17 00:00:00 2001 From: Yuichi Murata Date: Sun, 12 Jul 2015 21:58:24 +0900 Subject: [PATCH 073/416] Move the type definitions for ReactRouter 0.12.x to the legacy directory --- react-router/legacy/react-router-0.12-test.ts | 346 ++++++++++++++++++ react-router/legacy/react-router-0.12.d.ts | 278 ++++++++++++++ 2 files changed, 624 insertions(+) create mode 100644 react-router/legacy/react-router-0.12-test.ts create mode 100644 react-router/legacy/react-router-0.12.d.ts diff --git a/react-router/legacy/react-router-0.12-test.ts b/react-router/legacy/react-router-0.12-test.ts new file mode 100644 index 000000000..d0d122bd4 --- /dev/null +++ b/react-router/legacy/react-router-0.12-test.ts @@ -0,0 +1,346 @@ +/// +"use strict"; + +import React = require('react'); +import Router = require('react-router'); + +// 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 new file mode 100644 index 000000000..a38e55822 --- /dev/null +++ b/react-router/legacy/react-router-0.12.d.ts @@ -0,0 +1,278 @@ +// 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' { + import Export = ReactRouter; + export = Export; +} + +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; + } +} From 896b1b56d2ab78fc617601b5e662e3b62e6b638b Mon Sep 17 00:00:00 2001 From: Yuichi Murata Date: Sun, 12 Jul 2015 22:41:49 +0900 Subject: [PATCH 074/416] Fix issues of react-router occurring on tsc 1.4.1 --- .../legacy/react-router-0.12-test.d.ts | 6 ++ react-router/legacy/react-router-0.12-test.ts | 5 +- react-router/legacy/react-router-0.12.d.ts | 3 +- react-router/react-router-test.ts | 29 +++++++ react-router/react-router.d.ts | 86 ++++++++++++++++++- 5 files changed, 121 insertions(+), 8 deletions(-) create mode 100644 react-router/legacy/react-router-0.12-test.d.ts diff --git a/react-router/legacy/react-router-0.12-test.d.ts b/react-router/legacy/react-router-0.12-test.d.ts new file mode 100644 index 000000000..bf6e2e272 --- /dev/null +++ b/react-router/legacy/react-router-0.12-test.d.ts @@ -0,0 +1,6 @@ +/// + +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 index d0d122bd4..e896c80f7 100644 --- a/react-router/legacy/react-router-0.12-test.ts +++ b/react-router/legacy/react-router-0.12-test.ts @@ -1,8 +1,9 @@ +/// /// "use strict"; -import React = require('react'); -import Router = require('react-router'); +import React = require('react-0.12'); +import Router = ReactRouter; // Mixin class NavigationTest { diff --git a/react-router/legacy/react-router-0.12.d.ts b/react-router/legacy/react-router-0.12.d.ts index a38e55822..79763db11 100644 --- a/react-router/legacy/react-router-0.12.d.ts +++ b/react-router/legacy/react-router-0.12.d.ts @@ -227,8 +227,7 @@ declare module ReactRouter { } declare module 'react-router' { - import Export = ReactRouter; - export = Export; + export = ReactRouter; } declare module React { diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index 85180cf9e..62180a258 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -2,6 +2,7 @@ "use strict"; import React = require('react'); +import ReactAddons = require('react/addons'); import Router = require('react-router'); // Mixin @@ -128,6 +129,9 @@ class DefaultRouteTest { var Handler: React.ComponentClass; React.createElement(Router.DefaultRoute, null); React.createElement(Router.DefaultRoute, {name: 'name', handler: Handler}); + + ReactAddons.createElement(Router.DefaultRoute, null); + ReactAddons.createElement(Router.DefaultRoute, {name: 'name', handler: Handler}); } } @@ -165,6 +169,16 @@ class LinkTest { query: {}, onClick: () => console.log(1) }); + + ReactAddons.createElement(Router.Link, null); + ReactAddons.createElement(Router.Link, {to: 'home'}); + ReactAddons.createElement(Router.Link, { + activeClassName: 'name', + to: 'home', + params: {}, + query: {}, + onClick: () => console.log(1) + }); } } @@ -181,6 +195,10 @@ class NotFoundRouteTest { React.createElement(Router.NotFoundRoute, null); React.createElement(Router.NotFoundRoute, {handler: Handler}); React.createElement(Router.NotFoundRoute, {handler: Handler, name: "home"}); + + ReactAddons.createElement(Router.NotFoundRoute, null); + ReactAddons.createElement(Router.NotFoundRoute, {handler: Handler}); + ReactAddons.createElement(Router.NotFoundRoute, {handler: Handler, name: "home"}); } } @@ -197,6 +215,10 @@ class RedirectTest { React.createElement(Router.Redirect, null); React.createElement(Router.Redirect, {}); React.createElement(Router.Redirect, {path: 'a', from: 'a', to: 'b'}); + + ReactAddons.createElement(Router.Redirect, null); + ReactAddons.createElement(Router.Redirect, {}); + ReactAddons.createElement(Router.Redirect, {path: 'a', from: 'a', to: 'b'}); } } @@ -215,6 +237,10 @@ class RouteTest { React.createElement(Router.Route, null); React.createElement(Router.Route, {}); React.createElement(Router.Route, {name: "home", path: "/", handler: Handler, ignoreScrollBehavior: true}); + + ReactAddons.createElement(Router.Route, null); + ReactAddons.createElement(Router.Route, {}); + ReactAddons.createElement(Router.Route, {name: "home", path: "/", handler: Handler, ignoreScrollBehavior: true}); } } @@ -224,6 +250,9 @@ class RouteHandlerTest { createElement() { React.createElement(Router.RouteHandler, null); React.createElement(Router.RouteHandler, {}); + + ReactAddons.createElement(Router.RouteHandler, null); + ReactAddons.createElement(Router.RouteHandler, {}); } } diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index a54805815..9d0f63b96 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -4,11 +4,9 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// -declare module "react-router" { - - import React = require("react"); - +declare module ReactRouter { // // Transition // ---------------------------------------------------------------------- @@ -273,3 +271,83 @@ declare module "react-router" { isActive(to: string, params?: {}, query?: {}): boolean; } } + +declare module "react-router" { + export = ReactRouter; +} + +declare module React { + // for DefaultRoute + function createElement( + type: ReactRouter.DefaultRouteClass, + props: ReactRouter.DefaultRouteProp, + ...children: React.ReactNode[]): ReactRouter.DefaultRoute; + + // for Link + function createElement( + type: ReactRouter.LinkClass, + props: ReactRouter.LinkProp, + ...children: React.ReactNode[]): ReactRouter.Link; + + // for NotFoundRoute + function createElement( + type: ReactRouter.NotFoundRouteClass, + props: ReactRouter.NotFoundRouteProp, + ...children: React.ReactNode[]): ReactRouter.NotFoundRoute; + + // for Redirect + function createElement( + type: ReactRouter.RedirectClass, + props: ReactRouter.RedirectProp, + ...children: React.ReactNode[]): ReactRouter.Redirect; + + // for Route + function createElement( + type: ReactRouter.RouteClass, + props: ReactRouter.RouteProp, + ...children: React.ReactNode[]): ReactRouter.Route; + + // for RouteHandler + function createElement( + type: ReactRouter.RouteHandlerClass, + props: ReactRouter.RouteHandlerProp, + ...children: React.ReactNode[]): ReactRouter.RouteHandler; +} + +declare module "react/addons" { + // for DefaultRoute + function createElement( + type: ReactRouter.DefaultRouteClass, + props: ReactRouter.DefaultRouteProp, + ...children: React.ReactNode[]): ReactRouter.DefaultRoute; + + // for Link + function createElement( + type: ReactRouter.LinkClass, + props: ReactRouter.LinkProp, + ...children: React.ReactNode[]): ReactRouter.Link; + + // for NotFoundRoute + function createElement( + type: ReactRouter.NotFoundRouteClass, + props: ReactRouter.NotFoundRouteProp, + ...children: React.ReactNode[]): ReactRouter.NotFoundRoute; + + // for Redirect + function createElement( + type: ReactRouter.RedirectClass, + props: ReactRouter.RedirectProp, + ...children: React.ReactNode[]): ReactRouter.Redirect; + + // for Route + function createElement( + type: ReactRouter.RouteClass, + props: ReactRouter.RouteProp, + ...children: React.ReactNode[]): ReactRouter.Route; + + // for RouteHandler + function createElement( + type: ReactRouter.RouteHandlerClass, + props: ReactRouter.RouteHandlerProp, + ...children: React.ReactNode[]): ReactRouter.RouteHandler; +} From 442dbd53b5c3732d77862438bdeba14f0b32bd5b Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Sun, 12 Jul 2015 07:49:00 -0700 Subject: [PATCH 075/416] Initial definition push. --- angular-formly/angular-formly-test.ts | 34 ++ angular-formly/angular-formly.d.ts | 445 ++++++++++++++++++++++++++ 2 files changed, 479 insertions(+) create mode 100644 angular-formly/angular-formly-test.ts create mode 100644 angular-formly/angular-formly.d.ts diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts new file mode 100644 index 000000000..1aae390a5 --- /dev/null +++ b/angular-formly/angular-formly-test.ts @@ -0,0 +1,34 @@ +/// + +var app = angular.module('app', ['formly']); + +class AppController { + fields: AngularFormly.IFieldConfigurationObject[]; + constructor($scope: ng.IScope) { + var vm = this; + vm.fields = [ + { + field: 'label', + type: 'input', + templateOptions: { + maxlength: 8, + minlength: 3 + } + }, + { + field: 'project', + type: 'input', + defaultValue: 'Project 1', + templateOptions: { + placeholder: 'Enter a project name...' + } + }, + { + template: () => 'hello' + } + ] + } +} + +app.controller("AppController", AppController); + diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts new file mode 100644 index 000000000..d0b336bfd --- /dev/null +++ b/angular-formly/angular-formly.d.ts @@ -0,0 +1,445 @@ +// Type definitions for angular-formly 6.17.0 +// Project: https://github.com/formly-js/angular-formly +// Definitions by: Scott Hatcher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'AngularFormly' { + export = AngularFormly; +} + +declare module AngularFormly { + + + /** + * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages + */ + interface IExpresssionFunction { + ($viewValue, $modelValue, scope): any; + } + + + /** + * This is part of the built-in formlyConfig templateManipulator called ngModelAttrsTemplateManipulator. + * This allows you to keep your templates very small and add custom behavior on at the type or field level. + * + * see http://docs.angular-formly.com/docs/ngmodelattrs + */ + interface INGModelAttrs { + [key: string]: { + attribute?: string; + expresssion?: string; + value?: string; + } + } + + + interface ITemplateManipulator { + (template, options, scope): string; + } + + + /** + * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator + */ + interface ITemplateOptions { + + // both attribute or regular attribute + disabled?: boolean | string; + maxlength?: number | string; + minlength?: number | string; + pattern?: string; + required?: boolean | string; + + //attribute only + max?: number; + min?: number; + placeholder?: number | string; + tabindex?: number; + type?: string; + + //expression types + onBlur?: string; + onChange?: string; + onClick?: string; + onFocus?: string; + onKeydown?: string; + onKeypress?: string; + onKeyup?: string; + + [key: string]: any; + + } + + + /** + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + interface IValidator { + expression?: string | { (viewValue, modelValue): boolean }; + } + + + /** + * An object which has at least two properties called expression and listener. The watch.expression + * is added to the formly-form directive's scope (to allow it to run even when hide is true). You + * can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to + * $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + interface IWatcher { + expression?: string | { (field, scope): boolean }; + listener: (field, newValue, oldValue, scope, stopWatching) => void; + type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup + } + + + // see http://docs.angular-formly.com/docs/field-configuration-object + interface IFieldConfigurationObject { + + + /** + * The type of field to be rendered. This is the recommended method + * for defining fields. Types must be pre-defined using formlyConfig. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + */ + type?: string; + + + /** + * Can be set instead of type or templateUrl to use a custom html + * template form field. Recommended to be used with one-liners mostly + * (like a directive), or if you're using webpack with the ability to require templates :-) + * + * If a function is passed, it is invoked with the field configuration object and can return + * either a string for the template or a promise that resolves to a string. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function + */ + template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function + */ + templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#key-string + */ + key?: string; + + + /** + * Use defaultValue to initialize it the model. If this is provided and the value of the + * model at compile-time is undefined, then the value of the model will be assigned to defaultValue. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any + */ + defaultValue?: any; + + + /** + * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use + * hideExpression. See below. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean + */ + hide?: boolean + + + /** + * This is similar to expressionProperties with a slight difference. You should (hopefully) never + * notice the difference with the most common use case. This is available due to limitations with + * expressionProperties and ng-if not working together very nicely. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function + */ + hideExpression?: string | IExpresssionFunction; + + + /** + * By default, the model passed to the formly-field directive is the same as the model passed to the + * formly-form. However, if the field has a model specified, then it is used for that field (and that + * field only). In addition, a deep watch is added to the formly-field directive's scope to run the + * expressionProperties when the specified model changes. + * + * Note, the formly-form directive will allow you to specify a string which is an (almost) formly + * expression which allows you to define the model as relative to the scope of the form. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string + */ + model?: Object | string; + + + /** + * An object where the key is a property to be set on the main field config and the value is an + * expression used to assign that property. The value is a formly expressions. The returned value is + * wrapped in $q.when so you can return a promise from your function :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + */ + expressionProperties?: { + [key: string]: string | IExpresssionFunction; + } + + + /** + * You can specify your own class that will be applied to the formly-field directive (or ng-form of + * a fieldGroup). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string + */ + className?: string; + + + /** + * This allows you to specify the id of your field (which will be used for its name as well unless + * a name is provided). Note, you can also override the id generation code using the formlyConfig + * extra called getFieldId. + * + * AVOID THIS + * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's + * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need + * to concern yourself with making sure that this is unique. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#id-string + */ + id?: string; + + + /** + * If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting + * the form to a server using techniques of yester-year. + * + * AVOID THIS + * If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly + * provides is the fact that you don't need to concern yourself with stuff like this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#name-string + */ + name?: string; + + + /** + * This is reserved for the developer. You have our guarantee to be able to use this and not worry about + * future versions of formly overriding your usage and preventing you from upgrading :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#data-object + */ + data?: any; + + + /** + * This is reserved for the templates. Any template-specific options go in here. Look at your specific + * template implementation to know the options required for this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object + */ + templateOptions?: ITemplateOptions; + + + /** + * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a + * type configuration if you want it to apply to all fields of a certain type). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions + */ + templateManipulator?: { + [key: string]: ITemplateManipulator[]; + } + + + /** + * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If + * given an array, the formly field template will be wrapped by the first wrapper, then the second, then + * the third, etc. You can also specify these as part of a type (which is the recommended approach). + * Specifying this property will override the wrappers for the type for this field. + * + * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings + */ + wrapper?: string | string[]; + + + //TODO:Scott Figure out what this really does. + /** + * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element + * of field templates. You will likely not use this often. This object is a little complex, but extremely + * powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object + */ + ngModelAttrs?: any; + + + /** + * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the + * field, and anything else you have in your injector. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f + */ + controller?: string | { ($scope: ng.IScope, ...args): void }; + + + /** + * This allows you to specify a link function. It is invoked after your template has finished compiling. + * You are passed the normal arguments for a normal link function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function + */ + link?: ng.IDirectiveLinkFn; + + + /** + * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority + * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and + * hence will override any duplicates of those properties as well. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings + */ + optionsTypes?: string | string[]; + + + //TODO:Scott Still need to define + /** + * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see + * below) will add this attribute to your ng-model element automatically if this property exists. Note, + * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model + * to options.value which is a getterSetter that formly adds to field options. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions + */ + modelOptions?: any; + + + /** + * Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful + * for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal + * line for example). Defaults to undefined. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean + */ + noFormControl?: boolean; + + + /** + * An object which has at least two properties called expression and listener. The watch.expression is added + * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type + * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want + * it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + watcher?: IWatcher | IWatcher[]; + + + //TODO:Scott Look at defining validators as an Object to see if additional interface needs to be created + /** + * An object where the keys are the name of the validator and the values are Formly Expressions; + * + * Async Validation + * All function validators can return true/false/Promise. A validator passes if it returns true or a promise + * that is resolved. A validator fails if it returns false or a promise that is rejected. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + validators?: { + [key: string]: IValidator | string; + } + + + /** + * An object with a few useful properties mostly handy when used in combination with ng-messages + */ + validation?: { + + + /** + * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages + * like in this example. + */ + messages?: { + [key: string]: IExpresssionFunction; + } + + + /** + * A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible + * to be set to true when there are $errors. This is useful when you're trying to call the user's attention to + * some fields for some reason. + */ + show?: boolean; + + + /** + * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because + * you generally only want to show error messages when the user has interacted with a specific field, this value + * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference + * for pre-angular 1.3 because it doesn't have touched support). + */ + errorExistsAndShouldBeVisible?: boolean; + + } + + /** + * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true + * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, + * it will automagically change your field's ng-model attribute to use options.value. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function + */ + value?(): any; //Getter + value?(val): void; //Setter + + + //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) + + + /** + * This is the NgModelController for the field. It provides you with awesome stuff like $errors :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller + */ + formControl?: ng.IFormController; + + + /** + * Will reset the field's model and the field control to the last initialValue. This is used by the + * formly-form's options.resetModel function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function + */ + resetModel?: () => void; + + + /** + * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. + * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function + */ + updateInitialValue?: () => void; + + + /** + * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. + * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the + * way it works will result in a major version change, so you can rely on its api. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function + */ + runExpressions?: () => void; + + } + +} \ No newline at end of file From 10988482fb8021533084155bfb38dce2068f0986 Mon Sep 17 00:00:00 2001 From: Christopher Haws Date: Sun, 12 Jul 2015 12:18:05 -0700 Subject: [PATCH 076/416] Added declaration file and tests for gulp-uglify --- gulp-uglify/gulp-uglify-tests.ts | 24 ++++++ gulp-uglify/gulp-uglify.d.ts | 128 +++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 gulp-uglify/gulp-uglify-tests.ts create mode 100644 gulp-uglify/gulp-uglify.d.ts diff --git a/gulp-uglify/gulp-uglify-tests.ts b/gulp-uglify/gulp-uglify-tests.ts new file mode 100644 index 000000000..e4f1f0d8a --- /dev/null +++ b/gulp-uglify/gulp-uglify-tests.ts @@ -0,0 +1,24 @@ +/// +/// +import gulp = require("gulp"); +import uglify = require("gulp-uglify"); + + +gulp.task('compress', function() { + var tsResult = gulp.src('lib/*.ts') + .pipe(uglify()) + .pipe(gulp.dest('dist')); +}); + +gulp.task('compress2', function() { + var tsResult = gulp.src('lib/*.ts') + .pipe(uglify({ + mangle: false, + preserverComments: "some", + compress: false, + output: { + max_line_len: 300 + } + })) + .pipe(gulp.dest('dist')); +}); \ No newline at end of file diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts new file mode 100644 index 000000000..28ad91b93 --- /dev/null +++ b/gulp-uglify/gulp-uglify.d.ts @@ -0,0 +1,128 @@ +// Type definitions for gulp-uglify +// Project: https://github.com/terinjokes/gulp-uglify +// Definitions by: Christopher Haws +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-uglify" { + function GulpUglify(options?: IGulpUglifyOptions): NodeJS.ReadWriteStream; + + interface IGulpUglifyOptions { + /** + * Pass false to skip mangling names. + */ + mangle?: boolean; + + /** + * Pass if you wish to specify additional output options. The defaults are optimized for best compression. + */ + output?: IOutputOptions; + + /** + * Pass an object to specify custom compressor options. Pass false to skip compression completely. + */ + compress?: boolean; + + /** + * A convenience option for options.output.comments. Defaults to preserving no comments. + * all - Preserve all comments in code blocks + * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) + * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. + */ + preserverComments?: string|((node, comment) => boolean); + } + + interface IOutputOptions { + /** + * Start indentation on every line (only when `beautify`) + */ + indent_start?: number; + + /** + * Indentation level (only when `beautify`) + */ + indent_level?: number; + + /** + * Quote all keys in object literals? + */ + quote_keys?: boolean; + + /** + * Add a space after colon signs? + */ + space_colon?: boolean; + + /** + * Output ASCII-safe? (encodes Unicode characters as ASCII) + */ + ascii_only?: boolean; + + /** + * Escape " Date: Sun, 12 Jul 2015 12:30:48 -0700 Subject: [PATCH 077/416] Fixed an issue with implicit any's --- gulp-uglify/gulp-uglify.d.ts | 49 +++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts index 28ad91b93..840b5110b 100644 --- a/gulp-uglify/gulp-uglify.d.ts +++ b/gulp-uglify/gulp-uglify.d.ts @@ -30,7 +30,7 @@ declare module "gulp-uglify" { * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. */ - preserverComments?: string|((node, comment) => boolean); + preserverComments?: string|((node: any, comment: ITokenizer) => boolean); } interface IOutputOptions { @@ -123,6 +123,53 @@ declare module "gulp-uglify" { */ orig? :Object|JSON; } + + interface ITokenizer { + /** + * The type of this token. + * Can be "num", "string", "regexp", "operator", "punc", "atom", "name", "keyword", "comment1" or "comment2". + * "comment1" and "comment2" are for single-line, respectively multi-line comments. + */ + type: string; + + /** + * The name of the file where this token originated from. Useful when compressing multiple files at once to generate the proper source map. + */ + file: string; + + /** + * The "value" of the token. + * That's additional information and depends on the token type: "num", "string" and "regexp" tokens you get their literal value. + * - For "operator" you get the operator. + * - For "punc" it's the punctuation sign (parens, comma, semicolon etc). + * - For "atom", "name" and "keyword" it's the name of the identifier + * - For comments it's the body of the comment (excluding the initial "//" and "/*". + */ + value: string; + + /** + * The line number of this token in the original code. + * 1-based index. + */ + line: number; + + /** + * The column number of this token in the original code. + * 0-based index. + */ + col: number; + + /** + * Short for "newline before", it's a boolean that tells us whether there was a newline before this node in the original source. It helps for automatic semicolon insertion. + * For multi-line comments in particular this will be set to true if there either was a newline before this comment, or * * if this comment contains a newline. + */ + nlb: boolean; + + /** + * This doesn't apply for comment tokens, but for all other token types it will be an array of comment tokens that were found before. + */ + comments_before: string[]; + } export = GulpUglify; } \ No newline at end of file From cfb23d91bf0aef4eb63a7f42622f40b076060d40 Mon Sep 17 00:00:00 2001 From: Kern Handa Date: Sun, 12 Jul 2015 20:27:38 -0700 Subject: [PATCH 078/416] Add typings for seedrandom 2.4.2 --- seedrandom/seedrandom-tests.ts | 25 ++++++++++++++++++++ seedrandom/seedrandom.d.ts | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 seedrandom/seedrandom-tests.ts create mode 100644 seedrandom/seedrandom.d.ts diff --git a/seedrandom/seedrandom-tests.ts b/seedrandom/seedrandom-tests.ts new file mode 100644 index 000000000..1f913a406 --- /dev/null +++ b/seedrandom/seedrandom-tests.ts @@ -0,0 +1,25 @@ +import seedrandom = require("seedrandom"); + +var rng = seedrandom("hello."); +var n = rng(); + +seedrandom("hello.", {global: true}); +n = Math.random(); + +rng = seedrandom(); +n = rng(); + +rng = seedrandom('added entropy.', { entropy: true }); +n = rng(); + +var rng2 = seedrandom.xor4096('hello.'); +n = rng2(); + +n = rng.quick(); +n = rng.int32(); +n = rng.double(); + +var saveable = seedrandom("secret-seed", {state: true}); +for (var j = 0; j < 1e5; ++j) saveable(); +var saved = saveable.state(); +var replica = seedrandom("", {state: saved}); diff --git a/seedrandom/seedrandom.d.ts b/seedrandom/seedrandom.d.ts new file mode 100644 index 000000000..6b779c606 --- /dev/null +++ b/seedrandom/seedrandom.d.ts @@ -0,0 +1,43 @@ +// Type definitions for seedrandom 2.4.2 +// Project: https://github.com/davidbau/seedrandom +// Definitions by: Kern Handa +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare type seedrandomStateType = boolean | (() => prng); + +interface prng { + new(seed?: string, options?: seedRandomOptions, callback?: any): prng; + (): number; + quick(): number; + int32(): number; + double(): number; + state(): () => prng; +} + +interface seedrandom_prng { + (seed?: string, options?: seedRandomOptions, callback?: any): prng; + alea: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xor128: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + tychei: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xorwow: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xor4096: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + xorshift7: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + quick: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; +} + +interface seedrandomCallback { + (prng?: prng, shortseed?: string, global?: boolean, state?: seedrandomStateType): prng; +} + +interface seedRandomOptions { + entropy?: boolean; + 'global'?: boolean; + state?: seedrandomStateType; + pass?: seedrandomCallback; +} + +declare var seedrandom: seedrandom_prng; + +declare module "seedrandom" { + export = seedrandom; +} From ab710e1ba02ed0b321a459177a7a1ea1709969e5 Mon Sep 17 00:00:00 2001 From: Loc Nguyen Date: Mon, 13 Jul 2015 01:44:13 -0700 Subject: [PATCH 079/416] Fix typo in server connection object interface name. Changed ISeverConnectionOptions to IServerConnectionOptions and used the type in test file to prove it is working --- hapi/hapi-tests.ts | 6 +++--- hapi/hapi.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 11ad81d2d..ab58fd938 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -4,9 +4,9 @@ import Hapi = require("hapi"); // Create a server with a host and port var server = new Hapi.Server(); -server.connection({ +server.connection({ host: "localhost", - port: 8000, + port: 8000 }); // Add plugins @@ -24,7 +24,7 @@ plugin.register.attributes = { // optional options parameter server.register({}, function (err) {}); -// optional options.routes.vhost parameter +// optional options.routes.vhost parameter server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); //server.pack.register(plugin, (err: Object) => { diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 8d3da2620..9f16e558a 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -62,7 +62,7 @@ declare module "hapi" { } /** Any connections configuration server defaults can be included to override and customize the individual connection. */ - export interface ISeverConnectionOptions extends IConnectionConfigurationServerDefaults { + export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ host?: string; /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ @@ -1443,7 +1443,7 @@ declare module "hapi" { // server.connections.length === 2 var a = server.select('a'); // a.connections.length === 1*/ - connections: Array; + connections: Array; /** When the server contains exactly one connection, info is an object containing information about the sole connection. * When the server contains more than one connection, each server.connections array member provides its own connection.info. var server = new Hapi.Server(); @@ -1745,7 +1745,7 @@ declare module "hapi" { // server.connections.length === 2 // web.connections.length === 1 // admin.connections.length === 1 */ - connection(options: ISeverConnectionOptions): Server; + connection(options: IServerConnectionOptions): Server; /** server.decorate(type, property, method) Extends various framework interfaces with custom methods where: type - the interface being decorated. Supported types: From 98b7b8ef2c5d8f760da9e61674dbbb92d30d6f9a Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Mon, 13 Jul 2015 15:59:21 +0200 Subject: [PATCH 080/416] Added getRegion method to marionette.d.ts --- marionette/marionette.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 4a2bfac10..be684d9a8 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -1128,6 +1128,9 @@ declare module Marionette { * Add multiple regions as a {name: definition, name2: def2} object literal. */ addRegions(regions: any): any; + + /** Returns a region from the layout view */ + getRegion(name: string): Region; /** * Renders the view. From 42256bd2d1ed550d31081630c49ab7506f849597 Mon Sep 17 00:00:00 2001 From: afromogli Date: Mon, 13 Jul 2015 16:12:17 +0200 Subject: [PATCH 081/416] Fixed CI build errors in https://travis-ci.org/borisyankov/DefinitelyTyped/builds/70185499 --- globalize/globalize.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index f4ebd7697..43c126c2f 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -13,12 +13,16 @@ interface NumberFormatterOptions { useGrouping?: boolean; } +interface Cldr { + /* TODO: add typings */ +} + interface GlobalizeStatic { - load(jsonData: any); - locale(locale: string); + load(jsonData: any): void; + locale(locale: string): Cldr; numberFormatter(options?: NumberFormatterOptions): (value: number) => string; - formatNumber(value, options?: NumberFormatterOptions): string; + formatNumber(value:number, options?: NumberFormatterOptions): string; } declare var Globalize: GlobalizeStatic; From 700ec57d8b58c08827d2de0813417d77d7feb6f4 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 07:55:15 -0700 Subject: [PATCH 082/416] Allow custom bootstrap layout. --- angular-formly/angular-formly.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index d0b336bfd..0e2c7d920 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -440,6 +440,13 @@ declare module AngularFormly { */ runExpressions?: () => void; + + + ////////////////// BOOTSTRAP SPECIFIC /////////////////////// + fieldGroup?: IFieldConfigurationObject[]; + } + + } \ No newline at end of file From d48e140826129575610983b8e3e7c075c800393c Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 08:00:46 -0700 Subject: [PATCH 083/416] Added a few other field types to test file. --- angular-formly/angular-formly-test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts index 1aae390a5..4d4053823 100644 --- a/angular-formly/angular-formly-test.ts +++ b/angular-formly/angular-formly-test.ts @@ -15,6 +15,9 @@ class AppController { minlength: 3 } }, + { + template: '


' + }, { field: 'project', type: 'input', @@ -25,6 +28,24 @@ class AppController { }, { template: () => 'hello' + }, + { + type: 'input', + key: 'zip', + templateOptions: { + type: 'number', + label: 'Zip', + max: 99999, + min: 0, + pattern: '\\d{5}' + } + }, + { + type: 'checkbox', + key: 'happyUser', + templateOptions: { + label: 'Are you happy?' + } } ] } From 7f7ac2c2b115cff564dacf27225240e2478f954d Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 08:43:43 -0700 Subject: [PATCH 084/416] Remove implicit any's. --- angular-formly/angular-formly.d.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 0e2c7d920..807171d07 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -16,7 +16,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue, $modelValue, scope): any; + ($viewValue: any, $modelValue: any, scope: ng.IScope): any; } @@ -36,7 +36,7 @@ declare module AngularFormly { interface ITemplateManipulator { - (template, options, scope): string; + (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } @@ -77,7 +77,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object */ interface IValidator { - expression?: string | { (viewValue, modelValue): boolean }; + expression?: string | { (viewValue: any, modelValue: any): boolean }; } @@ -90,8 +90,9 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches */ interface IWatcher { - expression?: string | { (field, scope): boolean }; - listener: (field, newValue, oldValue, scope, stopWatching) => void; + deep?: boolean; //Defaults to false + expression?: string | { (field: string, scope: ng.IScope): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: ng.IScope, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -256,7 +257,8 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions */ templateManipulator?: { - [key: string]: ITemplateManipulator[]; + preWrapper: ITemplateManipulator[]; + postWrapper: ITemplateManipulator[]; } @@ -288,7 +290,7 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f */ - controller?: string | { ($scope: ng.IScope, ...args): void }; + controller?: string | { Function: void }; /** @@ -399,7 +401,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function */ value?(): any; //Getter - value?(val): void; //Setter + value?(val: any): void; //Setter //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) From 381072091d70da7a32ffa1d9a0f298dc3ca09cf9 Mon Sep 17 00:00:00 2001 From: Chris Wrench Date: Mon, 13 Jul 2015 17:25:26 +0100 Subject: [PATCH 085/416] Fix definition of `google.maps.InfoWindow.open()`. Fixes #4364. --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index b6091ef55..697a91071 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -572,7 +572,7 @@ declare module google.maps { * 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?: StreetViewPanorama, anchor?: MVCObject): void; + open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; setContent(content: string|Node): void; setOptions(options: InfoWindowOptions): void; setPosition(position: LatLng): void; From 4aa7366e014f44efd34d1b95e66a27cbe8acf661 Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Mon, 13 Jul 2015 13:09:50 -0400 Subject: [PATCH 086/416] UiGrid - Add enableRowSelection to gridOptions This property was missing --- ui-grid/ui-grid.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 19d0a2c7f..f27700e70 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -98,6 +98,7 @@ declare module uiGrid { enableHorizontalScrollbar?: boolean; enableMinHeightCheck?: boolean; enableRowHashing?: boolean; + enableRowSelection?: boolean; enableSorting?: boolean; enableVerticalScrollbar?: boolean; excessColumns?: number; From 31c2a4dc3f9bbb8060ca9d846c03af0aa1a0ac06 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Tue, 14 Jul 2015 00:09:21 +0300 Subject: [PATCH 087/416] Added tests for SharePoint.d.ts --- sharepoint/SharePoint-tests.ts | 2043 +++++++++++++++++++++++++++++++- 1 file changed, 2042 insertions(+), 1 deletion(-) diff --git a/sharepoint/SharePoint-tests.ts b/sharepoint/SharePoint-tests.ts index 83934008c..0e6b53e54 100644 --- a/sharepoint/SharePoint-tests.ts +++ b/sharepoint/SharePoint-tests.ts @@ -1,5 +1,11 @@ /// +/// +/// +/// + +//code from http://sptypescript.codeplex.com/ +//BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel:HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -522,4 +528,2039 @@ function deleteListItem(resultpanel: HTMLElement) { function errorHandler() { resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); } -} \ No newline at end of file +} + + + +/** Lightweight client-side rendering template overrides.*/ +module CSR { + + export interface UpdatedValueCallback { + (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; + } + + /** Creates new overrides. Call .register() at the end.*/ + export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + return new csr(listTemplateType, baseViewId) + .onPreRender(hookFormContext) + .onPostRender(fixCsrCustomLayout); + + function hookFormContext(ctx: IFormRenderContexWithHook) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + + for (var i = 0; i < ctx.ListSchema.Field.length; i++) { + var fieldSchemaInForm = ctx.ListSchema.Field[i]; + + if (!ctx.FormContextHook) { + ctx.FormContextHook = {} + + var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; + ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { + ctx.FormContextHook[fieldName].getValue = callback; + oldRegisterGetValueCallback(fieldName, callback); + }; + + var oldUpdateControlValue = ctx.FormContext.updateControlValue; + ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { + oldUpdateControlValue(fieldName, value); + + var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); + hookedContext.lastValue = value; + + var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; + for (var i = 0; i < updatedCallbacks.length; i++) { + updatedCallbacks[i](value, hookedContext.fieldSchema); + } + + } + } + ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; + } + } + } + + function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + return; + } + + if (ctx.ListSchema.Field.length > 1) { + var wpq = ctx.FormUniqueId; + var webpart = $get('WebPart' + wpq); + var forms = webpart.getElementsByClassName('ms-formtable'); + + if (forms.length > 0) { + var placeholder = $get(wpq + 'ClientFormTopContainer'); + var fragment = document.createDocumentFragment(); + for (var i = 0; i < placeholder.children.length; i++) { + fragment.appendChild(placeholder.children.item(i)); + } + + var form = forms.item(0); + form.parentNode.replaceChild(fragment, form); + } + + var old = ctx.CurrentItem; + ctx.CurrentItem = ctx.ListData.Items[0]; + var fields = ctx.ListSchema.Field; + for (var j = 0; j < fields.length; j++) { + var field = fields[j]; + var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; + var span = $get(pHolderId); + if (span) { + span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); + } + } + ctx.CurrentItem = old; + } + + } + + + } + + +//typescripttempltes.ts + declare var Strings:any; + export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName] + && contextWithHook.FormContextHook[fieldName].getValue) { + return contextWithHook.FormContextHook[fieldName].getValue(); + } + } + return null; + } + + export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName]) { + return contextWithHook.FormContextHook[fieldName].fieldSchema; + } + } + return null; + } + + export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); + var callbacks = f.updatedValueCallbacks; + if (callbacks.indexOf(callback) == -1) { + callbacks.push(callback); + if (f.lastValue) { + callback(f.lastValue, f.fieldSchema); + } + } + } + } + + } + + export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; + var index = callbacks.indexOf(callback); + if (index != -1) { + callbacks.splice(index, 1); + } + } + } + } + + export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { + var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; + //TODO: Handle different input types + return $get(id); + } + + export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { + var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; + ctx.FieldControlModes[field.Name] = mode; + var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); + return templates.Fields[field.Name]; + } + + + class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + + public Templates: SPClientTemplates.TemplateOverrides; + public OnPreRender: SPClientTemplates.RenderCallback[]; + public OnPostRender: SPClientTemplates.RenderCallback[]; + private IsRegistered: boolean; + + + constructor(public ListTemplateType?: number, public BaseViewID?: any) { + this.Templates = { Fields: {} }; + this.OnPreRender = [] ; + this.OnPostRender = []; + this.IsRegistered = false; + } + + /* tier 1 methods */ + view(template: any): ICSR { + this.Templates.View = template; + return this; + } + + item(template: any): ICSR { + this.Templates.Item = template; + return this; + } + + header(template: any): ICSR { + this.Templates.Header = template; + return this; + } + + body(template: any): ICSR { + this.Templates.Body = template; + return this; + } + + footer(template: any): ICSR { + this.Templates.Footer = template; + return this; + } + + fieldView(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].View = template; + return this; + } + + fieldDisplay(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].DisplayForm = template; + return this; + } + + fieldNew(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].NewForm = template; + return this; + } + + fieldEdit(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].EditForm = template; + return this; + } + + /* tier 2 methods */ + template(name: string, template: any): ICSR { + this.Templates[name] = template; + return this; + } + + fieldTemplate(fieldName: string, name: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName][name] = template; + return this; + } + + /* common */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPreRender.push(callbacks[i]); + } + return this; + } + + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPostRender.push(callbacks[i]); + } + return this; + } + + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + makeReadOnly(fieldName: string): ICSR { + return this + .onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema).ReadOnlyField = true; + (schema).ReadOnly = "TRUE"; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + if (ctxInView.inGridMode) { + //TODO: Disable editing in grid mode + + } + + } else { + var ctxInForm = ctx; + if (schema.Type != 'User' && schema.Type != 'UserMulti') { + + var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); + ctxInForm.Templates.Fields[fieldName] = template; + ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); + + } + } + + }) + .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type == 'User' || schema.Type == 'UserMulti') { + SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { + var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; + var retryCount = 10; + var callback = () => { + var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; + if (!pp) { + if (retryCount--) setTimeout(callback, 1); + } else { + pp.SetEnabledState(false); + pp.DeleteProcessedUser = function () { }; + } + }; + callback(); + }); + } + } + }); + } + + makeHidden(fieldName: string): ICSR { + return this.onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; + (schema).Hidden = true; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + + if (ctxInView.inGridMode) { + //TODO: Hide item in grid mode + } else { + ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); + } + + } else { + var ctxInForm = ctx; + + var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; + var placeholder = $get(pHolderId); + var current = placeholder; + while (current.tagName.toUpperCase() !== "TR") { + current = current.parentElement; + } + var row = current; + row.style.display = 'none'; + + } + + }); + } + + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + + + return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) + .fieldNew(fieldName, SPFieldCascadedLookup_Edit); + + + function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + + var parseRegex = /\{[^\}]+\}/g; + var dependencyExpressions: string[] = []; + var result: RegExpExecArray; + while ((result = parseRegex.exec(camlFilter))) { + dependencyExpressions.push(stripBraces(result[0])); + } + var dependencyValues: { [expr: string]: string } = {}; + + var _dropdownElt: HTMLSelectElement; + var _myData: SPClientTemplates.ClientFormContext; + + + if (rCtx == null) + return ''; + _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + + var _schema = _myData.fieldSchema; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); + + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; + var _noValueSelected = _selectedValue == 0; + var _optionsLoaded = false; + var pendingLoads = 0; + + if (_noValueSelected) + _valueStr = ''; + + _myData.registerInitCallback(_myData.fieldName, InitLookupControl); + + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_dropdownElt != null) + _dropdownElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); + _myData.updateControlValue(_myData.fieldName, _valueStr); + + return BuildLookupDropdownControl(); + + function InitLookupControl() { + _dropdownElt = document.getElementById(_dropdownId); + if (_dropdownElt != null) + AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); + + SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { + bindDependentControls(dependencyExpressions); + loadOptions(true); + }); + } + + + function BuildLookupDropdownControl() { + var result = ''; + result += '
'; + return result; + } + + + function OnLookupValueChanged() { + if (_optionsLoaded) { + if (_dropdownElt != null) { + _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + _selectedValue = parseInt(_dropdownElt.value, 10); + } + } + } + + function GetCurrentLookupValue() { + if (_dropdownElt == null) + return ''; + return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; + } + + function stripBraces(input: string): string { + return input.substring(1, input.length - 1); + } + + function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { + var isLookupValue = !!listId; + if (isLookupValue) { + var lookup = SPClientTemplates.Utility.ParseLookupValue(value); + if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + value = lookup.LookupValue; + expressionParts.shift(); + } else { + value = lookup.LookupId.toString(); + } + } + + if (expressionParts.length == 0) { + dependencyValues[expr] = value; + callback(); + } else { + var ctx = SP.ClientContext.get_current(); + var web = ctx.get_web(); + //TODO: Handle lookup to another web + var list = web.get_lists().getById(listId); + var item = list.getItemById(parseInt(value, 10)); + var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); + ctx.load(item); + ctx.load(field); + + ctx.executeQueryAsync((o, e) => { + var value = item.get_item(field.get_internalName()); + + if (field.get_typeAsString() == 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup); + var lookup = (value); + value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); + listId = (field).get_lookupList(); + } + + getDependencyValue(expr, value, listId, expressionParts, callback); + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + function bindDependentControls(dependencyExpressions: string[]) { + dependencyExpressions.forEach(expr => { + var exprParts = expr.split("."); + var field = exprParts.shift(); + + CSR.addUpdatedValueCallback(rCtx, field, + (v, s) => { + getDependencyValue(expr, v, + (s).LookupListId, + exprParts.slice(0), + loadOptions); + }); + + }); + } + + + function loadOptions(isFirstLoad?: boolean) { + _optionsLoaded = false; + pendingLoads++; + + var ctx = SP.ClientContext.get_current(); + //TODO: Handle lookup to another web + var web = ctx.get_web(); + var listId = _schema.LookupListId; + var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); + var query = new SP.CamlQuery(); + + var predicate = camlFilter.replace(parseRegex, (v, a) => { + var expr = stripBraces(v); + return dependencyValues[expr] ? dependencyValues[expr] : ''; + }); + + //TODO: Handle ShowField attribure + if (predicate.substr(0, 5) == '' + + predicate + + ' ' + + ''); + } + var results = list.getItems(query); + ctx.load(results); + + + ctx.executeQueryAsync((o, e) => { + var selected = false; + + while (_dropdownElt.options.length) { + _dropdownElt.options.remove(0); + } + + if (!_schema.Required) { + var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); + _dropdownElt.options.add(defaultOpt); + selected = _selectedValue == 0; + } + var isEmptyList = true; + + var enumerator = results.getEnumerator(); + while (enumerator.moveNext()) { + var c = enumerator.get_current(); + var id: number; + var text: string; + + if (!lookupField) { + id = c.get_id(); + text = c.get_item('Title'); + } else { + var value = c.get_item(lookupField); + id = value.get_lookupId(); + text = value.get_lookupValue(); + } + var isSelected = _selectedValue == id; + if (isSelected) { + selected = true; + } + var opt = new Option(text, id.toString(), isSelected, isSelected); + _dropdownElt.options.add(opt); + isEmptyList = false; + } + pendingLoads--; + _optionsLoaded = true; + if (!pendingLoads) { + if (isFirstLoad) { + if (_selectedValue == 0 && !selected) { + _dropdownElt.selectedIndex = 0; + OnLookupValueChanged(); + } + } else { + if (_selectedValue != 0 && !selected) { + _dropdownElt.selectedIndex = 0; + } + OnLookupValueChanged(); + } + } + + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + } + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + return this.fieldEdit(fieldName, koEditField_Edit) + .fieldNew(fieldName, koEditField_Edit); + + + function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; + + vm.renderingContext = rCtx; + + + if (dependencyFields) { + dependencyFields.forEach(dependencyField => { + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); + }); + } + + + if (!vm.value) { + vm.value = ko.observable(); + } + + vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); + _myData.registerGetValueCallback(fieldName, () => vm.value()); + + + _myData.registerInitCallback(fieldName, () => { + ko.applyBindings(vm, $get(elementId)); + }); + + return '
'+template+'
'; + } + } + + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + var dependentValues: { [field: string]: string } = {}; + + return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema); + sourceField.forEach((field) => { + CSR.addUpdatedValueCallback(ctx, field, v => { + dependentValues[field] = v; + targetControl.value = transform.apply(this, + sourceField.map(n => dependentValues[n] || '')); + + }); + }); + } + }); + } + + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + if (value || !ignoreNull) { + return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + ctx.ListData.Items[0][fieldName] = value; + }); + } else { + return this; + } + } + + + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + return this + .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) + .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); + + function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + var _autoFillControl: SPClientAutoFill; + var _textInputElt: HTMLInputElement; + var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; + var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_textInputElt != null) + _textInputElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); + _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); + + return buildAutoFillControl(); + + function initAutoFillControl() { + _textInputElt = document.getElementById(_textInputId); + + SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { + _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); + var callback = init({ + renderContext: rCtx, + fieldContext: _myData, + autofill: _autoFillControl, + control: _textInputElt, + }); + + //_autoFillControl.AutoFillMinTextLength = 2; + //_autoFillControl.VisibleItemCount = 15; + //_autoFillControl.AutoFillTimeout = 500; + }); + + } + //function OnPopulate(targetElement: HTMLInputElement) { + + //} + + //function OnLookupValueChanged() { + // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + //} + //function GetCurrentLookupValue() { + // return _valueStr; + //} + function buildAutoFillControl() { + var result: string[] = []; + result.push('
'); + result.push(''); + + result.push("
"); + result.push("
"); + + return result.join(""); + } + } + + + } + + seachLookup(fieldName: string): ICSR { + return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + var _myData = ctx.fieldContext; + var _schema = _myData.fieldSchema; + if (_myData.fieldSchema.Type != 'Lookup') { + return null; + } + + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); + var _noValueSelected = _selectedValue.LookupId == 0; + ctx.control.value = _selectedValue.LookupValue; + $addHandler(ctx.control, "blur", _ => { + if (ctx.control.value == '') { + _myData.fieldValue = ''; + _myData.updateControlValue(fieldName, _myData.fieldValue); + } + }); + + if (_noValueSelected) + _myData.fieldValue = ''; + + var _autoFillControl = ctx.autofill; + _autoFillControl.AutoFillMinTextLength = 2; + _autoFillControl.VisibleItemCount = 15; + _autoFillControl.AutoFillTimeout = 500; + + return () => { + var value = ctx.control.value; + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); + + SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { + var Search = Microsoft.SharePoint.Client.Search.Query; + var ctx = SP.ClientContext.get_current(); + var query = new Search.KeywordQuery(ctx); + query.set_rowLimit(_autoFillControl.VisibleItemCount); + query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); + var selectProps = query.get_selectProperties(); + selectProps.clear(); + //TODO: Handle ShowField attribute + selectProps.add('Title'); + selectProps.add('ListItemId'); + var executor = new Search.SearchExecutor(ctx); + var result = executor.executeQuery(query); + ctx.executeQueryAsync( + () => { + //TODO: Discover proper way to load collection + var tableCollection = new Search.ResultTableCollection(); + tableCollection.initPropertiesFromJson(result.get_value()); + + var relevantResults = tableCollection.get_item(0); + var rows = relevantResults.get_resultRows(); + + var items = []; + for (var i = 0; i < rows.length; i++) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + } + + items.push(AutoFillOptionBuilder.buildSeparatorItem()); + + if (relevantResults.get_totalRows() == 0) + items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); + else + items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); + + _autoFillControl.PopulateAutoFill(items, onSelectItem); + + }, + (sender, args) => { + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); + console.log(args.get_message()); + }); + }); + } + + function onSelectItem(targetInputId, item: ISPClientAutoFillData) { + var targetElement = ctx.control; + targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; + _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; + _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; + _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; + _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); + } + + }); + } + + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + return this.onPostRenderField(fieldName, + (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + + var control = CSR.getControl(schema); + if (control) { + var weburl = _spPageContextInfo.webServerRelativeUrl; + if (weburl[weburl.length - 1] == '/') { + weburl = weburl.substring(0, weburl.length - 1); + } + var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' + + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); + if (contentTypeId) { + newFormUrl += '&ContentTypeId=' + contentTypeId; + } + + var link = document.createElement('a'); + link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; + link.textContent = prompt; + if (control.nextElementSibling) { + control.parentElement.insertBefore(link, control.nextElementSibling); + } else { + control.parentElement.appendChild(link); + } + + if (showDialog) { + $addHandler(link, "click", (e: Sys.UI.DomEvent) => { + SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { + SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); + }); + e.stopPropagation(); + e.preventDefault(); + }); + } + } + }); + } + + register() { + if (!this.IsRegistered) { + SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); + this.IsRegistered = true; + } + } + } + + export class AutoFillOptionBuilder { + + static buildFooterItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.DisplayTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; + + return item; + } + + static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { + + var item = {}; + + item[SPClientAutoFill.KeyProperty] = id; + item[SPClientAutoFill.DisplayTextProperty] = displayText || title; + item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; + item[SPClientAutoFill.TitleTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; + + return item; + } + + static buildSeparatorItem(): ISPClientAutoFillData { + var item = {}; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; + return item; + } + + static buildLoadingItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; + item[SPClientAutoFill.DisplayTextProperty] = title; + return item; + } + + } + + /** Lightweight client-side rendering template overrides.*/ + export interface ICSR { + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: string): ICSR; + + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Sets pre-render callbacks. Callback called before rendering starts. + @param callbacks pre-render callbacks. + */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. + @param callbacks post-render callbacks. + */ + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks pre-render callbacks. + */ + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks post-render callbacks. + */ + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Registers overrides in client-side templating engine.*/ + register(): void; + + /** Override View rendering template. + @param template New view template. + */ + view(template: string): ICSR; + + /** Override View rendering template. + @param template New view template. + */ + view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; + view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; + item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + + /** Override DisplyForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: string): ICSR; + + /** Override DisplyForm rendering template. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override EditForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: string): ICSR; + + /** Override EditForm rendering template. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override NewForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: string): ICSR; + + /** Override NewForm rendering template. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + + /** Set initial value for field. + @param fieldName Internal name of the field. + @param value Initial value for field. + */ + setInitialValue(fieldName: string, value: any): ICSR; + + /** Make field hidden in list view and standard forms. + @param fieldName Internal name of the field. + */ + makeHidden(fieldName: string): ICSR + + + /** Replace New and Edit templates for field to Display template. + @param fieldName Internal name of the field. + */ + makeReadOnly(fieldName: string): ICSR + + /** Create cascaded Lookup Field. + @param fieldName Internal name of the field. + @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. + */ + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + + /** Auto computes text-based field value based on another fields. + @param targetField Internal name of the field. + @param transform Function combines source field values. + @param sourceField Internal names of source fields. + */ + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + + /** Field text value with autocomplete based on autofill.js + @param fieldName Internal name of the field. + @param ctx AutoFill context. + */ + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + + /** Replace defult dropdown to search-based autocomplete for Lookup field. + @param fieldName Internal name of the field. + */ + seachLookup(fieldName: string): ICSR; + + /** Adds link to add new value to lookup list. + @param fieldName Internal name of the field. + @param prompt Text to display as a link to add new value. + @param contentTypeID Default content type for new item. + */ + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + + + } + + export interface IAutoFillFieldContext { + renderContext: SPClientTemplates.RenderContext_FieldInForm; + fieldContext: SPClientTemplates.ClientFormContext; + autofill: SPClientAutoFill; + control: HTMLInputElement; + } + + export interface IKoFieldInForm { + renderingContext?:SPClientTemplates.RenderContext_FieldInForm; + value?:KnockoutObservable; + } + + + interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: IFormContextHook; + } + + interface IFormContextHook { + [fieldName: string]: IFormContextHookField; + } + + interface IFormContextHookField { + fieldSchema?: SPClientTemplates.FieldSchema_InForm; + lastValue?: any; + getValue?: () => any; + updatedValueCallbacks: UpdatedValueCallback[]; + } + + + function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + return hook[fieldName] = hook[fieldName] || { + updatedValueCallbacks: [] + }; + + } + + class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { + constructor(public valueGetter: () => boolean, public validationMessage: string) { } + + Validate(value: any): SPClientForms.ClientValidation.ValidationResult { + return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); + } + } + +} + +if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); +} + + +//mquery.ts + + + + +module spdevlab { + export module mQuery { + export class DynamicTable { + + // private fields + _domContainer:HTMLElement; + _tableContainer:MQueryResultSetElements; + + _rowTemplateId:string = null; + _rowTemplateContent:string = null; + + _options = { + tableCnt: '.spdev-rep-tb', + addCnt: '.spdev-rep-tb-add', + removeCnt: '.spdev-rep-tb-del' + }; + + // public methods + init(domContainer: HTMLElement, options) { + + if (m$.isDefinedAndNotNull(options)) { + m$.extend(this._options, options); + } + + this._initContainers(domContainer); + + this._initRowTemplate(); + this._initEvents(); + this._showUI(); + } + + // private methods + _initContainers(domContainer) { + + this._domContainer = domContainer; + this._tableContainer = m$(this._options.tableCnt, this._domContainer); + } + + _showUI() { + m$(this._domContainer).css("display", ""); + } + + _initEvents() { + + m$(this._options.addCnt, this._domContainer).click(() => { + + if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { + + m$(this._tableContainer).append(this._rowTemplateContent); + + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + + var targetElement = e.currentTarget; + var parentRow = m$(targetElement).parents("tr").first(); + + m$(parentRow).remove(); + }); + } + + return false; + }); + } + + _initRowTemplate() { + var templateId = m$(this._tableContainer).attr("template-id"); + + if (m$.isDefinedAndNotNull(templateId)) { + this._rowTemplateId = templateId; + this._rowTemplateContent = DynamicTable._templates[templateId]; + } + } + + static _templates:string[] = []; + static initTables() { + // init templates + m$('script').forEach((template:HTMLElement) => { + + var id = m$(template).attr("dynamic-table-template-id"); + + if (m$.isDefinedAndNotNull(id)) { + DynamicTable._templates[id] = template.innerHTML; + } + }); + + // init tables + m$(".spdev-rep-tb-cnt").forEach( divContainer => { + + var dynamicTable = new DynamicTable(); + + dynamicTable.init(divContainer, { + removeCnt: '.spdev-rep-tb-del-override' + }); + }); + } + + }; + + + } +} + +m$.ready(() => { + spdevlab.mQuery.DynamicTable.initTables(); +}); + + +//whoisapppart.ts + + +module _ { + var queryString = parseQueryString(); + var isIframe = queryString['DisplayMode'] == 'iframe' + var spHostUrl = queryString['SPHostUrl']; + var editmode = Number(queryString['editmode']); + var includeDetails = queryString['boolProp'] == 'true'; + + prepareVisual(); + m$.ready(() => { + loadPeoplePicker('peoplePicker'); + partProperties(); + + if (isIframe) { + partResize(); + } + }); + + //Load the people picker + function loadPeoplePicker(peoplePickerElementId: string) { + var schema: ISPClientPeoplePickerSchema = { + PrincipalAccountType: "User", + AllowMultipleValues: false, + Width: 300, + OnUserResolvedClientScript: onUserResolvedClientScript + } + + SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); + } + + function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { + if (users.length > 0) { + var person = users[0]; + var accountName = person.Key; + + var context = SP.ClientContext.get_current(); + + var peopleManager = new SP.UserProfiles.PeopleManager(context); + var personProperties = peopleManager.getPropertiesFor(accountName); + + context.load(personProperties); + context.executeQueryAsync((sender, args) => { + + $get("basicInfo").style.display = 'block'; + + var userPic = personProperties.get_userProfileProperties()["PictureURL"]; + $get("pic").innerHTML = ' + personProperties.get_displayName() + '; + + $get("name").innerHTML = '
' + personProperties.get_displayName() + ''; + $get("email").innerHTML = '' + personProperties.get_email() + ''; + $get("title").innerHTML = personProperties.get_title(); + $get("department").innerHTML = person.EntityData.Department; + $get("phone").innerHTML = person.EntityData.MobilePhone; + + var properties = personProperties.get_userProfileProperties(); + var messageText = ""; + for (var key in properties) { + messageText += "
[" + key + "]: \"" + properties[key] + "\""; + } + $get("detailInfo").innerHTML = messageText; + + if (isIframe) { + partResize(); + } + + }, (sender, args) => { alert('Error: ' + args.get_message()); }); + + } + } + + function partProperties() { + + if (editmode == 1) { + $get("editmodehdr").style.display = "inline"; + $get("content").style.display = "none"; + } + else if (includeDetails) { + $get('detailInfo').style.display = 'block'; + + $get("editmodehdr").style.display = "none"; + $get("content").style.display = "inline"; + } + } + + function partResize() { + var bounds = Sys.UI.DomElement.getBounds(document.body); + parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); + } + + function prepareVisual() { + if (isIframe) { + //Create a Link element for the defaultcss.ashx resource + var linkElement = document.createElement('link'); + linkElement.setAttribute('rel', 'stylesheet'); + linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); + + //Add the linkElement as a child to the head section of the html + document.head.appendChild(linkElement); + } else { + + m$.ready(() => { + var nav = new SP.UI.Controls.Navigation('navigation', { + appIconUrl: queryString['SPHostLogo'], + appTitle: document.title + }); + nav.setVisible(true); + $get('apppart-notification').style.display = 'block'; + document.body.style.overflow = 'visible'; + }); + } + } + + function parseQueryString() { + var result = {}; + var qs = document.location.search.split('?')[1]; + if (qs) { + var parts = qs.split('&'); + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var pair = parts[i].split('='); + result[pair[0]] = decodeURIComponent(pair[1]); + } + } + } + return result; + } +} + +//taxonomy +module SP { + + // Class + export class ClientContextPromise extends SP.ClientContext { + /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ + executeQueryPromise(): JQueryPromise { + var deferred = jQuery.Deferred(); + this.executeQueryAsync(function (sender, args) { + deferred.resolve(sender, args); + }, + function (sender, args) { + deferred.reject(sender, args); + }) + return deferred.promise(); + } + + constructor(serverRelativeUrlOrFullUrl: string) { + super(serverRelativeUrlOrFullUrl); + } + + static get_current(): ClientContextPromise { + return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); + } + + } + +} + +SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); + +module _ { + var context: SP.ClientContextPromise; + var web: SP.Web; + var site: SP.Site; + var session: SP.Taxonomy.TaxonomySession; + var termStore: SP.Taxonomy.TermStore; + var groups: SP.Taxonomy.TermGroupCollection; + + // This code runs when the DOM is ready and creates a context object + // which is needed to use the SharePoint object model. + // It also wires up the click handlers for the two HTML buttons in Default.aspx. + $(document).ready(function () { + context = SP.ClientContextPromise.get_current(); + site = context.get_site(); + web = context.get_web(); + $('#listExisting').click(function () { listGroups(); }); + $('#createTerms').click(function () { createTerms(); }); + }); + + // When the listExisting button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function listGroups() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); + } + + // Runs when the executeQueryAsync method in the listGroups function has succeeded. + // In this case, get and load the groups associated with the term store that we + // know we now have a reference to. + function onListTaxonomySession() { + groups = termStore.get_groups(); + context.load(groups); + context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. + // In this case, loop through all the groups and add a clickable div element to the report area + // for each group. + // NOTE: We clear the report area first to ensure we have a clean place to write to. + // Also note how we create a click event handler for each div on-the-fly, and that we pass in the + // current group ID to that function. So when the user clicks one of these divs, we will know which + // one was clicked. + function onRetrieveGroups() { + $('#report').children().remove(); + + var groupEnum = groups.getEnumerator(); + + // For each group, we'll build a clickable div. + while (groupEnum.moveNext()) { + (() => { + var currentGroup = groupEnum.get_current(); + var groupName = document.createElement("div"); + groupName.setAttribute("style", "float:none;cursor:pointer"); + var groupID = currentGroup.get_id(); + groupName.setAttribute("id", groupID.toString()); + $(groupName).click(() => showTermSets(groupID)); + groupName.appendChild(document.createTextNode(currentGroup.get_name())); + $('#report').append(groupName); + })(); + } + } + + // This is the function that runs when the user clicks one of the divs + // that we created in the onRetrieveGroups function. We can know which + // div was clicked by interrogating the groupID parameter. So what we'll + // do is retrieve a reference to the group with the same ID as the div, and + // then add the term sets that belong to that group under the div that was clicked. + function showTermSets(groupID: SP.Guid) { + + // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. + // The reason we don't clear them all is becuase we want to retain the text node of the + // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop + // controller. + var parentDiv = document.getElementById(groupID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // For each term set, we'll build a clickable div + var currentGroup = groups.getById(groupID); + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + context.load(currentGroup); + var termSets: SP.Taxonomy.TermSetCollection; + context.executeQueryPromise() + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise() + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } + + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + } + + + // This is the function that runs when the user clicks one of the divs + // that we created in the showTermSets function. We can know which + // div was clicked by interrogating the termSetID parameter. So what we'll + // do is retrieve a reference to the term set with the same ID as the div, and + // then add the term that belong to that term set under the div that was clicked. + + function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { + + // First, cancel the bubble so that the group div click handler does not also fire + // because that removes all term set divs and we don't want that here. + event.cancelBubble = true; + + // Get a reference to the term set div that was click and + // remove its children (apart from the TextNode that is currently + // showing the term set name. + var parentDiv = document.getElementById(termSetID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + var currentGroup = groups.getById(groupID); + var termSets:SP.Taxonomy.TermSetCollection; + var currentTermSet:SP.Taxonomy.TermSet; + var terms:SP.Taxonomy.TermCollection; + + context.load(currentGroup); + context + .executeQueryPromise() + .then(() => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) + .then(() => { + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) + .then(() => { + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); + + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailRetrieveGroups(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); + } + + // Runs when the executeQueryAsync method in the listGroups function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailListTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + + + // When the createTerms button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function createTerms() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); + } + + + // This function is the success callback for loading the session and store from the createTerms function + function onGetTaxonomySession() { + // Create six GUIDs that we will need when we create a new group, term set, and associated terms + var guidGroupValue = SP.Guid.newGuid(); + var guidTermSetValue = SP.Guid.newGuid(); + var guidTerm1 = SP.Guid.newGuid(); + var guidTerm2 = SP.Guid.newGuid(); + var guidTerm3 = SP.Guid.newGuid(); + var guidTerm4 = SP.Guid.newGuid(); + + // Create a new group + var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); + + // Create a new term set in the newly-created group + var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); + + // Create four new terms in the newly-created term set + myTermSet.createTerm("Top Secret", 1033, guidTerm1); + myTermSet.createTerm("Company Confidential", 1033, guidTerm2); + myTermSet.createTerm("Partners Only", 1033, guidTerm3); + myTermSet.createTerm("Public", 1033, guidTerm4); + + // Ensure the groups variable has been set, because when this all succeeds we will + // effectively run the same code as if the user had clicked the listGroups button + groups = termStore.get_groups(); + context.load(groups); + + // Execute all the preceeding statements in this function + context.executeQueryAsync(onAddTerms, onFailAddTerms); + + } + + // If all is well with creating the terms, then this function will run. + // Effectively this runs the same code as if the user had clicked the listGroups button + // so the user will see their newly-created group + function onAddTerms() { + listGroups(); + } + + // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailAddTerms(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to add terms. Error: " + args.get_message()); + } + + // Runs when the executeQueryAsync method in the createTerms function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + +}; + +//publishing.ts +// Variables used in various callbacks +JSRequest.EnsureSetup(); + +SP.SOD.execute('mquery.js', 'm$.ready', () => { + var context = SP.ClientContext.get_current(); + var web = context.get_web(); + m$('#CreatePage').click(createPage); +}); + +function createPage(evt) { + SP.SOD.execute('sp.js', 'SP.ClientConext', () => { + SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { + var context = SP.ClientContext.get_current(); + + + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function () { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function () { + + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( + + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function () { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, + + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function (sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to add a new Publishing Page. + function (sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function (sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); + }); +} + +//likes +module SampleReputation { + + interface MyList extends SPClientTemplates.RenderContext_InView { + listId: string; + } + + class MyItem { + + id: number; + title: string; + likesCount: number; + isLikedByCurrentUser: boolean; + + constructor(public row: SPClientTemplates.Item) { + this.id = parseInt(row['ID']); + this.title = row['Title']; + this.likesCount = parseInt(row['LikesCount']) || 0; + this.isLikedByCurrentUser = this.getLike(row['LikedBy']); + } + + private getLike(likedBy): boolean { + if (likedBy && likedBy.length > 0) { + for (var i = 0; i < likedBy.length; i++) { + if (likedBy[i].id == _spPageContextInfo.userId) { + return true; + } + } + } + return false; + } + } + + function init() { + SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); + SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); + SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { + CSR.override(10004, 1) + .onPreRender((ctx: MyList) => { + ctx.listId = ctx.listName.substring(1, 37); + }) + .header('
    ') + .body(renderTemplate) + .footer('
') + .register(); + }); + + SP.SOD.execute('mQuery.js', 'm$.ready', () => { + RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); + }); + + + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); + } + + function renderTemplate(ctx: MyList) { + var rows = ctx.ListData.Row; + var result = ''; + for (var i = 0; i < rows.length; i++) { + var item = new MyItem(rows[i]); + result += '\ +
  • ' + item.title +'\ + \ + ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ + \ +
  • '; + } + return result; + } + + function getLikeText(isLikedByCurrentUser: boolean) { + return isLikedByCurrentUser ? '\u2665' : '\u2661'; + } + + export function setLike(itemId: number, listId: string): void { + var context = SP.ClientContext.get_current(); + var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); + context.executeQueryAsync( + () => { + m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); + }, + (sender, args) => { + alert(args.get_message()); + }); + }); + } + + init(); +} + + + +//code from https://github.com/gandjustas/SharePointAngularTS +module App { + "use strict"; +var app = angular.module("app", []); +} + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + interface Iappcontroller { + title: string; + activate: () => void; + } + + class appcontroller implements Iappcontroller { + title: string = "appcontroller"; + lists: SP.List[]; + + static $inject: string[] = ["$SharePoint", "$spnotify"]; + + constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + this.activate(); + } + + activate() { + var loading = this.$n.showLoading(true) + this.$SharePoint + .getLists() + .then(l => this.lists = l ) + .catch((e: string) => this.$n.show(e, true)) + .finally(() => this.$n.remove(loading) ); + ; + + } + } + + angular.module("app").controller("appcontroller", appcontroller); +} + + + +module App { + "use strict"; + + export interface ISharePoint { + getLists: () => ng.IPromise; + } + + class SharePointServcie implements ISharePoint { + static $inject: string[] = ["$q"]; + + constructor(public $q: ng.IQService) { + } + + getLists() { + var promise = this.$q.defer(); + SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { + var ctx = SP.ClientContext.get_current(); + var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); + var appCtx = new SP.AppContextSite(ctx, hostUrl); + var hostWeb = appCtx.get_web(); + var lists = hostWeb.get_lists(); + ctx.load(lists); + + ctx.executeQueryAsync(() => { + var result: SP.List[] = []; + for (var e = lists.getEnumerator(); e.moveNext();) { + result.push(e.get_current()); + } + promise.resolve(result); + }, + (o, args) => { promise.reject(args.get_message()); }); + }); + return promise.promise; + } + } + + angular.module("app").service("$SharePoint", SharePointServcie); +} + + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + export interface ISpNotify { + showLoading(sticky?: boolean) : string; + show(msg: string, sticky?: boolean): string; + remove(id: string):void; + } + + class SpNotify implements ISpNotify { + static $inject: string[] = []; + + + showLoading(sticky: boolean = false) { + return SP.UI.Notify.showLoadingNotification(sticky); + } + + show(msg: string, sticky: boolean = false) { + return SP.UI.Notify.addNotification(msg, sticky); + } + + remove(id: string) { + SP.UI.Notify.removeNotification(id); + } + } + + angular.module("app").service("$spnotify", SpNotify); +} + From 224c116dd730b76c71d936b2b0e61267cccce122 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 14 Jul 2015 10:59:31 +0100 Subject: [PATCH 088/416] Type definition and tests for node cson module --- cson/cson-test.cson | 1 + cson/cson-test.json | 1 + cson/cson-tests.ts | 36 ++++++++++++++++++++++++++++++++++++ cson/cson.d.ts | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 cson/cson-test.cson create mode 100644 cson/cson-test.json create mode 100644 cson/cson-tests.ts create mode 100644 cson/cson.d.ts diff --git a/cson/cson-test.cson b/cson/cson-test.cson new file mode 100644 index 000000000..a69eb2ef5 --- /dev/null +++ b/cson/cson-test.cson @@ -0,0 +1 @@ +hello: 'world' diff --git a/cson/cson-test.json b/cson/cson-test.json new file mode 100644 index 000000000..56c8e2803 --- /dev/null +++ b/cson/cson-test.json @@ -0,0 +1 @@ +{"hello": "world"} diff --git a/cson/cson-tests.ts b/cson/cson-tests.ts new file mode 100644 index 000000000..62e7f064d --- /dev/null +++ b/cson/cson-tests.ts @@ -0,0 +1,36 @@ +/// + +import cson = require('cson'); + +var data: string = cson.stringify({hello: 'world'}); +console.log('cson.stringify => %s', data); + +data = cson.createString({hello: 'world'}); +console.log('cson.createString => %s', data); + +data = cson.createJSONString({hello: 'world'}); +console.log('cson.createJSONString => %s', data); + +data = cson.createCSONString({hello: 'world'}); +console.log('cson.createCSONString => %s', data); + +var obj: Object = cson.parse(data); +console.log('cson.parse => %s', JSON.stringify(obj)); + +obj = cson.parseCSONString(data); +console.log('cson.parseCSONString => %s', JSON.stringify(obj)); + +obj = cson.parseJSONString('{"hello": "world"}'); +console.log('cson.parseJSONString => %s', JSON.stringify(obj)); + +obj = cson.parseString("hello: 'world'"); +console.log('cson.parseString => %s', JSON.stringify(obj)); + +obj = cson.load('cson-test.cson'); +console.log('cson.load => %s', JSON.stringify(obj)); + +obj = cson.parseCSONFile('cson-test.cson'); +console.log('cson.parseCSONFile => %s', JSON.stringify(obj)); + +obj = cson.parseJSONFile('cson-test.json'); +console.log('cson.parseJSONFile => %s', JSON.stringify(obj)); diff --git a/cson/cson.d.ts b/cson/cson.d.ts new file mode 100644 index 000000000..ca7d2faed --- /dev/null +++ b/cson/cson.d.ts @@ -0,0 +1,32 @@ +// Type definitions for CSON +// Project: https://github.com/bevry/cson +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "cson" { + // Create Strings + export function stringify(data: Object, opts?: Object, indent?: any): string; + export function createCSONString(data: Object, opts?: Object, next?: any): string; + export function createJSONString(data: Object, opts?: Object, next?: any): string; + export function createString(data: Object, opts?: Object, next?: any): string; + + // Parse Strings + export function parse(data: string, opts?: Object, next?: any): Object; + export function parseCSONString(data: string, opts?: Object, next?: any): Object; + export function parseJSONString(data: string, opts?: Object, next?: any): Object; + export function parseCSString(data: string, opts?: Object, next?: any): Object; + export function parseJSString(data: string, opts?: Object, next?: any): Object; + export function parseString(data: string, opts?: Object, next?:any): Object; + + // Parse Files + export function load(filePath: string, opts?: Object, next?: any): Object; + export function parseCSONFile(filePath: string, opts?: Object, next?: any): Object; + export function parseJSONFile(filePath: string, opts?: Object, next?: any): Object; + export function parseCSFile(filePath: string, opts?: Object, next?: any): Object; + export function parseJSFile(filePath: string, opts?: Object, next?: any): Object; + + // Require Files + export function requireCSFile(filePath: string, opts?: Object, next?: any): Object; + export function requireJSFile(filePath: string, opts?: Object, next?: any): Object; + export function requireFile(filePath: string, opts?: Object, next?: any): Object; +} From fb069179afbfb93c34e4c1e3ff5df81278ac3a82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Tue, 14 Jul 2015 15:27:35 +0300 Subject: [PATCH 089/416] easy-jsend --- easy-jsend/easy-jsend-tests.ts | 49 ++++++++++++++++++++++++++++++++++ easy-jsend/easy-jsend.d.ts | 38 ++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 easy-jsend/easy-jsend-tests.ts create mode 100644 easy-jsend/easy-jsend.d.ts diff --git a/easy-jsend/easy-jsend-tests.ts b/easy-jsend/easy-jsend-tests.ts new file mode 100644 index 000000000..9d7814254 --- /dev/null +++ b/easy-jsend/easy-jsend-tests.ts @@ -0,0 +1,49 @@ +/// +/// + +import mongoose = require('mongoose'); +import express = require('express'); +import jSend = require('easy-jsend'); + +var schema = new mongoose.Schema({ + name: {type: String} +}); + +var Model = mongoose.model('model', schema); + +jSend.init({partial: true}); + +var app = express(); + +app.get('/success', function (req, res, next) { + res.success('Success'); +}); + +app.get('/fail', function (req, res, next) { + res.fail('fail'); +}); + +app.get('/error', function (req, res, next) { + res.error('error'); +}); + +app.get('/partial', function (req, res, next) { + res.partial({ + offset: 10, + limit: 50, + count: 100, + data: [] + }); +}); + +app.get('/partial', function (req, res, next) { + res.makePartial({ + model: Model, + search: {}, + opts: { + limit: 30, + skip: 10 + }, + result: [] + }); +}); \ No newline at end of file diff --git a/easy-jsend/easy-jsend.d.ts b/easy-jsend/easy-jsend.d.ts new file mode 100644 index 000000000..21a9bc11e --- /dev/null +++ b/easy-jsend/easy-jsend.d.ts @@ -0,0 +1,38 @@ +// Type definitions for easy-jsend +// Project: https://github.com/DeadAlready/easy-jsend +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + + interface MakePartialInput { + model:any; + opts: { + limit: number; + skip: number; + }; + search: Object; + result: any; + } + + interface PartialInput { + limit?: number; + offset: number; + count: number; + data: any; + } + + export interface Response { + success (data?: any, status?: number): void; + fail (data: any, status?: number): void; + error (err: any): void; + partial? (data: PartialInput, status?: number): void; + makePartial? (data: MakePartialInput): void; + } +} + +declare module "easy-jsend" { + export function init(conf?:{partial:boolean}): void; +} \ No newline at end of file From d910496ddc910e8e9b15290780505ea3fb45cbd8 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 09:28:38 -0700 Subject: [PATCH 090/416] Extended definitions with info from formlyApiCheck. --- angular-formly/angular-formly-test.ts | 67 ++-- angular-formly/angular-formly.d.ts | 439 ++++++++++++++------------ 2 files changed, 286 insertions(+), 220 deletions(-) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts index 4d4053823..603840208 100644 --- a/angular-formly/angular-formly-test.ts +++ b/angular-formly/angular-formly-test.ts @@ -2,49 +2,76 @@ var app = angular.module('app', ['formly']); +interface IScope extends ng.IScope { + to: { label: string; } +} + class AppController { fields: AngularFormly.IFieldConfigurationObject[]; constructor($scope: ng.IScope) { var vm = this; vm.fields = [ { - field: 'label', + key: 'email', type: 'input', templateOptions: { - maxlength: 8, - minlength: 3 + label: 'Email', + required: true, + type: 'email', + maxlength: 10, + minlength: 6, + placeholder: 'example@example.com' } }, { - template: '
    ' - }, - { - field: 'project', + key: 'ip', type: 'input', - defaultValue: 'Project 1', + validators: { + ipAddress: { + expression: function(viewValue, modelValue) { + var value = modelValue || viewValue; + return /(\d{1,3}\.){3}\d{1,3}/.test(value); + }, + message: '$viewValue + " is not a valid IP Address"' + } + }, templateOptions: { - placeholder: 'Enter a project name...' + label: 'IP Address', + required: true, + type: 'text', + placeholder: '127.0.0.1', + }, + validation: { + messages: { + required: function($viewValue: any, $modelValue: any, scope: IScope) { + return scope.to.label + ' is required' + } + } } }, { - template: () => 'hello' - }, - { + key: 'mac', type: 'input', - key: 'zip', templateOptions: { - type: 'number', - label: 'Zip', - max: 99999, - min: 0, - pattern: '\\d{5}' + label: 'MAC Address', + required: true, + placeholder: '49-8A-BD-4E-00-1D', + pattern: '([0-9A-F]{2}[:-]){5}([0-9A-F]{2})' } }, { type: 'checkbox', - key: 'happyUser', + key: 'checked', templateOptions: { - label: 'Are you happy?' + label: 'Check this' + } + }, + { + key: 'checked2', + type: 'checkbox', + wrapper: null, + templateOptions: { + label: 'no wrapper here...' } } ] diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 807171d07..b34cb1406 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -12,11 +12,46 @@ declare module 'AngularFormly' { declare module AngularFormly { + interface IFieldGroup { + data?: Object; + className?: string; + elementAttributes?: { [key: string]: string }; + fieldGroup: IFieldConfigurationObject[]; + form?: Object; + hide?: boolean; + hideExpression?: string | IExpresssionFunction; + key?: string | number; + model?: string | Object; + options?: IFormOptionsAPI + } + + + interface IFormOptionsAPI { + data?: Object; + fieldTransform?: Function; + formState?: Object; + removeChromeAutoComplete?: boolean; + resetModel?: Function; + templateManipulators?: ITemplateManipulators; + updateInitialValue?: Function; + wrapper?: string | string[]; + } + + /** * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue: any, $modelValue: any, scope: ng.IScope): any; + ($viewValue: any, $modelValue: any, scope: Object): any; + } + + + interface IModelOptions { + updateOn?: string; + debounce?: number; + allowInvalid?: boolean; + getterSetter?: string; + timezone?: string; } @@ -26,19 +61,24 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/ngmodelattrs */ - interface INGModelAttrs { - [key: string]: { - attribute?: string; - expresssion?: string; - value?: string; - } - } + // interface INGModelAttrs { + // [key: string]: { + // attribute?: string; + // expresssion?: string; + // value?: string; + // } + // } interface ITemplateManipulator { (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } + interface ITemplateManipulators { + preWrapper?: ITemplateManipulator[]; + postWrapper?: ITemplateManipulator[]; + } + /** * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator @@ -46,11 +86,11 @@ declare module AngularFormly { interface ITemplateOptions { // both attribute or regular attribute - disabled?: boolean | string; - maxlength?: number | string; - minlength?: number | string; + disabled?: boolean; + maxlength?: number; + minlength?: number; pattern?: string; - required?: boolean | string; + required?: boolean; //attribute only max?: number; @@ -68,6 +108,7 @@ declare module AngularFormly { onKeypress?: string; onKeyup?: string; + label?: string; [key: string]: any; } @@ -77,7 +118,8 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object */ interface IValidator { - expression?: string | { (viewValue: any, modelValue: any): boolean }; + expression: string | IExpresssionFunction; + message?: string | IExpresssionFunction; } @@ -91,8 +133,8 @@ declare module AngularFormly { */ interface IWatcher { deep?: boolean; //Defaults to false - expression?: string | { (field: string, scope: ng.IScope): boolean }; - listener: (field: string, newValue: any, oldValue: any, scope: ng.IScope, stopWatching: Function) => void; + expression?: string | { (field: string, scope: Object): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: Object, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -100,45 +142,22 @@ declare module AngularFormly { // see http://docs.angular-formly.com/docs/field-configuration-object interface IFieldConfigurationObject { - /** - * The type of field to be rendered. This is the recommended method - * for defining fields. Types must be pre-defined using formlyConfig. + * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the + * field, and anything else you have in your injector. * - * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f */ - type?: string; + controller?: string | Function; /** - * Can be set instead of type or templateUrl to use a custom html - * template form field. Recommended to be used with one-liners mostly - * (like a directive), or if you're using webpack with the ability to require templates :-) + * This is reserved for the developer. You have our guarantee to be able to use this and not worry about + * future versions of formly overriding your usage and preventing you from upgrading :-) * - * If a function is passed, it is invoked with the field configuration object and can return - * either a string for the template or a promise that resolves to a string. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function + * see http://docs.angular-formly.com/docs/field-configuration-object#data-object */ - template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function - */ - templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#key-string - */ - key?: string; + data?: Object; /** @@ -150,6 +169,30 @@ declare module AngularFormly { defaultValue?: any; + /** + * You can specify your own class that will be applied to the formly-field directive (or ng-form of + * a fieldGroup). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string + */ + className?: string; + + + elementAttributes?: string; + + + /** + * An object where the key is a property to be set on the main field config and the value is an + * expression used to assign that property. The value is a formly expressions. The returned value is + * wrapped in $q.when so you can return a promise from your function :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + */ + expressionProperties?: { + [key: string]: string | IExpresssionFunction | IValidator; + } + + /** * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use * hideExpression. See below. @@ -169,6 +212,42 @@ declare module AngularFormly { hideExpression?: string | IExpresssionFunction; + /** + * This allows you to specify the id of your field (which will be used for its name as well unless + * a name is provided). Note, you can also override the id generation code using the formlyConfig + * extra called getFieldId. + * + * AVOID THIS + * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's + * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need + * to concern yourself with making sure that this is unique. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#id-string + */ + id?: string; + + + initialValue?: any; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#key-string + */ + key?: string | number; + + + /** + * This allows you to specify a link function. It is invoked after your template has finished compiling. + * You are passed the normal arguments for a normal link function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function + */ + link?: ng.IDirectiveLinkFn; + + /** * By default, the model passed to the formly-field directive is the same as the model passed to the * formly-form. However, if the field has a model specified, then it is used for that field (and that @@ -184,39 +263,14 @@ declare module AngularFormly { /** - * An object where the key is a property to be set on the main field config and the value is an - * expression used to assign that property. The value is a formly expressions. The returned value is - * wrapped in $q.when so you can return a promise from your function :-) + * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see + * below) will add this attribute to your ng-model element automatically if this property exists. Note, + * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model + * to options.value which is a getterSetter that formly adds to field options. * - * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions */ - expressionProperties?: { - [key: string]: string | IExpresssionFunction; - } - - - /** - * You can specify your own class that will be applied to the formly-field directive (or ng-form of - * a fieldGroup). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string - */ - className?: string; - - - /** - * This allows you to specify the id of your field (which will be used for its name as well unless - * a name is provided). Note, you can also override the id generation code using the formlyConfig - * extra called getFieldId. - * - * AVOID THIS - * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's - * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need - * to concern yourself with making sure that this is unique. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#id-string - */ - id?: string; + modelOptions?: IModelOptions; /** @@ -232,48 +286,6 @@ declare module AngularFormly { name?: string; - /** - * This is reserved for the developer. You have our guarantee to be able to use this and not worry about - * future versions of formly overriding your usage and preventing you from upgrading :-) - * - * see http://docs.angular-formly.com/docs/field-configuration-object#data-object - */ - data?: any; - - - /** - * This is reserved for the templates. Any template-specific options go in here. Look at your specific - * template implementation to know the options required for this. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object - */ - templateOptions?: ITemplateOptions; - - - /** - * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a - * type configuration if you want it to apply to all fields of a certain type). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions - */ - templateManipulator?: { - preWrapper: ITemplateManipulator[]; - postWrapper: ITemplateManipulator[]; - } - - - /** - * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If - * given an array, the formly field template will be wrapped by the first wrapper, then the second, then - * the third, etc. You can also specify these as part of a type (which is the recommended approach). - * Specifying this property will override the wrappers for the type for this field. - * - * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings - */ - wrapper?: string | string[]; - - - //TODO:Scott Figure out what this really does. /** * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element * of field templates. You will likely not use this often. This object is a little complex, but extremely @@ -281,47 +293,12 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object */ - ngModelAttrs?: any; - - - /** - * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the - * field, and anything else you have in your injector. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f - */ - controller?: string | { Function: void }; - - - /** - * This allows you to specify a link function. It is invoked after your template has finished compiling. - * You are passed the normal arguments for a normal link function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function - */ - link?: ng.IDirectiveLinkFn; - - - /** - * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority - * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and - * hence will override any duplicates of those properties as well. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings - */ - optionsTypes?: string | string[]; - - - //TODO:Scott Still need to define - /** - * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see - * below) will add this attribute to your ng-model element automatically if this property exists. Note, - * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model - * to options.value which is a getterSetter that formly adds to field options. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions - */ - modelOptions?: any; + ngModelAttrs?: { + attribute?: any; + bound?: any; + expression?: any; + value?: any; + }; /** @@ -335,29 +312,62 @@ declare module AngularFormly { /** - * An object which has at least two properties called expression and listener. The watch.expression is added - * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type - * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want - * it to be a deep watch via the watcher.deep property (defaults to false). + * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority + * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and + * hence will override any duplicates of those properties as well. * - * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings */ - watcher?: IWatcher | IWatcher[]; + optionsTypes?: string | string[]; - //TODO:Scott Look at defining validators as an Object to see if additional interface needs to be created /** - * An object where the keys are the name of the validator and the values are Formly Expressions; + * Can be set instead of type or templateUrl to use a custom html + * template form field. Recommended to be used with one-liners mostly + * (like a directive), or if you're using webpack with the ability to require templates :-) * - * Async Validation - * All function validators can return true/false/Promise. A validator passes if it returns true or a promise - * that is resolved. A validator fails if it returns false or a promise that is rejected. + * If a function is passed, it is invoked with the field configuration object and can return + * either a string for the template or a promise that resolves to a string. * - * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function */ - validators?: { - [key: string]: IValidator | string; - } + template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a + * type configuration if you want it to apply to all fields of a certain type). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions + */ + templateManipulators?: ITemplateManipulators; + + + /** + * This is reserved for the templates. Any template-specific options go in here. Look at your specific + * template implementation to know the options required for this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object + */ + templateOptions?: ITemplateOptions; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function + */ + templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * The type of field to be rendered. This is the recommended method + * for defining fields. Types must be pre-defined using formlyConfig. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + */ + type?: string; /** @@ -365,13 +375,21 @@ declare module AngularFormly { */ validation?: { + /** + * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because + * you generally only want to show error messages when the user has interacted with a specific field, this value + * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference + * for pre-angular 1.3 because it doesn't have touched support). + */ + errorExistsAndShouldBeVisible?: boolean; + /** * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages * like in this example. */ messages?: { - [key: string]: IExpresssionFunction; + [key: string]: IExpresssionFunction | string; } @@ -382,17 +400,23 @@ declare module AngularFormly { */ show?: boolean; - - /** - * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because - * you generally only want to show error messages when the user has interacted with a specific field, this value - * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference - * for pre-angular 1.3 because it doesn't have touched support). - */ - errorExistsAndShouldBeVisible?: boolean; - } + + /** + * An object where the keys are the name of the validator and the values are Formly Expressions; + * + * Async Validation + * All function validators can return true/false/Promise. A validator passes if it returns true or a promise + * that is resolved. A validator fails if it returns false or a promise that is rejected. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + validators?: { + [key: string]: string | IExpresssionFunction | IValidator; + } + + /** * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, @@ -404,6 +428,28 @@ declare module AngularFormly { value?(val: any): void; //Setter + /** + * An object which has at least two properties called expression and listener. The watch.expression is added + * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type + * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want + * it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + watcher?: IWatcher | IWatcher[]; + + + /** + * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If + * given an array, the formly field template will be wrapped by the first wrapper, then the second, then + * the third, etc. You can also specify these as part of a type (which is the recommended approach). + * Specifying this property will override the wrappers for the type for this field. + * + * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings + */ + wrapper?: string | string[]; + + //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) @@ -412,7 +458,7 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller */ - formControl?: ng.IFormController; + formControl?: ng.IFormController | ng.IFormController[]; /** @@ -424,15 +470,6 @@ declare module AngularFormly { resetModel?: () => void; - /** - * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. - * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function - */ - updateInitialValue?: () => void; - - /** * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the @@ -443,12 +480,14 @@ declare module AngularFormly { runExpressions?: () => void; - - ////////////////// BOOTSTRAP SPECIFIC /////////////////////// - fieldGroup?: IFieldConfigurationObject[]; + /** + * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. + * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function + */ + updateInitialValue?: () => void; } - - } \ No newline at end of file From b22932b2efcb0f433b587df4bc6dccd30331c99a Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 09:29:51 -0700 Subject: [PATCH 091/416] Removed unused interface. --- angular-formly/angular-formly.d.ts | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index b34cb1406..48f5c7bad 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -55,25 +55,11 @@ declare module AngularFormly { } - /** - * This is part of the built-in formlyConfig templateManipulator called ngModelAttrsTemplateManipulator. - * This allows you to keep your templates very small and add custom behavior on at the type or field level. - * - * see http://docs.angular-formly.com/docs/ngmodelattrs - */ - // interface INGModelAttrs { - // [key: string]: { - // attribute?: string; - // expresssion?: string; - // value?: string; - // } - // } - - interface ITemplateManipulator { (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } + interface ITemplateManipulators { preWrapper?: ITemplateManipulator[]; postWrapper?: ITemplateManipulator[]; From 2f073bda43831dc97bbb709028940f14e938f99b Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:08:15 -0700 Subject: [PATCH 092/416] Added in optional bootstrap template option. Will need to pull out and place in bootstrap-templates definition if it expands much further. --- angular-formly/angular-formly.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 48f5c7bad..b2520bc2c 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -94,7 +94,9 @@ declare module AngularFormly { onKeypress?: string; onKeyup?: string; + //Bootstrap types label?: string; + description?: string; [key: string]: any; } From 5f6361e360c2c5176213736eefceab4b77d93c1d Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:45:53 -0700 Subject: [PATCH 093/416] Add asyncValidators. Added in 6.18.0. --- angular-formly/angular-formly.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index b2520bc2c..001f53767 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-formly 6.17.0 +// Type definitions for angular-formly 6.18.0 // Project: https://github.com/formly-js/angular-formly // Definitions by: Scott Hatcher // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -130,6 +130,17 @@ declare module AngularFormly { // see http://docs.angular-formly.com/docs/field-configuration-object interface IFieldConfigurationObject { + + /** + * Added in 6.18.0 + * + * Demo + * see http://angular-formly.com/#/example/other/unique-value-async-validation + */ + asyncValidators: { + [key: string]: string | IExpresssionFunction | IValidator; + } + /** * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the * field, and anything else you have in your injector. From 0f38c90093459581a33ab8c84abc903eff1aeaf1 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:48:48 -0700 Subject: [PATCH 094/416] asyncValidators isn't required. --- angular-formly/angular-formly.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 001f53767..8ce552c52 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -137,7 +137,7 @@ declare module AngularFormly { * Demo * see http://angular-formly.com/#/example/other/unique-value-async-validation */ - asyncValidators: { + asyncValidators?: { [key: string]: string | IExpresssionFunction | IValidator; } From 5518db1fd9c5e7853680f3f9eb23d4c71d29723a Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 14 Jul 2015 20:17:45 +0100 Subject: [PATCH 095/416] Type definitions and tests for node luaparse module --- luaparse/luaparse-tests.ts | 10 ++++++++++ luaparse/luaparse.d.ts | 8 ++++++++ 2 files changed, 18 insertions(+) create mode 100644 luaparse/luaparse-tests.ts create mode 100644 luaparse/luaparse.d.ts diff --git a/luaparse/luaparse-tests.ts b/luaparse/luaparse-tests.ts new file mode 100644 index 000000000..af10d12d6 --- /dev/null +++ b/luaparse/luaparse-tests.ts @@ -0,0 +1,10 @@ +/// + +import luaparse = require('luaparse'); + +var luacode: string = '-- this is hello world in lua.\nprint(\'hello world\')'; +var ast: Object = luaparse.parse(luacode); +console.log(JSON.stringify(ast)); + +ast = luaparse.parse(luacode, {comments: false}); +console.log(JSON.stringify(ast)); diff --git a/luaparse/luaparse.d.ts b/luaparse/luaparse.d.ts new file mode 100644 index 000000000..311bf651d --- /dev/null +++ b/luaparse/luaparse.d.ts @@ -0,0 +1,8 @@ +// Type definitions for luaparse +// Project: https://github.com/oxyc/luaparse +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "luaparse" { + export function parse(code: string, options?: Object): Object; +} From 4a254090f22aac20e9bcae6c23641e7a235658df Mon Sep 17 00:00:00 2001 From: Johan Gorter Date: Tue, 14 Jul 2015 21:58:39 +0200 Subject: [PATCH 096/416] Strong typing of attributes and properties --- maquette/maquette-tests.ts | 2 + maquette/maquette.d.ts | 144 +++++++++++++++++++++++++++++-------- 2 files changed, 118 insertions(+), 28 deletions(-) diff --git a/maquette/maquette-tests.ts b/maquette/maquette-tests.ts index 0c174e6f4..9d05b3005 100644 --- a/maquette/maquette-tests.ts +++ b/maquette/maquette-tests.ts @@ -51,6 +51,8 @@ var result = cache.result([1], calculate); // h +h("div",{onclick: (ev:MouseEvent) => true}) + var vnode = h("div", [ "text", null, diff --git a/maquette/maquette.d.ts b/maquette/maquette.d.ts index f1e583cad..3270fd547 100644 --- a/maquette/maquette.d.ts +++ b/maquette/maquette.d.ts @@ -9,6 +9,33 @@ */ declare module maquette { + // Needed for typescript pre-1.5? + interface Touch { + clientX: number; + clientY: number; + identifier: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; + target: EventTarget; + } + interface TouchList { + length: number; + item(index: number): Touch; + [index: number]: Touch; + } + interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + export interface VNodeProperties { enterAnimation?: ((element: Element, properties?: VNodeProperties) => void) | string; exitAnimation?: ((element: Element, removeElement: () => void, properties?: VNodeProperties) => void) | string; @@ -17,6 +44,60 @@ declare module maquette { children: VNode[]) => void; afterUpdate?: (element: Element, projectionOptions: ProjectionOptions, vnodeSelector: string, properties: VNodeProperties, children: VNode[]) => void; + key?: Object; + classes?: {[index:string]: boolean}; + styles?: {[index:string]: string}; + + // From Element + ontouchcancel?: (ev?: TouchEvent) => boolean|void; + ontouchend?: (ev?: TouchEvent) => boolean|void; + ontouchmove?: (ev?: TouchEvent) => boolean|void; + ontouchstart?: (ev?: TouchEvent) => boolean|void; + // From HTMLFormElement + action?: string; + encoding?: string; + enctype?: string; + method?: string; + name?: string; + target?: string; + // From HTMLElement + onblur?: (ev?: FocusEvent) => boolean|void; + onchange?: (ev?: Event) => boolean|void; + onclick?: (ev?: MouseEvent) => boolean|void; + ondblclick?: (ev?: MouseEvent) => boolean|void; + onfocus?: (ev?: FocusEvent) => boolean|void; + oninput?: (ev?: Event) => boolean|void; + onkeydown?: (ev?: KeyboardEvent) => boolean|void; + onkeypress?: (ev?: KeyboardEvent) => boolean|void; + onkeyup?: (ev?: KeyboardEvent) => boolean|void; + onload?: (ev?: Event) => boolean|void; + onmousedown?: (ev?: MouseEvent) => boolean|void; + onmouseenter?: (ev?: MouseEvent) => boolean|void; + onmouseleave?: (ev?: MouseEvent) => boolean|void; + onmousemove?: (ev?: MouseEvent) => boolean|void; + onmouseout?: (ev?: MouseEvent) => boolean|void; + onmouseover?: (ev?: MouseEvent) => boolean|void; + onmouseup?: (ev?: MouseEvent) => boolean|void; + onmousewheel?: (ev?: MouseWheelEvent) => boolean|void; + onscroll?: (ev?: UIEvent) => boolean|void; + onsubmit?: (ev?: Event) => boolean|void; + spellcheck?: boolean; + tabIndex?: number; + title?: string; + accessKey?: string; + id?: string; + // From HTMLInputElement + autocomplete?: string; + checked?: boolean; + placeholder?: string; + readOnly?: boolean; + src?: string; + value?: string; + // From HTMLImageElement + alt?: string; + srcset?: string; + + // Everything else (uncommon or custom properties and attributes) [index: string]: Object; } @@ -27,7 +108,10 @@ declare module maquette { } } - export type VNodeChild = string|VNode|Array>>>; // Array means Array + // The following line is not possible in Typescript, hence the workaround in the two lines below + // export type VNodeChild = string|VNode|Array + export interface VNodeChildren extends Array {} // A bit of a hack to create a recursive type + export type VNodeChild = string|VNode|VNodeChildren; export var dom: MaquetteDom; @@ -62,40 +146,44 @@ declare module maquette { export function createProjector(projectionOptions? : ProjectionOptions) : Projector; /** - * The `h` method is used to create a virtual DOM node. - * This function is largely inspired by the mercuryjs and mithril frameworks. + * Creates a virtual DOM node, used to render a real DOM later. * The `h` stands for (virtual) hyperscript. * - * @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. - * It is formatted as follows: `tagname.cssclass1.cssclass2#id`. - * @param {Object} properties - An object literal containing properties that will be placed on the DOM node. - * Properties with functions values like `onclick:handleClick` are registered as event handlers. - * Properties with string values, like `href:"/"` are used as attributes. - * All non-string values are put on the DOM node as properties. - * Property 'key' is used to uniquely identify a DOM node among siblings. - * A key is required when there are more children with the same selector and these children are added or removed dynamically. - * Property classes is an object literal like `{important:true}` which allows css classes, like `important` to be added and removed dynamically. - * Property styles is an object literal like `{height:"100px"}` which allows styles to be changed dynamically. All values must be strings. - * Property enterAnimation is the animation to perform when this node is added to an already existing parent. - * {@link http://maquettejs.org/docs/animations.html|More about animations}. - * When this value is a string, you must pass a `projectionOptions.transitions` object when creating the projector {@link module:maquette.createProjector}. - * Properties exitAnimation is the animation to perform when this node is removed while its parent remains. - * When this value is a string, you must pass a `projectionOptions.transitions` object when creating the projector {@link module:maquette.createProjector}. - * {@link http://maquettejs.org/docs/animations.html|More about animations}. - * Property updateAnimation is the animation to perform when the properties of this node change. - * This also includes attributes, styles, css classes. This callback is also invoked when node contains only text and that text changes. - * {@link http://maquettejs.org/docs/animations.html|More about animations}. - * property afterCreate is the callback that is executed after this node is added to the DOM. Childnodes and properties have already been applied. - * property afterUpdate is the callback that is executed every time this node may have been updated. Childnodes and properties have already been updated. - * @param {Array} children - An array of virtual DOM nodes and strings to add as child nodes. - * This array may contain nested arrays, `null` or `undefined` values. - * Nested arrays are flattened, `null` and `undefined` will be skipped. + * @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`. + * @param {Object} properties - An object literal containing attributes, properties, event handlers and more be placed on the DOM node. + * @param {Array} children - An array of virtual DOM nodes and strings to add as child nodes. May contain nested arrays, null or undefined. * - * @returns {VNode} A VNode object, used to render a real DOM later. NOTE: There are {@link http://maquettejs.org/docs/rules.html|three basic rules} you should be aware of when updating the virtual DOM. + * @returns {VNode} A VNode object, used to render a real DOM later. */ export function h(selector: string, properties: VNodeProperties, children: Array): VNode; + /** + * Creates a virtual DOM node, used to render a real DOM later. + * The `h` stands for (virtual) hyperscript. + * + * @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`. + * @param {Array} children - An array of virtual DOM nodes and strings to add as child nodes. May contain nested arrays, null or undefined. + * + * @returns {VNode} A VNode object, used to render a real DOM later. + */ export function h(selector: string, children: Array): VNode; + /** + * Creates a virtual DOM node, used to render a real DOM later. + * The `h` stands for (virtual) hyperscript. + * + * @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`. + * @param {Object} properties - An object literal containing attributes, properties, event handlers and more be placed on the DOM node. + * + * @returns {VNode} A VNode object, used to render a real DOM later. + */ export function h(selector: string, properties: VNodeProperties): VNode; + /** + * Creates a virtual DOM node, used to render a real DOM later. + * The `h` stands for (virtual) hyperscript. + * + * @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format. It is formatted as follows: `tagname.cssclass1.cssclass2#id`. + * + * @returns {VNode} A VNode object, used to render a real DOM later. + */ export function h(selector: string): VNode; /** From 9916fab22d48b85591d811a0d8490dc47269a7bf Mon Sep 17 00:00:00 2001 From: lnlwd Date: Tue, 14 Jul 2015 22:53:55 -0300 Subject: [PATCH 097/416] Update collection to support new crud operations --- mongodb/mongodb.d.ts | 61 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index a1424cb7e..e4ed2e0c1 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -296,21 +296,54 @@ declare module "mongodb" { // Documentation : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html export interface Collection { new (db: Db, collectionName: string, pkFactory?: Object, options?: CollectionCreateOptions): Collection; // is this right? - + /** + * @deprecated use insertOne or insertMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert + */ insert(query: any, callback: (err: Error, result: any) => void): void; insert(query: any, options: { safe?: any; continueOnError?: boolean; keepGoing?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertOne + inserOne(doc:any, callback: (err: Error, result: any) => void) :void; + insertOne(doc: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMany + insertMany(docs, callback: (err: Error, result: any) => void): void; + insertMany(docs, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + /** + * @deprecated use deleteOne or deleteMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove + */ remove(selector: Object, callback?: (err: Error, result: any) => void): void; remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteOne + deleteOne(filter, callback: (err: Error, result: any) => void): void; + deleteOne(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteMany + deleteMany(filter, callback: (err: Error, result: any) => void): void; + deleteMany(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + rename(newName: String, callback?: (err: Error, result: any) => void): void; save(doc: any, callback : (err: Error, result: any) => void): void; - save(doc: any, options: { safe: any; }, callback : (err: Error, result: any) => void): void; - + save(doc: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback : (err: Error, result: any) => void): void; + /** + * @deprecated use updateOne or updateMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update + */ update(selector: Object, document: any, callback?: (err: Error, result: any) => void): void; update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateOne + updateOne(filter: Object, update: any, callback: (err: Error, result: any) => void): void; + updateOne(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateMany + updateMany(filter: Object, update: any, callback: (err: Error, result: any) => void): void; + updateMany(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + distinct(key: string, query: Object, callback: (err: Error, result: any) => void): void; distinct(key: string, query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; @@ -319,13 +352,31 @@ declare module "mongodb" { count(query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; drop(callback?: (err: Error, result: any) => void): void; - + /** + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify + */ findAndModify(query: Object, sort: any[], doc: Object, callback: (err: Error, result: any) => void): void; findAndModify(query: Object, sort: any[], doc: Object, options: { safe?: any; remove?: boolean; upsert?: boolean; new?: boolean; }, callback: (err: Error, result: any) => void): void; - + /** + * @deprecated use findOneAndDelete + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndRemove + */ findAndRemove(query : Object, sort? : any[], callback?: (err: Error, result: any) => void): void; findAndRemove(query : Object, sort? : any[], options?: { safe: any; }, callback?: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndDelete + findOneAndDelete(filter: any, callback: (err: Error, result: any) => void): void; + findOneAndDelete(filter: any, options: { projection?: any; sort?: any; maxTimeMS?: number; }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndReplace + findOneAndReplace(filter: any, replacement: any, callback: (err: Error, result: any) => void): void; + findOneAndReplace(filter: any, replacement: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndUpdate + findOneAndUpdate(filter: any, update: any, callback: (err: Error, result: any) => void): void; + findOneAndUpdate(filter: any, update: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback: (err: Error, result: any) => void): void; + find(callback?: (err: Error, result: Cursor) => void): Cursor; find(selector: Object, callback?: (err: Error, result: Cursor) => void): Cursor; find(selector: Object, fields: any, callback?: (err: Error, result: Cursor) => void): Cursor; From 3675e7ea849a06811282b93bf7d059944f322143 Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Tue, 7 Jul 2015 11:30:46 +0700 Subject: [PATCH 098/416] Add typings for atom-keymap library --- atom-keymap/.editorconfig | 3 + atom-keymap/atom-keymap-tests.ts | 24 ++++++ atom-keymap/atom-keymap.d.ts | 135 +++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+) create mode 100644 atom-keymap/.editorconfig create mode 100644 atom-keymap/atom-keymap-tests.ts create mode 100644 atom-keymap/atom-keymap.d.ts diff --git a/atom-keymap/.editorconfig b/atom-keymap/.editorconfig new file mode 100644 index 000000000..570211f89 --- /dev/null +++ b/atom-keymap/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = tab +indent_size = 4 diff --git a/atom-keymap/atom-keymap-tests.ts b/atom-keymap/atom-keymap-tests.ts new file mode 100644 index 000000000..520327da9 --- /dev/null +++ b/atom-keymap/atom-keymap-tests.ts @@ -0,0 +1,24 @@ +/// + +import atomKeymap = require('atom-keymap'); +var KeymapManager = atomKeymap.KeymapManager; +type ICompleteMatchEvent = AtomKeymap.ICompleteMatchEvent; +// The import and type aliasing above can be done more concisely in TypeScript 1.5+: +//import { KeymapManager, ICompleteMatchEvent } from "atom-keymap"; + +var manager = new KeymapManager(); +manager.add('some/unique/path', { + '.workspace': { + 'ctrl-x': 'package:do-something', + 'ctrl-y': 'package:do-something-else' + }, + '.mini.editor': { + 'enter': 'core:confirm' + } +}); + +manager.onDidMatchBinding((event: ICompleteMatchEvent): void => { + console.log(event.binding.command); +}) + +manager.destroy(); diff --git a/atom-keymap/atom-keymap.d.ts b/atom-keymap/atom-keymap.d.ts new file mode 100644 index 000000000..355ea38af --- /dev/null +++ b/atom-keymap/atom-keymap.d.ts @@ -0,0 +1,135 @@ +// Type definitions for atom-keymap v5.1.5 +// Project: https://github.com/atom/atom-keymap/ +// Definitions by: Vadim Macagon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module AtomKeymap { + type Disposable = AtomEventKit.Disposable; + + /** Instance side of KeyBinding class. */ + interface KeyBinding { + enabled: boolean; + source: string; + command: string; + keystrokes: string; + keystrokeCount: number; + selector: string; + specificity: number; + + matches(keystroke: string): boolean; + compare(keyBinding: KeyBinding): number; + } + + interface ICompleteMatchEvent { + /** Keystrokes that matched the binding. */ + keystrokes: string; + /** Binding that was matched to the keystrokes. */ + binding: KeyBinding; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IPartialMatchEvent { + /** Keystrokes that matched the binding. */ + keystrokes: string; + /** Bindings that were partially matched to the keystrokes. */ + partiallyMatchedBindings: KeyBinding[]; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IFailedMatchEvent { + /** Keystrokes that failed to match a binding. */ + keystrokes: string; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IKeymapLoadEvent { + /** Path to a keymap file. */ + path: string; + } + + /** Static side of KeymapManager class. */ + interface KeymapManagerStatic { + prototype: KeymapManager; + new (options?: { defaultTarget?: Element }): KeymapManager; + } + + /** Instance side of KeymapManager class. */ + interface KeymapManager { + constructor: KeymapManagerStatic; + /** Unwatches all watched paths. */ + destroy(): void; + + // Event Subscription + + /** Sets callback to invoke when one or more keystrokes completely match a key binding. */ + onDidMatchBinding(callback: (event: ICompleteMatchEvent) => void): Disposable; + /** Sets callback to invoke when one or more keystrokes partially match a binding. */ + onDidPartiallyMatchBindings(callback: (event: IPartialMatchEvent) => void): Disposable; + /** Sets callback to invoke when one or more keystrokes fail to match any bindings. */ + onDidFailToMatchBinding(callback: (event: IFailedMatchEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file is reloaded. */ + onDidReloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file is unloaded. */ + onDidUnloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file could not to be loaded. */ + onDidFailToReadFile(callback: (error: Error) => void): Disposable; + + // Adding and Removing Bindings + + /** Adds sets of key bindings grouped by CSS selector. */ + add(source: string, keyBindingsBySelector: any): Disposable; + + // Accessing Bindings + + getKeyBindings(): KeyBinding[]; + findKeyBindings(params?: { + keystrokes: string; // e.g. 'ctrl-x ctrl-s' + command: string; // e.g. 'editor:backspace' + target?: Element; + }): KeyBinding[]; + + // Managing Keymap Files + + /** + * Loads the key bindings from the given path. + * + * @param bindingsPath A path to a file or a directory. If the path is a directory all files + * inside it will be loaded. + */ + loadKeymap(bindingsPath: string, options?: { watch: boolean }): void; + /** + * Starts watching the given file/directory for changes, reloading any keymaps at that location + * when changes are detected. + * + * @param filePath A path to a file or a directory. + */ + watchKeymap(filePath: string): void; + + // Managing Keyboard Events + + /** + * Dispatches a custom event associated with the matching key binding for the given + * `KeyboardEvent` if one can be found. + */ + handleKeyboardEvent(event: KeyboardEvent): void; + /** Translates a keydown event to a keystroke string. */ + keystrokeForKeyboardEvent(event: KeyboardEvent): string; + /** + * @return The number of milliseconds allowed before pending states caused by partial matches of + * multi-keystroke bindings are terminated. + */ + getPartialMatchTimeout(): number; + } + + /** Allows commands to be associated with keystrokes in a context-sensitive way.*/ + var KeymapManager: KeymapManagerStatic; +} + +declare module 'atom-keymap' { + export = AtomKeymap; +} From e22b188d1b6477ead3ac7866c6209581bf01e2ce Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 15 Jul 2015 10:10:32 +0100 Subject: [PATCH 099/416] Type definitions and tests for node random-string module --- random-string/random-string-tests.ts | 11 +++++++++++ random-string/random-string.d.ts | 9 +++++++++ 2 files changed, 20 insertions(+) create mode 100644 random-string/random-string-tests.ts create mode 100644 random-string/random-string.d.ts diff --git a/random-string/random-string-tests.ts b/random-string/random-string-tests.ts new file mode 100644 index 000000000..2b278a4f5 --- /dev/null +++ b/random-string/random-string-tests.ts @@ -0,0 +1,11 @@ +/// + +import randomString = require('random-string'); + +console.log(randomString()); +console.log(randomString({ + length: 20, + numeric: true, + letters: true, + special: true +})); diff --git a/random-string/random-string.d.ts b/random-string/random-string.d.ts new file mode 100644 index 000000000..f9bcddb1b --- /dev/null +++ b/random-string/random-string.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-string +// Project: https://github.com/valiton/node-random-string +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "random-string" { + function randomString(opts?: Object): string; + export = randomString; +} From 22ac5f1c784e6222ccaddde2dcf793a1c947d310 Mon Sep 17 00:00:00 2001 From: chr22 Date: Wed, 15 Jul 2015 11:37:52 +0200 Subject: [PATCH 100/416] Added three missing methods to $urlMatcherFactory --- angular-ui-router/angular-ui-router.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 18a6fb397..ed2f36ccf 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -88,6 +88,9 @@ declare module angular.ui { compile(pattern: string): IUrlMatcher; isMatcher(o: any): boolean; type(name: string, definition: any, definitionFn?: any): any; + caseInsensitive(value: boolean): void; + defaultSquashPolicy(value: string): void; + strictMode(value: boolean): void; } interface IUrlRouterProvider extends angular.IServiceProvider { From d54bab2cbcdd321ac0eca03aae1e81103a57890f Mon Sep 17 00:00:00 2001 From: Michael Jerred Date: Wed, 15 Jul 2015 12:36:17 +0100 Subject: [PATCH 101/416] Correcting .chunk and .size --- lodash/lodash-tests.ts | 10 ++++++---- lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 3a1c51f18..6a0b68075 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -149,13 +149,13 @@ result = <_.Dictionary>_({ a: 1, b: 2}).mapValues(function(num: number) // * Arrays * // *************/ result = _.chunk([1, '2', '3', false]); -result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(); result = _.chunk([1, '2', '3', false], 2); -result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(2); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(2); result = _.chunk([1, 2, 3, 4]); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(); result = _.chunk([1, 2, 3, 4], 2); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(2); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(2); result = _.compact([0, 1, false, 2, '', 3]); result = <_.LoDashArrayWrapper>_([0, 1, false, 2, '', 3]).compact(); @@ -622,7 +622,9 @@ result = <_.LoDashArrayWrapper>_([1, 2, 3]).shuffle(); result = <_.LoDashArrayWrapper<_.Dictionary>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).shuffle(); result = _.size([1, 2]); +result = _([1, 2]).size(); result = _.size({ 'one': 1, 'two': 2, 'three': 3 }); +result = _({ 'one': 1, 'two': 2, 'three': 3 }).size(); result = _.size('curly'); result = _.some([null, 0, 'yes', false], Boolean); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index fcf468577..6a839596d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -279,7 +279,7 @@ declare module _ { /** * @see _.chunk **/ - chunk(size?: number): LoDashArrayWrapper; + chunk(size?: number): LoDashArrayWrapper; } //_.compact @@ -4526,6 +4526,20 @@ declare module _ { size(aString: string): number; } + interface LoDashArrayWrapper { + /** + * @see _.size + **/ + size(): number; + } + + interface LoDashObjectWrapper { + /** + * @see _.size + **/ + size(): number; + } + //_.some interface LoDashStatic { /** From c3b544905994200debd3b5a6b5734a71c5436f4a Mon Sep 17 00:00:00 2001 From: catbusstop Date: Wed, 15 Jul 2015 14:39:26 +0100 Subject: [PATCH 102/416] Fixing slickgrid getItemMetadata Added optional index parameter to allow for row formatting --- slickgrid/SlickGrid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index cfdd3c690..54686df9f 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -1557,7 +1557,7 @@ declare module Slick { public getLength(): number; public getItem(index: number): T; - public getItemMetadata(): void; + public getItemMetadata(index?: number): void; public onRowCountChanged: Slick.Event; public onRowsChanged: Slick.Event; From e39fec20653e110c960b2956a9ef6d1644117865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Wed, 15 Jul 2015 16:55:42 +0300 Subject: [PATCH 103/416] Easy-api-request --- easy-api-request/easy-api-request-tests.ts | 44 ++++++++ easy-api-request/easy-api-request.d.ts | 115 +++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 easy-api-request/easy-api-request-tests.ts create mode 100644 easy-api-request/easy-api-request.d.ts diff --git a/easy-api-request/easy-api-request-tests.ts b/easy-api-request/easy-api-request-tests.ts new file mode 100644 index 000000000..38a4b68dd --- /dev/null +++ b/easy-api-request/easy-api-request-tests.ts @@ -0,0 +1,44 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// + +import express = require('express'); +import APIRequest = require('easy-api-request'); + +APIRequest.create({ + name: 'testAPI', + config: { + url: 'http://example.com' + } +}); + +var app = express(); + +app.get('/', function (req:any, res:express.Response) { + var rMaker = req.testAPI; + var r = rMaker(); + r.get('/', function (err, resp) { + if(err) { + console.error(err); + } + res.json(err || resp); + }); +}); + +app.get('/', function (req:any, res:express.Response) { + var rMaker = req.testAPI; + var r = rMaker(); + r.get('/') + .then(function (resp) { + res.json(resp); + }) + .catch(function (err){ + if(err) { + console.error(err); + } + res.json(err); + }); +}); diff --git a/easy-api-request/easy-api-request.d.ts b/easy-api-request/easy-api-request.d.ts new file mode 100644 index 000000000..d3152e49d --- /dev/null +++ b/easy-api-request/easy-api-request.d.ts @@ -0,0 +1,115 @@ +// Type definitions for easy-api-request +// Project: https://github.com/DeadAlready/easy-api-request +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +/// +/// + +declare module "easy-api-request" { + import stream = require('stream'); + import http = require('http'); + import request = require('request'); + import bunyan = require('bunyan'); + import express = require('express'); + + export function create(opts: { + name: any; + config: { + url: string; + internal?: boolean; + headers?: string[]; + cookies?: string[]; + replyCookies?: string[]; + jSend?: boolean; + opts?: Object; + }; + }): void; + + import Q = require('q'); + interface Result { + response: http.IncomingMessage; + body: any; + err?: any; + data?: any; + } + class BaseRequest { + protected base: request.Request; + protected req: express.Request; + protected log: bunyan.Logger; + protected replyCookies: string[]; + protected jSend: boolean; + constructor(opts: any); + _parseOptions(args: IArguments, type: string): { + opts: any; + cb: any; + }; + _do(args: IArguments, type?: string): any; + _request(opts?: any, cb?:any): any; + + get(url?: any, opts?: any, cb?: any): any; + post(url?: any, opts?: any, cb?: any): any; + patch(url?: any, opts?: any, cb?: any): any; + del(url?: any, opts?: any, cb?: any): any; + } + + class StreamRequest extends BaseRequest { + _request(opts: Object): stream.Stream; + + get(url: string, params: Object): stream.Stream; + get(opts: Object): stream.Stream; + get(url: string): stream.Stream; + + post(url: string, params: Object): stream.Stream; + post(opts: Object): stream.Stream; + post(url: string): stream.Stream; + + patch(url: string, params: Object): stream.Stream; + patch(opts: Object): stream.Stream; + patch(url: string): stream.Stream; + + del(url: string, params: Object): stream.Stream; + del(opts: Object): stream.Stream; + del(url: string): stream.Stream; + } + + class CBPromiseRequest extends BaseRequest { + _request(opts: Object): stream.Stream; + + get(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; + get(url: string, cb:(err?:any, resp?: Result) => void): void; + get(opts: Object, cb:(err?:any, resp?: Result) => void): void; + get(url: string, params: Object): Q.Promise; + get(opts: Object): Q.Promise; + get(url: string): Q.Promise; + + post(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; + post(url: string, cb:(err?:any, resp?: Result) => void): void; + post(opts: Object, cb:(err?:any, resp?: Result) => void): void; + post(url: string, params: Object): Q.Promise; + post(opts: Object): Q.Promise; + post(url: string): Q.Promise; + + patch(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; + patch(url: string, cb:(err?:any, resp?: Result) => void): void; + patch(opts: Object, cb:(err?:any, resp?: Result) => void): void; + patch(url: string, params: Object): Q.Promise; + patch(opts: Object): Q.Promise; + patch(url: string): Q.Promise; + + del(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; + del(url: string, cb:(err?:any, resp?: Result) => void): void; + del(opts: Object, cb:(err?:any, resp?: Result) => void): void; + del(url: string, params: Object): Q.Promise; + del(opts: Object): Q.Promise; + del(url: string): Q.Promise; + } + + export interface RequestMaker { + (): CBPromiseRequest; + (stream: boolean): StreamRequest | CBPromiseRequest; + } +} From c5f81c00fba471a648ea6391b3954b620729cb75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Wed, 15 Jul 2015 16:59:26 +0300 Subject: [PATCH 104/416] Fix casing --- easy-api-request/easy-api-request.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/easy-api-request/easy-api-request.d.ts b/easy-api-request/easy-api-request.d.ts index d3152e49d..61bc79142 100644 --- a/easy-api-request/easy-api-request.d.ts +++ b/easy-api-request/easy-api-request.d.ts @@ -3,7 +3,7 @@ // Definitions by: Karl Düüna // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// /// /// /// From db52e392faaadc8de5e6636d23c3d9c615c61632 Mon Sep 17 00:00:00 2001 From: lnlwd Date: Wed, 15 Jul 2015 11:04:10 -0300 Subject: [PATCH 105/416] Correct param types, for parse build --- mongodb/mongodb.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index e4ed2e0c1..ed3fc38c4 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -308,8 +308,8 @@ declare module "mongodb" { insertOne(doc: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMany - insertMany(docs, callback: (err: Error, result: any) => void): void; - insertMany(docs, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + insertMany(docs: any, callback: (err: Error, result: any) => void): void; + insertMany(docs: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; /** * @deprecated use deleteOne or deleteMany * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove @@ -318,12 +318,12 @@ declare module "mongodb" { remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteOne - deleteOne(filter, callback: (err: Error, result: any) => void): void; - deleteOne(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + deleteOne(filter: any, callback: (err: Error, result: any) => void): void; + deleteOne(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteMany - deleteMany(filter, callback: (err: Error, result: any) => void): void; - deleteMany(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + deleteMany(filter: any, callback: (err: Error, result: any) => void): void; + deleteMany(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; rename(newName: String, callback?: (err: Error, result: any) => void): void; From ea103215ea8fa2493325a1b8d2327f47e6a9d6de Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Wed, 15 Jul 2015 16:20:54 +0200 Subject: [PATCH 106/416] Make it possible to initialize a Backbone.Collection from raw objects The following syntax is supported in Backbone, but is currently not compileable in Typescript: var data = [ { id: 1, bar: 'foo' }, { id: 2, bar: 'baz' } ]; var myCollection = new Backbone.Collection(data); As of now, the constructor expects an array of models. I've added the Object[] parameter type, in addition to the TModel[] type to support this syntax. --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5..08cb396b2 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -173,8 +173,8 @@ declare module Backbone { models: TModel[]; length: number; - constructor(models?: TModel[], options?: any); - initialize(models?: TModel[], options?: any): void; + constructor(models?: TModel[] | Object[], options?: any); + initialize(models?: TModel[] | Object[], options?: any): void; fetch(options?: CollectionFetchOptions): JQueryXHR; From 8d9ed6686dca2bcf0b0f5945c1c6c734273acfde Mon Sep 17 00:00:00 2001 From: Michael Nahkies Date: Thu, 16 Jul 2015 09:09:31 +1200 Subject: [PATCH 107/416] Added support for query (docs: https://github.com/pgte/nock#specifying-request-query-string) --- nock/nock-tests.ts | 3 +++ nock/nock.d.ts | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index 00227dfaf..bc936a05b 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -45,6 +45,9 @@ inst = inst.merge(str, data); inst = inst.merge(str, obj); inst = inst.merge(str, regex); +inst = inst.query(obj); +inst = inst.query(bool); + inst = inst.intercept(str, str); inst = inst.intercept(str, str, str); inst = inst.intercept(str, str, obj); diff --git a/nock/nock.d.ts b/nock/nock.d.ts index b6803ca89..3cd92e65a 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -45,6 +45,9 @@ declare module "nock" { merge(path: string, data?: Object): Scope; merge(path: string, regex?: RegExp): Scope; + query(params: any): Scope; + query(acceptAnyParams: boolean): Scope; + intercept(path: string, verb: string, body?: string, options?: any): Scope; intercept(path: string, verb: string, body?: Object, options?: any): Scope; intercept(path: string, verb: string, body?: RegExp, options?: any): Scope; @@ -55,7 +58,7 @@ declare module "nock" { replyWithFile(responseCode: number, fileName: string): Scope; defaultReplyHeaders(headers: Object): Scope; - + matchHeader(name: string, value: string): Scope; matchHeader(name: string, regex: RegExp): Scope; matchHeader(name: string, fn: (value: string) => boolean): Scope; From c8bcc84a58cb2d0b830780d5a564d6c11d565b31 Mon Sep 17 00:00:00 2001 From: PatrickJS Date: Wed, 15 Jul 2015 15:45:26 -0700 Subject: [PATCH 108/416] fix(browserify): missing options in function calls source code shows options object https://github.com/substack/node-browserify/blob/master/index.js#L267 --- browserify/browserify.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index 2289d2165..c301df51e 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -6,7 +6,7 @@ /// interface BrowserifyObject extends NodeJS.EventEmitter { - add(file:string): BrowserifyObject; + add(file:string, opts?:any): BrowserifyObject; require(file:string, opts?:{ expose: string; }): BrowserifyObject; @@ -18,10 +18,10 @@ interface BrowserifyObject extends NodeJS.EventEmitter { insertGlobalVars?: any; }, cb?:(err:any, src:any) => void): NodeJS.ReadableStream; - external(file:string): BrowserifyObject; - ignore(file:string): BrowserifyObject; - transform(tr:string): BrowserifyObject; - transform(tr:Function): BrowserifyObject; + external(file:string, opts?:any): BrowserifyObject; + ignore(file:string, opts?:any): BrowserifyObject; + transform(tr:string, opts?:any): BrowserifyObject; + transform(tr:Function, opts?:any): BrowserifyObject; plugin(plugin:string, opts?:any): BrowserifyObject; plugin(plugin:Function, opts?:any): BrowserifyObject; } From e95209b2433658b056d31d20ca0f8ad9cb7b2209 Mon Sep 17 00:00:00 2001 From: Victor Pineda Gonzalez Date: Wed, 15 Jul 2015 18:03:01 -0500 Subject: [PATCH 109/416] node() function will return DOM Node --- d3/d3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index a5b908cbe..37719a5f4 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -386,7 +386,7 @@ declare module d3 { /** * Returns the first non-null element in the selection, or null otherwise. */ - node(): EventTarget; + node(): Node; /** * Returns the total number of elements in the selection. From 5576e902151dc027bcf308728a46817a7ee4248c Mon Sep 17 00:00:00 2001 From: Arjun Mathur Date: Wed, 15 Jul 2015 16:10:32 -0700 Subject: [PATCH 110/416] Fixed name of variable for browser global context --- deep-diff/deep-diff.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deep-diff/deep-diff.d.ts b/deep-diff/deep-diff.d.ts index 93e99f789..4242731f2 100644 --- a/deep-diff/deep-diff.d.ts +++ b/deep-diff/deep-diff.d.ts @@ -34,7 +34,7 @@ declare module deepDiff { } } -declare var diff: deepDiff.IDeepDiff; +declare var DeepDiff: deepDiff.IDeepDiff; declare module "deep-diff" { var diff: deepDiff.IDeepDiff; From f91aabedc10bb94dd657d550f858af68077bf527 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Wed, 15 Jul 2015 17:08:47 -0700 Subject: [PATCH 111/416] Started bardjs tests; Made some bardjs types more clear. --- bardjs/bardjs-tests.ts | 158 +++++++++++++++++++++++++++++++++++++++++ bardjs/bardjs.d.ts | 6 +- 2 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 bardjs/bardjs-tests.ts diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts new file mode 100644 index 000000000..9243c1008 --- /dev/null +++ b/bardjs/bardjs-tests.ts @@ -0,0 +1,158 @@ +/// +/// +/// +/// +/// + +var expect = chai.expect, assert = chai.assert; + +function someFunction() { } +var someObject = { }; +var myService; + +/* + * bard.$httpBackend + */ +var myService; + +beforeEach(module(bard.$httpBackend, 'app')); + +beforeEach(inject(function(_myService_) { + myService = _myService_; +})); + +it('should return valid data', function(done) { + myService.remoteCall() + .then(function(data) { + expect(data).to.exist; + }) + .then(done, done); + + $rootScope.$apply; // because not using bard.$q, must flush the $http and $q queues +}); + +/* + * bard.$q + */ +beforeEach(module(bard.$q, bard.$httpBackend, 'app')); + +beforeEach(inject(function(_myService_) { + myService = _myService_; +})); + +it('should return valid data', (done) => { + myService.remoteCall() + .then((data) => { + expect(data).to.exist; + }) + .then(done, done); + + // no need to flush +}); + +/* + * bard.addGlobals + */ + +/* + * bard.appModule + */ +beforeEach(bard.appModule('myModule')); + +beforeEach(bard.appModule('myModule', someFunction, someObject)); + +/* + * bard.assertFail + */ + +/* + * bard.asyncModule + */ +beforeEach(bard.asyncModule('app')); + +beforeEach(bard.asyncModule('myModule', someFunction, someObject)); + +/* + * bard.debugging + */ + +/* + * bard.fakeLogger + */ +beforeEach(module('myModule', bard.fakeLogger)); +beforeEach(bard.appModule('myModule', bard.fakeLogger)); +beforeEach(bard.asyncModule('myModule', bard.fakeLogger)); + +/* + * bard.fakeRouteHelperProvider + */ +beforeEach(module('myModule', bard.fakeRouteHelperProvider)); +beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); +beforeEach(bard.asyncModule('myModule', bard.fakeRouteHelperProvider)); + +/* + * bard.fakeRouteProvider + */ +beforeEach(module('myModule', bard.fakeRouteProvider)); +beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); +beforeEach(bard.asyncModule('myModule', bard.fakeRouteProvider)); + +/* + * bard.fakeStateProvider + */ +beforeEach(module('myModule', bard.fakeStateProvider)); +beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); +beforeEach(bard.asyncModule('myModule', bard.fakeStateProvider)); + +/* + * bard.fakeToastr + */ +beforeEach(module('myModule', bard.fakeToastr)); +beforeEach(bard.appModule('myModule', bard.fakeToastr)); +beforeEach(bard.asyncModule('myModule', bard.fakeToastr)); + +/* + * bard.inject + */ +beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice')); + +/* + * bard.log + */ +bard.log('We got the goods'); + +/* + * bard.mochaRunnerListener + */ + +/* + * bard.mockService + */ +var controller; +var avengers = [{name: 'Captain America' /* ... */}]; +var $controller, $q, $rootScope, dataservice; + +beforeEach(function() { + bard.appModule('app.avengers'); + bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice'); + + bard.mockService(dataservice, { + getAvengers: $q.when(avengers), + _default: $q.when([]) + }); + + controller = $controller('Avengers'); + $rootScope.$apply(); +}); + +/* + * bard.replaceAccentChars + */ + +/* + * bard.verifyNoOutstandingHttpRequests + */ + +/* + * bard.wrapWithDone + */ diff --git a/bardjs/bardjs.d.ts b/bardjs/bardjs.d.ts index e0288825f..3d3ad5f22 100644 --- a/bardjs/bardjs.d.ts +++ b/bardjs/bardjs.d.ts @@ -47,7 +47,7 @@ declare module bard { * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES! * Fall back to `angular.mock.module(...)` or just `module(...)` */ - function appModule(...args: any[]): any; + function appModule(...fns: (string | Function | Object)[]): () => void; /** * Assert a failure in mocha, without condition @@ -59,7 +59,7 @@ declare module bard { * Also adds fakeLogger to the end of the definition * Use it as you would the ngMocks#module method */ - function asyncModule(...args: any[]): any; + function asyncModule(...fns: (string | Function | Object)[]): () => void; /** * Get or set bard debugging flag @@ -114,7 +114,7 @@ declare module bard { * [strings] - same string array you'd use to set fn.$inject * (...string) - string arguments turned into a string array */ - function inject(context?: any, ...args: string[]): void; + function inject(context?: Function, ...args: string[]): void; /** * Write to console if bard debugging flag is on From e28aef1c025ec1f6377cc1a4cbba5ac256e8840a Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Wed, 15 Jul 2015 21:35:55 -0700 Subject: [PATCH 112/416] Fixed some issues with bard tests --- bardjs/bardjs-tests.ts | 372 +++++++++++++++++++++++++---------------- 1 file changed, 226 insertions(+), 146 deletions(-) diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index 9243c1008..d15cc3d18 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -4,155 +4,235 @@ /// /// -var expect = chai.expect, assert = chai.assert; +var expect = chai.expect, + assert = chai.assert; -function someFunction() { } -var someObject = { }; -var myService; - -/* - * bard.$httpBackend - */ -var myService; - -beforeEach(module(bard.$httpBackend, 'app')); - -beforeEach(inject(function(_myService_) { - myService = _myService_; -})); - -it('should return valid data', function(done) { - myService.remoteCall() - .then(function(data) { - expect(data).to.exist; - }) - .then(done, done); - - $rootScope.$apply; // because not using bard.$q, must flush the $http and $q queues -}); - -/* - * bard.$q - */ -beforeEach(module(bard.$q, bard.$httpBackend, 'app')); - -beforeEach(inject(function(_myService_) { - myService = _myService_; -})); - -it('should return valid data', (done) => { - myService.remoteCall() - .then((data) => { - expect(data).to.exist; - }) - .then(done, done); - - // no need to flush -}); - -/* - * bard.addGlobals - */ - -/* - * bard.appModule - */ -beforeEach(bard.appModule('myModule')); - -beforeEach(bard.appModule('myModule', someFunction, someObject)); - -/* - * bard.assertFail - */ - -/* - * bard.asyncModule - */ -beforeEach(bard.asyncModule('app')); - -beforeEach(bard.asyncModule('myModule', someFunction, someObject)); - -/* - * bard.debugging - */ - -/* - * bard.fakeLogger - */ -beforeEach(module('myModule', bard.fakeLogger)); -beforeEach(bard.appModule('myModule', bard.fakeLogger)); -beforeEach(bard.asyncModule('myModule', bard.fakeLogger)); - -/* - * bard.fakeRouteHelperProvider - */ -beforeEach(module('myModule', bard.fakeRouteHelperProvider)); -beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); -beforeEach(bard.asyncModule('myModule', bard.fakeRouteHelperProvider)); - -/* - * bard.fakeRouteProvider - */ -beforeEach(module('myModule', bard.fakeRouteProvider)); -beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); -beforeEach(bard.asyncModule('myModule', bard.fakeRouteProvider)); - -/* - * bard.fakeStateProvider - */ -beforeEach(module('myModule', bard.fakeStateProvider)); -beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); -beforeEach(bard.asyncModule('myModule', bard.fakeStateProvider)); - -/* - * bard.fakeToastr - */ -beforeEach(module('myModule', bard.fakeToastr)); -beforeEach(bard.appModule('myModule', bard.fakeToastr)); -beforeEach(bard.asyncModule('myModule', bard.fakeToastr)); - -/* - * bard.inject - */ -beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice')); - -/* - * bard.log - */ -bard.log('We got the goods'); - -/* - * bard.mochaRunnerListener - */ - -/* - * bard.mockService - */ -var controller; -var avengers = [{name: 'Captain America' /* ... */}]; -var $controller, $q, $rootScope, dataservice; - -beforeEach(function() { - bard.appModule('app.avengers'); - bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice'); - - bard.mockService(dataservice, { - getAvengers: $q.when(avengers), - _default: $q.when([]) +class MyService { + static $inject = ['$q']; + + constructor(private $q: angular.IQService) {} + + remoteCall(): angular.IPromise { + return new this.$q((resolve, reject) => { + resolve('Here is some data'); }); + } +} - controller = $controller('Avengers'); - $rootScope.$apply(); -}); +function myService($q: angular.IQService) { + return new MyService($q); +} -/* - * bard.replaceAccentChars - */ +angular + .module('tests') + .service('myService', myService); -/* - * bard.verifyNoOutstandingHttpRequests - */ -/* - * bard.wrapWithDone - */ + +module bardTests { + /* + * bard.$httpBackend + */ + function test_$httpBackend() { + var myService: MyService; + var $rootScope: any; + + beforeEach(module(bard.$httpBackend, 'app')); + + beforeEach(inject(function(_myService_: MyService, _$rootScope_: any) { + myService = _myService_; + $rootScope = _$rootScope_; + })); + + it('should return valid data', function(done) { + myService.remoteCall() + .then(function(data) { + expect(data).to.exist; + }) + .then(done, done); + + $rootScope.$apply; // because not using bard.$q, must flush the $http and $q queues + }); + } + + /* + * bard.$q + */ + function test_$q() { + var myService: MyService; + + beforeEach(module(bard.$q, bard.$httpBackend, 'app')); + + beforeEach(inject(function(_myService_) { + myService = _myService_; + })); + + it('should return valid data', (done) => { + myService.remoteCall() + .then((data) => { + expect(data).to.exist; + }) + .then(done, done); + + // no need to flush + }); + } + + /* + * bard.addGlobals + */ + function test_addGlobals() { + + } + + /* + * bard.appModule + */ + function test_appModule() { + beforeEach(bard.appModule('myModule')); + //// + beforeEach(bard.appModule('myModule', function() {}, {})); + } + + /* + * bard.assertFail + */ + function test_assertFail() { + + } + + /* + * bard.asyncModule + */ + function test_asyncModule() { + beforeEach(bard.asyncModule('app')); + //// + beforeEach(bard.asyncModule('myModule', function() {}, {})); + } + + /* + * bard.debugging + */ + function test_debugging() { + + } + + /* + * bard.fakeLogger + */ + function test_fakeLogger() { + beforeEach(module('myModule', bard.fakeLogger)); + //// + beforeEach(bard.appModule('myModule', bard.fakeLogger)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeLogger)); + } + + /* + * bard.fakeRouteHelperProvider + */ + function test_fakeRouteHelperProvider() { + beforeEach(module('myModule', bard.fakeRouteHelperProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeRouteHelperProvider)); + } + + /* + * bard.fakeRouteProvider + */ + function test_fakeRouteProvider() { + beforeEach(module('myModule', bard.fakeRouteProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeRouteProvider)); + } + + /* + * bard.fakeStateProvider + */ + function test_fakeStateProvider() { + beforeEach(module('myModule', bard.fakeStateProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeStateProvider)); + } + + /* + * bard.fakeToastr + */ + function test_fakeToastr() { + beforeEach(module('myModule', bard.fakeToastr)); + //// + beforeEach(bard.appModule('myModule', bard.fakeToastr)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeToastr)); + } + + /* + * bard.inject + */ + function test_inject() { + beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice')); + } + + /* + * bard.log + */ + function test_log() { + bard.log('We got the goods'); + } + + /* + * bard.mochaRunnerListener + */ + function test_mochaRunnerListener() { + + } + + /* + * bard.mockService + */ + function test_mockService() { + var controller; + var avengers = [{name: 'Captain America' /* ... */}]; + var $controller, $q, $rootScope, dataservice; + + beforeEach(function() { + bard.appModule('app.avengers'); + bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice'); + + bard.mockService(dataservice, { + getAvengers: $q.when(avengers), + _default: $q.when([]) + }); + + controller = $controller('Avengers'); + $rootScope.$apply(); + }); + } + + /* + * bard.replaceAccentChars + */ + function test_replaceAccentChars() { + + } + + /* + * bard.verifyNoOutstandingHttpRequests + */ + function test_verifyNoOutstandingHttpRequests() { + + } + + /* + * bard.wrapWithDone + */ + function test_wrapWithDone() { + + } +} \ No newline at end of file From e80350d66819f909e50bbccef3e74f6205fb95a6 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Wed, 15 Jul 2015 21:51:59 -0700 Subject: [PATCH 113/416] Fixed some bardjs implicit 'any' types --- bardjs/bardjs-tests.ts | 67 +++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index d15cc3d18..8083fd3f2 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -4,42 +4,40 @@ /// /// -var expect = chai.expect, - assert = chai.assert; - -class MyService { - static $inject = ['$q']; - - constructor(private $q: angular.IQService) {} - - remoteCall(): angular.IPromise { - return new this.$q((resolve, reject) => { - resolve('Here is some data'); - }); - } -} - -function myService($q: angular.IQService) { - return new MyService($q); -} - -angular - .module('tests') - .service('myService', myService); - - - module bardTests { + var expect = chai.expect, + assert = chai.assert; + + class MyService { + static $inject = ['$q']; + + constructor(private $q: angular.IQService) {} + + remoteCall(): angular.IPromise { + return new this.$q((resolve, reject) => { + resolve(['Hello', 'World']); + }); + } + } + + function myService($q: angular.IQService) { + return new MyService($q); + } + + angular + .module('bardTests') + .service('myService', myService); + /* * bard.$httpBackend */ function test_$httpBackend() { var myService: MyService; - var $rootScope: any; + var $rootScope: angular.IRootScopeService; beforeEach(module(bard.$httpBackend, 'app')); - beforeEach(inject(function(_myService_: MyService, _$rootScope_: any) { + beforeEach(inject(function(_myService_: MyService, _$rootScope_: angular.IRootScopeService) { myService = _myService_; $rootScope = _$rootScope_; })); @@ -51,7 +49,7 @@ module bardTests { }) .then(done, done); - $rootScope.$apply; // because not using bard.$q, must flush the $http and $q queues + $rootScope.$apply; // Because not using bard.$q, must flush the $http and $q queues }); } @@ -63,7 +61,7 @@ module bardTests { beforeEach(module(bard.$q, bard.$httpBackend, 'app')); - beforeEach(inject(function(_myService_) { + beforeEach(inject(function(_myService_: MyService) { myService = _myService_; })); @@ -74,7 +72,7 @@ module bardTests { }) .then(done, done); - // no need to flush + // No need to flush }); } @@ -176,7 +174,7 @@ module bardTests { * bard.inject */ function test_inject() { - beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice')); + beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'myService')); } /* @@ -199,11 +197,14 @@ module bardTests { function test_mockService() { var controller; var avengers = [{name: 'Captain America' /* ... */}]; - var $controller, $q, $rootScope, dataservice; + var $controller: angular.IControllerService, + $q: angular.IQService, + $rootScope: angular.IRootScopeService, + myService: MyService; beforeEach(function() { bard.appModule('app.avengers'); - bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice'); + bard.inject(this, '$controller', '$q', '$rootScope', 'myService'); bard.mockService(dataservice, { getAvengers: $q.when(avengers), From 6de3f1f79c3470d02f41f9319839879c74b1328b Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Wed, 15 Jul 2015 22:19:10 -0700 Subject: [PATCH 114/416] Added more tests to bardjs-tests.ts --- bardjs/bardjs-tests.ts | 462 ++++++++++++++++++++++------------------- 1 file changed, 253 insertions(+), 209 deletions(-) diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index 8083fd3f2..3eedd970b 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -5,235 +5,279 @@ /// module bardTests { - var expect = chai.expect, - assert = chai.assert; + var expect = chai.expect, + assert = chai.assert; - class MyService { - static $inject = ['$q']; + class MyService { + static $inject = ['$q']; - constructor(private $q: angular.IQService) {} + constructor(private $q: angular.IQService) {} - remoteCall(): angular.IPromise { - return new this.$q((resolve, reject) => { - resolve(['Hello', 'World']); - }); + remoteCall(): angular.IPromise { + return new this.$q((resolve, reject) => { + resolve(['Hello', 'World']); + }); + } } - } - function myService($q: angular.IQService) { - return new MyService($q); - } + function myService($q: angular.IQService) { + return new MyService($q); + } - angular - .module('bardTests') - .service('myService', myService); + class MyController { + myProperty: string; + } - /* - * bard.$httpBackend - */ - function test_$httpBackend() { - var myService: MyService; - var $rootScope: angular.IRootScopeService; + angular + .module('myModule') + .service('myService', myService) + .controller('MyController', MyController); - beforeEach(module(bard.$httpBackend, 'app')); + /* + * bard.$httpBackend + */ + function test_$httpBackend() { + var myService: MyService; + var $rootScope: angular.IRootScopeService; - beforeEach(inject(function(_myService_: MyService, _$rootScope_: angular.IRootScopeService) { - myService = _myService_; - $rootScope = _$rootScope_; - })); + beforeEach(module(bard.$httpBackend, 'myModule')); - it('should return valid data', function(done) { - myService.remoteCall() - .then(function(data) { - expect(data).to.exist; + beforeEach(inject(function(_myService_: MyService, _$rootScope_: angular.IRootScopeService) { + myService = _myService_; + $rootScope = _$rootScope_; + })); + + it('should return valid data', function(done) { + myService.remoteCall() + .then(function(data) { + expect(data).to.exist; + }) + .then(done, done); + + $rootScope.$apply; // Because not using bard.$q, must flush the $http and $q queues + }); + } + + /* + * bard.$q + */ + function test_$q() { + var myService: MyService; + + beforeEach(module(bard.$q, bard.$httpBackend, 'myModule')); + + beforeEach(inject(function(_myService_: MyService) { + myService = _myService_; + })); + + it('should return valid data', (done) => { + myService.remoteCall() + .then((data) => { + expect(data).to.exist; + }) + .then(done, done); + + // No need to flush + }); + } + + /* + * bard.addGlobals + */ + function test_addGlobals() { + describe('someting', function() { + var ctx = this; + + it('should work', function() { + var bar = 'bar'; + bard.addGlobals(this, 'foo'); // where `this` is the spec context + bard.addGlobals(this, 'foo', bar); + bard.addGlobals.bind(this)('foo', 'bar'); + bard.addGlobals(ctx, ['foo', 'bar']) // where ctx is the spec context + }); }) - .then(done, done); + } - $rootScope.$apply; // Because not using bard.$q, must flush the $http and $q queues - }); - } - - /* - * bard.$q - */ - function test_$q() { - var myService: MyService; + /* + * bard.appModule + */ + function test_appModule() { + beforeEach(bard.appModule('myModule')); + //// + beforeEach(bard.appModule('myModule', function() {}, {})); + } - beforeEach(module(bard.$q, bard.$httpBackend, 'app')); + /* + * bard.assertFail + */ + function test_assertFail() { + bard.assertFail('FAIL!'); + } - beforeEach(inject(function(_myService_: MyService) { - myService = _myService_; - })); + /* + * bard.asyncModule + */ + function test_asyncModule() { + beforeEach(bard.asyncModule('myModule')); + //// + beforeEach(bard.asyncModule('myModule', function() {}, {})); + } - it('should return valid data', (done) => { - myService.remoteCall() - .then((data) => { - expect(data).to.exist; - }) - .then(done, done); + /* + * bard.debugging + */ + function test_debugging() { + console.log( + bard.debugging(true), // should be true + bard.debugging(false), // should be false + bard.debugging(42), // should be true + bard.debugging(''), // should be false + bard.debugging() // should be false + ); + } - // No need to flush - }); - } - - /* - * bard.addGlobals - */ - function test_addGlobals() { - - } + /* + * bard.fakeLogger + */ + function test_fakeLogger() { + beforeEach(module('myModule', bard.fakeLogger)); + //// + beforeEach(bard.appModule('myModule', bard.fakeLogger)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeLogger)); + } - /* - * bard.appModule - */ - function test_appModule() { - beforeEach(bard.appModule('myModule')); - //// - beforeEach(bard.appModule('myModule', function() {}, {})); - } + /* + * bard.fakeRouteHelperProvider + */ + function test_fakeRouteHelperProvider() { + beforeEach(module('myModule', bard.fakeRouteHelperProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeRouteHelperProvider)); + } - /* - * bard.assertFail - */ - function test_assertFail() { - - } + /* + * bard.fakeRouteProvider + */ + function test_fakeRouteProvider() { + beforeEach(module('myModule', bard.fakeRouteProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeRouteProvider)); + } - /* - * bard.asyncModule - */ - function test_asyncModule() { - beforeEach(bard.asyncModule('app')); - //// - beforeEach(bard.asyncModule('myModule', function() {}, {})); - } - - /* - * bard.debugging - */ - function test_debugging() { - - } - - /* - * bard.fakeLogger - */ - function test_fakeLogger() { - beforeEach(module('myModule', bard.fakeLogger)); - //// - beforeEach(bard.appModule('myModule', bard.fakeLogger)); - //// - beforeEach(bard.asyncModule('myModule', bard.fakeLogger)); - } - - /* - * bard.fakeRouteHelperProvider - */ - function test_fakeRouteHelperProvider() { - beforeEach(module('myModule', bard.fakeRouteHelperProvider)); - //// - beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); - //// - beforeEach(bard.asyncModule('myModule', bard.fakeRouteHelperProvider)); - } - - /* - * bard.fakeRouteProvider - */ - function test_fakeRouteProvider() { - beforeEach(module('myModule', bard.fakeRouteProvider)); - //// - beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); - //// - beforeEach(bard.asyncModule('myModule', bard.fakeRouteProvider)); - } - - /* - * bard.fakeStateProvider - */ - function test_fakeStateProvider() { - beforeEach(module('myModule', bard.fakeStateProvider)); - //// - beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); - //// - beforeEach(bard.asyncModule('myModule', bard.fakeStateProvider)); - } - - /* - * bard.fakeToastr - */ - function test_fakeToastr() { - beforeEach(module('myModule', bard.fakeToastr)); - //// - beforeEach(bard.appModule('myModule', bard.fakeToastr)); - //// - beforeEach(bard.asyncModule('myModule', bard.fakeToastr)); - } - - /* - * bard.inject - */ - function test_inject() { - beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'myService')); - } - - /* - * bard.log - */ - function test_log() { - bard.log('We got the goods'); - } - - /* - * bard.mochaRunnerListener - */ - function test_mochaRunnerListener() { - - } - - /* - * bard.mockService - */ - function test_mockService() { - var controller; - var avengers = [{name: 'Captain America' /* ... */}]; - var $controller: angular.IControllerService, - $q: angular.IQService, - $rootScope: angular.IRootScopeService, - myService: MyService; + /* + * bard.fakeStateProvider + */ + function test_fakeStateProvider() { + beforeEach(module('myModule', bard.fakeStateProvider)); + //// + beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeStateProvider)); + } - beforeEach(function() { - bard.appModule('app.avengers'); - bard.inject(this, '$controller', '$q', '$rootScope', 'myService'); + /* + * bard.fakeToastr + */ + function test_fakeToastr() { + beforeEach(module('myModule', bard.fakeToastr)); + //// + beforeEach(bard.appModule('myModule', bard.fakeToastr)); + //// + beforeEach(bard.asyncModule('myModule', bard.fakeToastr)); + } - bard.mockService(dataservice, { - getAvengers: $q.when(avengers), - _default: $q.when([]) - }); + /* + * bard.inject + */ + function test_inject() { + beforeEach(() => bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'myService')); + } - controller = $controller('Avengers'); - $rootScope.$apply(); - }); - } - - /* - * bard.replaceAccentChars - */ - function test_replaceAccentChars() { - - } - - /* - * bard.verifyNoOutstandingHttpRequests - */ - function test_verifyNoOutstandingHttpRequests() { - - } - - /* - * bard.wrapWithDone - */ - function test_wrapWithDone() { - - } + /* + * bard.log + */ + function test_log() { + bard.log('We got the goods'); + } + + /* + * bard.mochaRunnerListener + */ + function test_mochaRunnerListener() { + var runner = mocha.run(); + bard.mochaRunnerListener(runner); + } + + /* + * bard.mockService + */ + function test_mockService() { + var controller: MyController, + myArray = ['This', 'is', 'some', 'mocked', 'data']; + var $controller: angular.IControllerService, + $q: angular.IQService, + $rootScope: angular.IRootScopeService, + myService: MyService; + + beforeEach(function() { + bard.appModule('myModule'); + bard.inject(this, '$controller', '$q', '$rootScope', 'myService'); + + bard.mockService(myService, { + remoteCall: $q.when(myArray), + _default: $q.when([]) + }); + + controller = $controller('MyController'); + $rootScope.$apply(); + }); + } + + /* + * bard.replaceAccentChars + */ + function test_replaceAccentChars() { + console.log(bard.replaceAccentChars('àáâãäåèéêëìíîïòóôõöùúûüýÿ') === 'aaaaaaeeeeeeeeooooouuuuyy'); + } + + /* + * bard.verifyNoOutstandingHttpRequests + */ + function test_verifyNoOutstandingHttpRequests() { + var controller: MyController, + myArray = ['This', 'is', 'some', 'mocked', 'data']; + var $controller: angular.IControllerService, + $q: angular.IQService, + $rootScope: angular.IRootScopeService, + myService: MyService; + + beforeEach(function() { + bard.appModule('myModule'); + bard.inject(this, '$controller', '$q', '$rootScope', 'myService'); + + bard.mockService(myService, { + remoteCall: $q.when(myArray), + _default: $q.when([]) + }); + + controller = $controller('MyController'); + $rootScope.$apply(); + }); + + bard.verifyNoOutstandingHttpRequests(); + } + + /* + * bard.wrapWithDone + */ + function test_wrapWithDone() { + function callback() { console.log('Doing something...'); } + function done() { console.log('...Done'); } + bard.wrapWithDone(callback, done); + } } \ No newline at end of file From 3cf112bb6b9d85b9b931f8ff575b5ba3b10ed747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 12:14:45 +0300 Subject: [PATCH 115/416] Easy-x-headers --- easy-x-headers/easy-x-headers-tests.ts | 16 ++++++++++++++++ easy-x-headers/easy-x-headers.d.ts | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 easy-x-headers/easy-x-headers-tests.ts create mode 100644 easy-x-headers/easy-x-headers.d.ts diff --git a/easy-x-headers/easy-x-headers-tests.ts b/easy-x-headers/easy-x-headers-tests.ts new file mode 100644 index 000000000..9a306ea6a --- /dev/null +++ b/easy-x-headers/easy-x-headers-tests.ts @@ -0,0 +1,16 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// + +import express = require('express'); +import xHeaders = require('easy-x-headers'); + +var app = express(); +app.use(xHeaders.getMiddleware()); + +app.get('/', function (req, res) { + res.json(req.info); +}); diff --git a/easy-x-headers/easy-x-headers.d.ts b/easy-x-headers/easy-x-headers.d.ts new file mode 100644 index 000000000..c0a13d1a8 --- /dev/null +++ b/easy-x-headers/easy-x-headers.d.ts @@ -0,0 +1,18 @@ +// Type definitions for easy-x-headers +// Project: https://github.com/DeadAlready/easy-x-headers +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + info: any; + } +} + +declare module "easy-x-headers" { + import express = require('express'); + + export function getMiddleware(): express.RequestHandler; +} From d79fffd2221b23cf286c668b0be7180c8b586954 Mon Sep 17 00:00:00 2001 From: Alwin Schoemaker Date: Thu, 16 Jul 2015 12:00:21 +0200 Subject: [PATCH 116/416] Added content param for IToastService.showSimple() This param was missing in the interface, but [according to the doc](https://github.com/angular/material/blob/master/src/components/toast/toast.js#L49) without it, it's rather useless. --- angular-material/angular-material.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 17f8328e1..aba83a86f 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -144,7 +144,7 @@ declare module angular.material { interface IToastService { show(optionsOrPreset: IToastOptions|IToastPreset): angular.IPromise; - showSimple(): angular.IPromise; + showSimple(content: string): angular.IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; updateContent(): void; From abb3f318b878ba5277212e75284ccc3412d871bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 13:07:49 +0300 Subject: [PATCH 117/416] easy-xapi-supertest --- .../easy-xapi-supertest-tests.ts | 27 +++++++++++++++++ easy-xapi-supertest/easy-xapi-supertest.d.ts | 29 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 easy-xapi-supertest/easy-xapi-supertest-tests.ts create mode 100644 easy-xapi-supertest/easy-xapi-supertest.d.ts diff --git a/easy-xapi-supertest/easy-xapi-supertest-tests.ts b/easy-xapi-supertest/easy-xapi-supertest-tests.ts new file mode 100644 index 000000000..5b43ce061 --- /dev/null +++ b/easy-xapi-supertest/easy-xapi-supertest-tests.ts @@ -0,0 +1,27 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// + +import express = require('express'); +import eSupertest = require('easy-xapi-supertest'); + +var app = express(); + +var getAgent = eSupertest.getAgentFactory(app); + +var agent = getAgent({ + user: 'Jack', + role: 'user' +}); + +var getAgent2 = eSupertest.getAgentFactory(app, function (user:string, role?:string) { + return { + user: user, + role: role || 'user' + } +}); + +var agent = getAgent2('Jack'); diff --git a/easy-xapi-supertest/easy-xapi-supertest.d.ts b/easy-xapi-supertest/easy-xapi-supertest.d.ts new file mode 100644 index 000000000..4ea936976 --- /dev/null +++ b/easy-xapi-supertest/easy-xapi-supertest.d.ts @@ -0,0 +1,29 @@ +// Type definitions for easy-x-headers +// Project: https://github.com/DeadAlready/easy-x-headers +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "easy-xapi-supertest" { + import express = require('express'); + + export interface BodyAgent { + send(data: Object): any; + attach(arg1: any, arg2?: any): any; + } + + export interface Agent { + get(url:string): any; + delete(url:string): any; + post(url:string): BodyAgent; + patch(url:string): BodyAgent; + put(url:string): BodyAgent; + } + + interface getAgent { + (...args:any[]): Agent + } + + export function getAgentFactory(app: express.Application, transform?: Function): getAgent; +} From 9d04a7b772d8ba7afc37f1e93a8e1bd9d3fbedf1 Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Sun, 5 Jul 2015 13:16:47 +0900 Subject: [PATCH 118/416] add webvr-api definition --- webvr-api/webvr-api-test.ts | 62 +++++++++++++ webvr-api/webvr-api.d.ts | 175 ++++++++++++++++++++++++++++++++++++ 2 files changed, 237 insertions(+) create mode 100644 webvr-api/webvr-api-test.ts create mode 100644 webvr-api/webvr-api.d.ts diff --git a/webvr-api/webvr-api-test.ts b/webvr-api/webvr-api-test.ts new file mode 100644 index 000000000..df2a72438 --- /dev/null +++ b/webvr-api/webvr-api-test.ts @@ -0,0 +1,62 @@ +/// + +function fieldOfViewToProjectionMatrix(fov: WebVRApi.VRFieldOfView, zNear: number, zFar: number) { + var upTan = Math.tan(fov.upDegrees * Math.PI/180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI/180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + + var out = new Float32Array(16); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = ((upTan - downTan) * yScale * 0.5); + out[10] = -(zNear + zFar) / (zFar - zNear); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = -(2.0 * zFar * zNear) / (zFar - zNear); + out[15] = 0.0; + + return out; +} + +var hmd: HMDVRDevice; +var leftEyeParams = hmd.getEyeParameters("left"); +var rightEyeParams = hmd.getEyeParameters("right"); +var leftEyeRect = leftEyeParams.renderRect; +var rightEyeRect = rightEyeParams.renderRect; + +var canvas: HTMLCanvasElement; +canvas.width = rightEyeRect.x + rightEyeRect.width; +canvas.height = Math.max(leftEyeRect.y + leftEyeRect.height, rightEyeRect.y + rightEyeRect.height); + +var gHMD: WebVRApi.VRDevice; +var gPositionSensor: WebVRApi.VRDevice; + +navigator.getVRDevices().then(function(devices) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof HMDVRDevice) { + gHMD = devices[i]; + break; + } + } + + if (gHMD) { + for (var i = 0; i < devices.length; ++i) { + if (devices[i] instanceof PositionSensorVRDevice && + devices[i].hardwareUnitId == gHMD.hardwareUnitId) { + gPositionSensor = devices[i]; + break; + } + } + } +}); diff --git a/webvr-api/webvr-api.d.ts b/webvr-api/webvr-api.d.ts new file mode 100644 index 000000000..16918cf30 --- /dev/null +++ b/webvr-api/webvr-api.d.ts @@ -0,0 +1,175 @@ +// Type definitions for WebVR API +// Project: http://mozvr.github.io/webvr-spec/webvr.html +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare type VREye = string; + +declare module WebVRApi { + export interface VRFieldOfViewReadOnly { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfViewInit { + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRFieldOfView extends VRFieldOfViewReadOnly { + constructor(upDegrees:number, rightDegrees:number, downDegrees:number, leftDegrees:number): VRFieldOfView; + upDegrees: number; + rightDegrees: number; + downDegrees: number; + leftDegrees: number; + } + + export interface VRPositionState { + /** + * Monotonically increasing value that allows the author to determine if position state data been updated from the hardware. + */ + timeStamp: number; + /** + * True if the position attribute is valid. If false position MUST be null. + */ + hasPosition: boolean; + /** + * Position of the sensor at timeStamp as a 3D vector. + */ + position?: GeometryDom.DOMPoint; + /** + * Linear velocity of the sensor at timeStamp. + */ + linearVelocity?: GeometryDom.DOMPoint; + /** + * Linear acceleration of the sensor at timeStamp. + */ + linearAcceleration?: GeometryDom.DOMPoint; + /** + * True if the orientation attribute is valid. If false orientation MUST be null. + */ + hasOrientation: boolean; + /** + * Orientation of the sensor at timeStamp as a quaternion. + */ + orientation?: GeometryDom.DOMPoint; + /** + * Angular velocity of the sensor at timeStamp. + */ + angularVelocity?: GeometryDom.DOMPoint; + /** + * Angular acceleration of the sensor at timeStamp. + */ + angularAcceleration?: GeometryDom.DOMPoint; + } + + export interface VREyeParameters { + /** + * Describes the minimum supported field of view for the eye. + */ + minimumFieldOfView: VRFieldOfView; + /** + * Describes the maximum supported field of view for the eye. + */ + maximumFieldOfView: VRFieldOfView; + /** + * Describes the recommended field of view for the eye. + */ + recommendedFieldOfView: VRFieldOfView; + /** + * Offset from the center of the users head to the eye in meters. + */ + eyeTranslation: GeometryDom.DOMPoint; + /** + * The current field of view for the eye, as specified by setFieldOfView. + */ + currentFieldOfView: VRFieldOfView; + /** + * Describes the viewport of a canvas into which visuals for this eye should be rendered. + */ + renderRect: GeometryDom.DOMRect; + } + + export interface VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + } +} + +declare class HMDVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return the current VREyeParameters for the given eye. + */ + getEyeParameters(whichEye: VREye): WebVRApi.VREyeParameters; + /** + * Set the field of view for both eyes. If + */ + setFieldOfView(leftFOV?: WebVRApi.VRFieldOfViewInit, rightFOV?: WebVRApi.VRFieldOfViewInit, zNear?: number, zFar?: number): void; +} + +declare class PositionSensorVRDevice implements WebVRApi.VRDevice { + /** + * An identifier for the distinct hardware unit that this VRDevice is a part of. + */ + hardwareUnitId: string; + /** + * An identifier for this distinct sensor/device on a physical hardware device. + */ + deviceId: string; + /** + * A user-readable name identifying the device. + */ + deviceName: string; + + /** + * Return a VRPositionState dictionary containing the state of this position sensor state for the current frame (if within a requestAnimationFrame context) or for the previous frame. + */ + getState(): WebVRApi.VRPositionState; + /** + * Return the current instantaneous sensor state. + */ + getImmediateState(): WebVRApi.VRPositionState; + + /** + * Reset this sensor, treating its current position and orientation yaw as the "origin/zero" values. + */ + resetSensor(): void; +} + +interface Navigator { + /** + * Return a Promise which resolves to a list of available VRDevices. + */ + getVRDevices(): Promise>; +} + From af4db82d97e862205afc10efd11ea77e2169889c Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Thu, 16 Jul 2015 19:18:30 +0900 Subject: [PATCH 119/416] rename webvr-api-test --- webvr-api/{webvr-api-test.ts => webvr-api-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename webvr-api/{webvr-api-test.ts => webvr-api-tests.ts} (100%) diff --git a/webvr-api/webvr-api-test.ts b/webvr-api/webvr-api-tests.ts similarity index 100% rename from webvr-api/webvr-api-test.ts rename to webvr-api/webvr-api-tests.ts From 14e024237bd6c4f346ee43941366d537faf2eede Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Thu, 16 Jul 2015 19:23:42 +0900 Subject: [PATCH 120/416] remove garbage --- webvr-api/webvr-api-test.ts | 62 ------------------------------------- 1 file changed, 62 deletions(-) delete mode 100644 webvr-api/webvr-api-test.ts diff --git a/webvr-api/webvr-api-test.ts b/webvr-api/webvr-api-test.ts deleted file mode 100644 index df2a72438..000000000 --- a/webvr-api/webvr-api-test.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -function fieldOfViewToProjectionMatrix(fov: WebVRApi.VRFieldOfView, zNear: number, zFar: number) { - var upTan = Math.tan(fov.upDegrees * Math.PI/180.0); - var downTan = Math.tan(fov.downDegrees * Math.PI/180.0); - var leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0); - var rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0); - var xScale = 2.0 / (leftTan + rightTan); - var yScale = 2.0 / (upTan + downTan); - - var out = new Float32Array(16); - out[0] = xScale; - out[1] = 0.0; - out[2] = 0.0; - out[3] = 0.0; - out[4] = 0.0; - out[5] = yScale; - out[6] = 0.0; - out[7] = 0.0; - out[8] = -((leftTan - rightTan) * xScale * 0.5); - out[9] = ((upTan - downTan) * yScale * 0.5); - out[10] = -(zNear + zFar) / (zFar - zNear); - out[11] = -1.0; - out[12] = 0.0; - out[13] = 0.0; - out[14] = -(2.0 * zFar * zNear) / (zFar - zNear); - out[15] = 0.0; - - return out; -} - -var hmd: HMDVRDevice; -var leftEyeParams = hmd.getEyeParameters("left"); -var rightEyeParams = hmd.getEyeParameters("right"); -var leftEyeRect = leftEyeParams.renderRect; -var rightEyeRect = rightEyeParams.renderRect; - -var canvas: HTMLCanvasElement; -canvas.width = rightEyeRect.x + rightEyeRect.width; -canvas.height = Math.max(leftEyeRect.y + leftEyeRect.height, rightEyeRect.y + rightEyeRect.height); - -var gHMD: WebVRApi.VRDevice; -var gPositionSensor: WebVRApi.VRDevice; - -navigator.getVRDevices().then(function(devices) { - for (var i = 0; i < devices.length; ++i) { - if (devices[i] instanceof HMDVRDevice) { - gHMD = devices[i]; - break; - } - } - - if (gHMD) { - for (var i = 0; i < devices.length; ++i) { - if (devices[i] instanceof PositionSensorVRDevice && - devices[i].hardwareUnitId == gHMD.hardwareUnitId) { - gPositionSensor = devices[i]; - break; - } - } - } -}); From b00376da53018decfb4119c53fec46205fd91017 Mon Sep 17 00:00:00 2001 From: Toshiya Nakakura Date: Thu, 16 Jul 2015 19:48:28 +0900 Subject: [PATCH 121/416] add skyway definition --- skyway/skyway-tests.ts | 51 ++++++++++++ skyway/skyway.d.ts | 184 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 skyway/skyway-tests.ts create mode 100644 skyway/skyway.d.ts diff --git a/skyway/skyway-tests.ts b/skyway/skyway-tests.ts new file mode 100644 index 000000000..a7eced27d --- /dev/null +++ b/skyway/skyway-tests.ts @@ -0,0 +1,51 @@ +/// +/// + +var peerByOption: PeerJs.Peer = new Peer({ + key: 'peerKey', + debug: 3, + logFunction: ()=>{ + } +}); + +peerByOption.listAllPeers(function(items){ + for(var i in items){ + console.log(decodeURI(items[i])); + } +}); + +var peerById: PeerJs.Peer = new Peer("peerid"); + +var peerByIdAndOption: PeerJs.Peer = new Peer( + "peerId", + { + key: 'peerKey', + debug: 3, + logFunction: ()=>{ + } + }); + +var id = peerByOption.id; +var connections = peerByOption.connections; +var flag = peerByOption.disconnected; +flag = peerByOption.destroyed; + +peerByOption.disconnect(); +peerByOption.destroy(); + +var connection = peerById.connect("id", { + label: 'chat', + serialization: 'none', + metadata: {message: 'hi i want to chat with you!'} +}); + +var call = peerById.call('callto-id', (window).localStream); + +var openHandler=()=> console.log("open"); +peerById.on("open", openHandler); +peerById.on("connection", (c)=> console.log("connection")); +peerById.on("call", (media)=> console.log("call")); +peerById.on("close", ()=> console.log("close")); +peerById.on("disconnected", ()=> console.log("disconnected")); +peerById.on("error", (err)=> console.log(err)); +peerById.off("open", openHandler); diff --git a/skyway/skyway.d.ts b/skyway/skyway.d.ts new file mode 100644 index 000000000..681d358b8 --- /dev/null +++ b/skyway/skyway.d.ts @@ -0,0 +1,184 @@ +// Type definitions for SkyWay +// Project: http://nttcom.github.io/skyway/ +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module PeerJs{ + interface PeerJSOption{ + key?: string; + host?: string; + port?: number; + path?: string; + secure?: boolean; + turn?: boolean; + config?: RTCPeerConnectionConfig; + debug?: number; + } + + interface PeerConnectOption{ + label?: string; + metadata?: any; + serialization?: string; + reliable?: boolean; + } + + interface DataConnection{ + send(data: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'data', cb: (data: any)=>void): void; + on(event: 'open', cb: ()=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + bufferSize: number; + dataChannel: RTCDataChannel; + label: string; + metadata: any; + open: boolean; + peerConnection: any; + peer: string; + reliable: boolean; + serialization: string; + type: string; + } + + interface MediaConnection{ + answer(stream?: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'stream', cb: (stream: any)=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + open: boolean; + metadata: any; + peer: string; + type: string; + } + + interface utilSupportsObj { + audioVideo: boolean; + data: boolean; + binary: boolean; + reliable: boolean; + } + + interface util{ + browser: string; + supports: utilSupportsObj; + } + + export interface Peer{ + /** + * + * @param id The brokering ID of the remote peer (their peer.id). + * @param options for specifying details about Peer Connection + */ + connect(id: string, options?: PeerJs.PeerJSOption): PeerJs.DataConnection; + /** + * Connects to the remote peer specified by id and returns a data connection. + * @param id The brokering ID of the remote peer (their peer.id). + * @param stream The caller's media stream + */ + call(id: string, stream: any): PeerJs.MediaConnection; + /** + * Calls the remote peer specified by id and returns a media connection. + * @param event Event name + * @param cb Callback Function + */ + on(event: string, cb: ()=>void): void; + /** + * Emitted when a connection to the PeerServer is established. + * @param event Event name + * @param cb id is the brokering ID of the peer + */ + on(event: 'open', cb: (id: string)=>void): void; + /** + * Emitted when a new data connection is established from a remote peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; + /** + * Emitted when a remote peer attempts to call you. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; + /** + * Emitted when the peer is destroyed and can no longer accept or create any new connections. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'close', cb: ()=>void): void; + /** + * Emitted when the peer is disconnected from the signalling server + * @param event Event name + * @param cb Callback Function + */ + on(event: 'disconnected', cb: ()=>void): void; + /** + * Errors on the peer are almost always fatal and will destroy the peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'error', cb: (err: any)=>void): void; + /** + * Remove event listeners.(EventEmitter3) + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Boolean} once Only remove once listeners. + */ + off(event: string, fn: Function, once?: boolean): void; + /** + * Close the connection to the server, leaving all existing data and media connections intact. + */ + disconnect(): void; + /** + * Close the connection to the server and terminate all existing connections. + */ + destroy(): void; + /** + * Get a list of available peer IDs + * @param callback + */ + listAllPeers(callback: (peerIds: Array)=>void): void; + + /** + * The brokering ID of this peer + */ + id: string; + /** + * A hash of all connections associated with this peer, keyed by the remote peer's ID. + */ + connections: any; + /** + * false if there is an active connection to the PeerServer. + */ + disconnected: boolean; + /** + * true if this peer and all of its connections can no longer be used. + */ + destroyed: boolean; + } +} + +declare var Peer: { + prototype: RTCIceServer; + /** + * A peer can connect to other peers and listen for connections. + * @param id Other peers can connect to this peer using the provided ID. + * If no ID is given, one will be generated by the brokering server. + * @param options for specifying details about PeerServer + */ + new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; + + /** + * A peer can connect to other peers and listen for connections. + * @param options for specifying details about PeerServer + */ + new (options: PeerJs.PeerJSOption): PeerJs.Peer; +}; From f1e34355814e30f94e0b80680a6c6863e0b07c32 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 16 Jul 2015 11:52:55 +0100 Subject: [PATCH 122/416] Type definitions and tests for node shortid module --- shortid/shortid-tests.ts | 10 ++++++++++ shortid/shortid.d.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 shortid/shortid-tests.ts create mode 100644 shortid/shortid.d.ts diff --git a/shortid/shortid-tests.ts b/shortid/shortid-tests.ts new file mode 100644 index 000000000..31ee0df1d --- /dev/null +++ b/shortid/shortid-tests.ts @@ -0,0 +1,10 @@ +/// + +import shortid = require('shortid'); + +var my_short_id: string = shortid.generate(); +console.log(my_short_id); + +console.log('Is valid short id? => %s', shortid.isValid(my_short_id)); // => true +console.log('Is valid short id? => %s', shortid.isValid(5)); // => false +console.log('Is valid short id? => %s', shortid.isValid('i have spaces')); // => false diff --git a/shortid/shortid.d.ts b/shortid/shortid.d.ts new file mode 100644 index 000000000..049e53969 --- /dev/null +++ b/shortid/shortid.d.ts @@ -0,0 +1,12 @@ +// Type definitions for shortid +// Project: https://github.com/dylang/shortid +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "shortid" { + export function generate(): string; + export function characters(string: string): string; + export function isValid(id: any): boolean; + export function worker(integer: number): void; + export function seed(float: number): void; +} From 4340cbf5c38ccd2d6a751e1c17dff70d8e403406 Mon Sep 17 00:00:00 2001 From: Nicholas Penree Date: Thu, 16 Jul 2015 08:34:58 -0400 Subject: [PATCH 123/416] Add type definitions for kue --- kue/kue-tests.ts | 96 ++++++++++++++++++++++++++++++ kue/kue.d.ts | 149 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 245 insertions(+) create mode 100644 kue/kue-tests.ts create mode 100644 kue/kue.d.ts diff --git a/kue/kue-tests.ts b/kue/kue-tests.ts new file mode 100644 index 000000000..c58f6f874 --- /dev/null +++ b/kue/kue-tests.ts @@ -0,0 +1,96 @@ +/// +/// + +import kue = require('kue'); + +// create our job queue + +var jobs = kue.createQueue(); + +// start redis with $ redis-server + +// create some jobs at random, +// usually you would create these +// in your http processes upon +// user input etc. + +function create() { + var name = [ 'tobi', 'loki', 'jane', 'manny' ][ Math.random() * 4 | 0 ]; + var job = jobs.create( 'video conversion', { + title: 'converting ' + name + '\'s to avi', user: 1, frames: 200 + }); + + job.on('complete', function() { + console.log(" Job complete"); + }).on('failed', function() { + console.log(" Job failed"); + }).on('progress', function(progress: number) { + process.stdout.write('\r job #' + job.id + ' ' + progress + '% complete'); + }); + + job.save(); + + setTimeout( create, Math.random() * 2000 | 0 ); +} + +create(); + +// process video conversion jobs, 1 at a time. + +jobs.process('video conversion', 1, function(job: kue.Job, done: Function) { + var frames: number = job.data.frames; + + function next(i: number) { + // pretend we are doing some work + convertFrame(i, function(err: Error) { + if (err) return done(err); + // report progress, i/frames complete + job.progress(i, frames); + if (i >= frames) done(); + else next(i + Math.random() * 10); + } ); + } + + next(0); +} ); + +function convertFrame(i: number, fn: Function) { + setTimeout(fn, Math.random() * 50); +} + +// one minute + +var minute = 60000; + +var email = jobs.create('email', { + title: 'Account renewal required', to: 'tj@learnboost.com', template: 'renewal-email' +}).delay(minute) + .priority('high') + .save(); + + +email.on('promotion', function() { + console.log('renewal job promoted'); +} ); + +email.on('complete', function() { + console.log('renewal job completed' ); +} ); + +jobs.create('email', { + title: 'Account expired', to: 'tj@learnboost.com', template: 'expired-email' +} ).delay( minute * 10 ) + .priority('high') + .save(); + +jobs.promote(); + +jobs.process('email', 10, function(job, done) { + setTimeout(function() { + done(); + }, Math.random() * 5000); +}); + +// start the UI +kue.app.listen(3000); +console.log('UI started on port 3000'); \ No newline at end of file diff --git a/kue/kue.d.ts b/kue/kue.d.ts new file mode 100644 index 000000000..1b3fff227 --- /dev/null +++ b/kue/kue.d.ts @@ -0,0 +1,149 @@ +// Type definitions for kue 0.9.x +// Project: https://github.com/Automattic/kue +// Definitions by: Nicholas Penree +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module "kue" { + import events = require('events'); + import express = require('express'); + import redis = require('redis'); + + export class Queue extends events.EventEmitter { + name: string; + id: string; + promoter: any; + workers: Worker[]; + shuttingDown: boolean; + client: redis.RedisClient; + testMode: TestMode; + + static singleton: Queue; + + constructor(options: Object); + create(type: string, data: Object): Job; + createJob(type: string, data: Object): Job; + promote(ms?: number): void; + setupTimer(): void; + checkJobPromotion(ms: number): void; + checkActiveJobTtl(ttlOptions: Object): void; + watchStuckJobs(ms: number): void; + setting(name: string, fn: Function): Queue; + process(type: string, n?: number, fn?: Function): void; + shutdown(timeout: number, type: string, fn: Function): Queue; + types(fn: Function): Queue; + state(string: string, fn: Function): Queue; + workTime(fn: Function): Queue; + cardByType(type: string, state: string, fn: Function): Queue; + card(state: string, fn: Function): Queue; + complete(fn: Function): Queue; + failed(fn: Function): Queue; + inactive(fn: Function): Queue; + active(fn: Function): Queue; + delayed(fn: Function): Queue; + completeCount(type: string, fn: Function): Queue; + failedCount(type: string, fn: Function): Queue; + inactiveCount(type: string, fn: Function): Queue; + activeCount(type: string, fn: Function): Queue; + delayedCount(type: string, fn: Function): Queue; + } + + interface Priorities { + low: number; + normal: number; + medium: number; + high: number; + critical: number; + } + + export class Job extends events.EventEmitter { + public id: number; + public type: string; + public data: any; + public client: redis.RedisClient; + private _max_attempts; + + static priorities: Priorities; + static disableSearch: boolean; + static jobEvents: boolean; + static get(id: number, fn: Function): void; + static remove(id: number, fn?: Function): void; + static removeBadJob(id: number): void; + static log(id: number, fn: Function): void; + static range(from: number, to: number, order: string, fn: Function): void; + static rangeByState(state: string, from: number, to: number, order: string, fn: Function): void; + static rangeByType(type: string, state: string, from: number, to: number, order: string, fn: Function): void; + + constructor(type: string, data?: any); + toJSON(): Object; + log(str: string): Job; + set(key: string, val: string, fn?: Function): Job; + get(key: string, fn?: Function): Job; + progress(complete: number, total: number, data?: any): Job; + delay(ms:number|Date): Job; + removeOnComplete(param: any): void; + backoff(param: any): void; + ttl(param: any): void; + private _getBackoffImpl(): void; + priority(level: string|number): Job; + attempt(fn: Function): Job; + reattempt(attempt: number, fn?: Function): void; + attempts(n: number): Job; + searchKeys(keys: string[]|string): Job; + remove(fn?: Function): Job; + state(state: string, fn?: Function): Job; + error(err: Error): Job; + complete(fn?: Function): Job; + failed(fn?: Function): Job; + inactive(fn?: Function): Job; + active(fn?: Function): Job; + delayed(fn?: Function): Job; + save(fn?: Function): Job; + update(fn?: Function): Job; + subscribe(fn?: Function): Job; + } + + class Worker extends events.EventEmitter { + queue: Queue; + type: string; + client: redis.RedisClient; + job: Job; + + constructor(queue: Queue, type: string); + start(fn: Function): Worker; + error(err: Error, job: Job): Worker; + failed(job: Job, theErr: Object, fn?: Function): Worker; + process(job: Job, fn: Function): Worker; + private zpop(key: string, fn: Function): void; + private getJob(fn: Function): void; + idle(): Worker; + shutdown(timeout: number, fn: Function): void; + emitJobEvent(event: Object, job: Job, arg1: any, arg2: any): void; + resume(): boolean; + } + + interface Redis { + configureFactory(options: Object, queue: Queue): void; + createClient(): redis.RedisClient; + createClientFactory(options: Object): redis.RedisClient; + client(): redis.RedisClient; + pubsubClient(): redis.RedisClient; + reset(): void; + } + + interface TestMode { + jobs: Job[]; + enter(): void; + exit(): void; + clear(): void; + } + + export var app: express.Application; + export var redis: Redis; + export var workers: Worker[]; + + export function createQueue(options?: Object): Queue; +} \ No newline at end of file From 7057e7d2aac7e19cd035497fc289205539f3b5b8 Mon Sep 17 00:00:00 2001 From: Nicholas Penree Date: Thu, 16 Jul 2015 09:48:03 -0400 Subject: [PATCH 124/416] Fix types in kue tests --- kue/kue-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kue/kue-tests.ts b/kue/kue-tests.ts index c58f6f874..0a990ee7b 100644 --- a/kue/kue-tests.ts +++ b/kue/kue-tests.ts @@ -85,7 +85,7 @@ jobs.create('email', { jobs.promote(); -jobs.process('email', 10, function(job, done) { +jobs.process('email', 10, function(job: kue.Job, done: Function) { setTimeout(function() { done(); }, Math.random() * 5000); From 2bab2df8287f7eb91900d63f69485f6a16eb3896 Mon Sep 17 00:00:00 2001 From: Chabardes Date: Thu, 16 Jul 2015 17:12:01 +0200 Subject: [PATCH 125/416] Update velocity-animate.d.ts add hook functions (http://julian.com/research/velocity/#hook) --- velocity-animate/velocity-animate.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts index 00c421896..6946da972 100644 --- a/velocity-animate/velocity-animate.d.ts +++ b/velocity-animate/velocity-animate.d.ts @@ -34,6 +34,16 @@ declare module jquery.velocity { animate(options: {elements: NodeListOf; properties: Object; options: VelocityOptions}): void; animate(elements: NodeListOf, properties: Object, options: VelocityOptions): void; animate(element: HTMLElement, properties: Object, options: VelocityOptions): void; + /** + * Get a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string): string; + /** + * Set a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string, cssValue: string): void; } interface VelocityOptions { From 8f1775b79db7a5a552eb8f26f6e59fe9e04a8e09 Mon Sep 17 00:00:00 2001 From: Dasa Paddock Date: Thu, 16 Jul 2015 08:15:38 -0700 Subject: [PATCH 126/416] Update for ArcGIS API for JavaScript version 3.14 --- arcgis-js-api/arcgis-js-api.d.ts | 3396 +++++++++++++++++++----------- 1 file changed, 2151 insertions(+), 1245 deletions(-) diff --git a/arcgis-js-api/arcgis-js-api.d.ts b/arcgis-js-api/arcgis-js-api.d.ts index 1f6523a23..ba5e0fb9f 100644 --- a/arcgis-js-api/arcgis-js-api.d.ts +++ b/arcgis-js-api/arcgis-js-api.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript v3.13 +// Type definitions for ArcGIS API for JavaScript v3.14 // Project: http://js.arcgis.com // Definitions by: Esri // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -16,12 +16,12 @@ declare module "esri" { import Extent = require("esri/geometry/Extent"); import TileInfo = require("esri/layers/TileInfo"); import BasemapLayer = require("esri/dijit/BasemapLayer"); + import Symbol = require("esri/symbols/Symbol"); import BookmarkItem = require("esri/dijit/BookmarkItem"); import Units = require("esri/units"); import Color = require("esri/Color"); import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol"); - import Geocoder = require("esri/dijit/Geocoder"); import RouteParameters = require("esri/tasks/RouteParameters"); import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); import Font = require("esri/symbols/Font"); @@ -31,16 +31,19 @@ declare module "esri" { import LayerSource = require("esri/layers/LayerSource"); import GraphicsLayer = require("esri/layers/GraphicsLayer"); import SpatialReference = require("esri/SpatialReference"); - import Symbol = require("esri/symbols/Symbol"); import Layer = require("esri/layers/layer"); + import SimpleFillSymbol = require("esri/symbols/SimpleFillSymbol"); + import ArcGISImageServiceLayer = require("esri/layers/ArcGISImageServiceLayer"); + import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); import Locator = require("esri/tasks/locator"); import InfoWindowBase = require("esri/InfoWindowBase"); import LOD = require("esri/layers/LOD"); + import Polyline = require("esri/geometry/Polyline"); + import Polygon = require("esri/geometry/Polygon"); import FillSymbol = require("esri/symbols/FillSymbol"); import PrintTemplate = require("esri/tasks/PrintTemplate"); import QueryTask = require("esri/tasks/QueryTask"); import TextSymbol = require("esri/symbols/TextSymbol"); - import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask"); import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo"); @@ -245,6 +248,18 @@ declare module "esri" { /** Whether the widget is visible by default. */ visible?: boolean; } + export interface BlendRendererOptions { + /** This determines how colors are blended together. */ + blendMode?: string; + /** An array of objects to blend containing the field name and color to use. */ + fields: any[]; + /** The field to normalize. */ + normalizationField?: string; + /** An array of objects which determines opacity. */ + opacityStops: any[]; + /** The symbol in which the BlendRenderer is applied. */ + symbol: Symbol; + } export interface BookmarksOptions { /** An array of BookmarkItem objects or a json object with the BookmarkItem format to initially display in the bookmark widget. */ bookmarks?: BookmarkItem[]; @@ -279,7 +294,7 @@ declare module "esri" { } export interface CircleOptions2 { /** The center point of the circle. */ - center: any; + center: Point | number[]; /** Applicable when the spatial reference of the center point is either set to Web Mercator or geographic/geodesic as true would apply. */ geodesic?: boolean; /** A circle can be thought of similar to a polygon. */ @@ -537,7 +552,7 @@ declare module "esri" { } export interface DirectionsOptions { /** Defines the values that label each stop. */ - alphabet?: any; + alphabet?: string | string[] | boolean; /** When true, solve will start when the last destination is complete and enter key is hit. */ autoSolve?: boolean; /** Display the 'Add Destination' button. */ @@ -556,10 +571,6 @@ declare module "esri" { fromSymbol?: PictureMarkerSymbol; /** The symbol that displays when the from location is dragged to a new location. */ fromSymbolDrag?: PictureMarkerSymbol; - /** Define optional geocoder options view the Geocoder help for details on the object properties. */ - geocoderOptions?: any; - /** List of Geocoder widgets used for each stop. */ - geocoders?: Geocoder[]; /** If available, this geometry service is used to provide latitude/longitude values for stops whose reverse geocoding did not return an address (Added at v3.11). */ geometryTaskUrl?: string; /** Reference to the map object. */ @@ -586,6 +597,8 @@ declare module "esri" { routeSymbol?: SimpleLineSymbol; /** Specify the service that will be used to calculate directions. */ routeTaskUrl?: string; + /** Used to define optional search options. */ + searchOptions?: any; /** Define the info template for the popup that appears when the popup for a route segment is displayed. */ segmentInfoTemplate?: InfoTemplate; /** Specify the symbol used to render the individual route segments that display on the map when a direction step is clicked. */ @@ -617,7 +630,7 @@ declare module "esri" { /** List of graphics used to display the point marker. */ stopGraphics?: Graphic[]; /** An array of points that define the stop locations. */ - stops?: any; + stops?: Point[] | number[][] | string[] | any[]; /** Define the info template for the popup that appears when a stop is clicked. */ stopsInfoTemplate?: InfoTemplate; /** The symbol that displays on the map for the locations between the origin and final destination locations. */ @@ -642,6 +655,8 @@ declare module "esri" { traffic?: boolean; /** The traffic layer used for real-time traffic. */ trafficLayer?: ArcGISDynamicMapServiceLayer; + /** An example of when to use this is when working with a proxied ArcGIS Online route service item with stored credentials. */ + travelModesServiceUrl?: string; } export interface DissolveBoundariesOptions { /** The URL to the GPServer used to execute an analysis job. */ @@ -709,7 +724,7 @@ declare module "esri" { /** Marker symbol used to display the insertable vertices. */ ghostVertexSymbol?: MarkerSymbol; /** If users want to place the text symbol editor to a user defined HTML element. */ - textSymbolEditorHolder?: any; + textSymbolEditorHolder?: Node | string; /** When true, if the geometry is re-sized the aspect ration will be preserved. */ uniformScaling?: boolean; /** Marker symbol used to draw the vertices. */ @@ -719,6 +734,16 @@ declare module "esri" { /** Create a new settings object that defines the capabilities of the widget. */ settings?: any; } + export interface ElevationProfileOptions { + /** This object contains properties used to render the chart. */ + chartOptions?: any; + /** Reference to the map. */ + map: Map; + /** The URL to the elevation profile service. */ + profileTaskUrl: string; + /** The measurement unit of the scalebar units. */ + scalebarUnits?: string; + } export interface EnrichLayerOptions { /** The URL to the GPServer used to execute an analysis job. */ analysisGpServer?: string; @@ -823,6 +848,10 @@ declare module "esri" { /** Initial visibility of the layer. */ visible?: boolean; } + export interface FeatureLayerStatisticsOptions { + /** The feature layer that will be the source for calculating statistics. */ + layer: FeatureLayer; + } export interface FeatureTableOptions { /** A dGrid property. */ allowSelectAll?: boolean; @@ -963,7 +992,7 @@ declare module "esri" { } export interface GeocoderOptions { /** By default, the Geocoder widget uses the Esri World Locator to find search locations. */ - arcgisGeocoder?: any; + arcgisGeocoder?: boolean | any; /** When false, the geocoder will not display the auto-complete results menu. */ autoComplete?: boolean; /** When false, the geolocator will not navigate to the result after selection or search. */ @@ -1005,7 +1034,7 @@ declare module "esri" { /** Class attribute to set for the layer's node. */ className?: string; /** List of attribute fields to be added as custom data attributes to graphics node. */ - dataAttributes?: any; + dataAttributes?: string | string[]; /** When true, graphics are displayed during panning. */ displayOnPan?: boolean; /** Id to assign to the layer. */ @@ -1085,6 +1114,44 @@ declare module "esri" { /** Specify the geodatabase version to display. */ gdbVersion?: string; } + export interface ImageServiceMeasureOptions { + /** Symbol to be used when drawing a polygon or extent. */ + fillSymbol?: SimpleFillSymbol; + /** Image service layer with which the toolbar is associated. */ + layer: ArcGISImageServiceLayer; + /** Symbol to be used when drawing a line. */ + lineSymbol?: SimpleLineSymbol; + /** Map instance with which the toolbar is associate. */ + map: Map; + /** Symbol to be used when drawing a point. */ + markerSymbol?: SimpleMarkerSymbol; + } + export interface ImageServiceMeasureToolOptions { + /** The angular unit in which directions of line segments will be calculated. */ + angularUnit?: string; + /** The area unit in which areas of polygons will be calculated. */ + areaUnit?: string; + /** Symbol to be used when drawing a polygon or extent. */ + fillSymbol?: SimpleFillSymbol; + /** Image service layer the toolbar is associated with. */ + layer: ArcGISImageServiceLayer; + /** The linear unit in which height, length, or perimeters will be calculated. */ + linearUnit?: string; + /** Symbol to be used when drawing a line. */ + lineSymbol?: SimpleLineSymbol; + /** Map instance the toolbar is associated with. */ + map: Map; + /** Symbol to be used when drawing a point. */ + markerSymbol?: SimpleMarkerSymbol; + } + export interface ImageSpatialReferenceOptions { + /** The full Image Coordinate System object, which includes transformations and map spatial reference information specific to each image. */ + ics?: any; + /** The OBJECTID of the image in a mosaic dataset. */ + icsid?: number; + /** The url of the image service. */ + url: string; + } export interface KMLLayerOptions { /** Class attribute to set for the layer's node. */ className?: string; @@ -1099,6 +1166,20 @@ declare module "esri" { /** Display mode for the label layer. */ mode?: string; } + export interface LayerListOptions { + /** An array of operational layers. */ + layers: any[]; + /** Reference to the map. */ + map: Map; + /** Indicates whether to remove underscores from the layer title. */ + removeUnderscores?: boolean; + /** Indicates whether to show sublayers in the list of layers. */ + subLayers?: boolean; + /** The CSS class selector used to uniquely style the widget. */ + theme?: string; + /** Indicates whether to show the LayerList widget. */ + visible?: boolean; + } export interface LayerOptions { /** Class attribute to set for the layer's node. */ className?: string; @@ -1183,7 +1264,7 @@ declare module "esri" { /** Specify a basemap for the map. */ basemap?: string; /** The location where the map should be centered. */ - center?: any; + center?: number[] | Point; /** When true, graphics are displayed during panning. */ displayGraphicsOnPan?: boolean; /** If provided, the extent and projection of the map is set to the properties of Extent. */ @@ -1249,7 +1330,7 @@ declare module "esri" { /** The default length unit for the measure distance tool. */ defaultLengthUnit?: Units; /** Allows the user to immediately measure previously-created geometry on dijit creation. */ - geometry?: any; + geometry?: Point | Polyline | Polygon; /** Line symbol used to draw the lines for the measure line and measure distance tools. */ lineSymbol?: SimpleLineSymbol; /** Reference to the map. */ @@ -1341,6 +1422,36 @@ declare module "esri" { /** The ArcGIS for Portal URL. */ portalUrl?: string; } + export interface ObliqueViewerOptions { + /** Azimuth angle value for which to display oblique images. */ + azimuthAngle?: number; + /** Image service field that denotes the sensor azimuth value for a record. */ + azimuthField?: string; + /** Tolerance value applied when filtering azimuth images. */ + azimuthTolerance?: number; + /** Image service field that denotes the sensor elevation value for a record. */ + elevationField?: string; + /** Elevation value between 0 and 90 that differentiates an image as oblique or nadir. */ + elevationThreshold?: number; + /** Image service layer to be used as source for oblique images. */ + imageServiceLayer: ArcGISImageServiceLayer; + /** Map object associated with the widget. */ + map: Map; + /** When true, the widget doesn't refresh itself with new oblique records when the map's extent changes. */ + noQueryOnExtentChange?: boolean; + /** Raster info fields to be queried and displayed in the raster list. */ + rasterInfoFields?: any[]; + /** DOM Node or id, where the list element is to be placed. */ + rasterListDiv?: string | Node; + /** When true, list is populated on data refresh. */ + rasterListRefresh?: boolean; + /** DOM Node or id, where the oblique rotation gauge element is to be placed. */ + rotationDiv?: string | Node; + /** When true, thumbnail images for records are displayed in the list. */ + showThumbnail?: boolean; + /** Sorting function that takes query results and sorts them. */ + sorter?: Function; + } export interface OpacitySliderOptions { /** Handles identified by their index values within the stops array. */ handles: number[]; @@ -1595,7 +1706,7 @@ declare module "esri" { /** Toggle for showing the black handle bars. */ showHandles?: boolean; /** Flexible toggle for showing labels (e.g. */ - showLabels?: any; + showLabels?: boolean | string[]; /** Toggle for showing the horizontal line indicators from the center of the handle. */ showTicks?: boolean; /** Stores positions represented as numbers that fall between minimum and maximum. */ @@ -1623,7 +1734,7 @@ declare module "esri" { } export interface SearchOptions { /** The currently selected source. */ - activeSourceIndex?: any; + activeSourceIndex?: number | string; /** Indicates whether to automatically add all the feature layers from the map. */ addLayersFromMap?: boolean; /** Indicates whether to automatically navigate to the selected result. */ @@ -1710,6 +1821,8 @@ declare module "esri" { sizeInfo: any; /** Represents statistics data object. */ statistics?: any; + /** The symbol used with the widget. */ + symbol: Symbol; /** Additional options to customize slider. */ zoomOptions?: any; } @@ -1883,6 +1996,18 @@ declare module "esri" { /** When true, the template picker displays map service legend swatches for feature layers created in selection mode that have an associated map service added to the map as a dynamic map service layer. */ useLegend?: boolean; } + export interface TimeClassBreaksAgerOptions { + /** The alpha opacity for the break. */ + alpha: number; + /** The color for the break. */ + color: Color; + /** The maximum age for the break info. */ + maxAge: number; + /** The minimum age for the break info. */ + minAge: number; + /** The size for the break. */ + size: number; + } export interface TimeSliderOptions { /** When true, subtracts one second to the time extent's end time to exclude data at the exact end time instant. */ excludeDataAtLeadingThumb?: boolean; @@ -1937,6 +2062,42 @@ declare module "esri" { /** A predefined style. */ style?: string; } + export interface VisibleScaleRangeSliderOptions { + /** Layer used to determine the suggested scale range and set the minScale, maxScale values. */ + layer: FeatureLayer; + /** Reference to the map. */ + map: Map; + /** Region of preview scale thumbnails. */ + region?: string; + } + export interface WFSLayerOptions { + /** Full WFS body request sent to WFS server via POST method. */ + getFeatureRequest?: string; + /** URL used when executing getFeature request. */ + getFeatureUrl?: string; + /** The template that defines the content to display in the map info window when the user clicks on a feature. */ + infoTemplate?: InfoTemplate; + /** For "ondemand" mode only. */ + inverseFilter?: boolean; + /** When true, the XY coordinates should be swapped (this is required for some WFS vendors, versions, and WKIDS). */ + inverseResponse?: boolean; + /** Specifies the maximum number of features to return in one response. */ + maxFeatures?: number; + /** The query mode for the WFS layer. */ + mode?: string; + /** For "ondemand" mode only. */ + nsGeometryFieldName?: string; + /** The full layer name including the namespace as a prefix. */ + nsLayerName?: string; + /** When true, more details will be printed to console when the first connection to a WFS server is established. */ + showDetails?: boolean; + /** URL to the WFS server. */ + url: string; + /** OGC WFS version number. */ + version?: string; + /** The well-known ID of the spatial reference used by the WFSLayer. */ + wkid?: string; + } export interface WMSLayerOptions { /** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */ format?: string; @@ -2018,17 +2179,7 @@ declare module "esri/Color" { * Creates a new Color object. * @param color A named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object. */ - constructor(color?: string); - /** - * Creates a new Color object. - * @param color A named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object. - */ - constructor(color?: number[]); - /** - * Creates a new Color object. - * @param color A named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object. - */ - constructor(color?: any); + constructor(color?: string | number[] | any); /** * Blend colors start and end with weight from 0 to 1, 0.5 being a 50/50 blend. * @param start The start color. @@ -2065,17 +2216,7 @@ declare module "esri/Color" { * Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object and sets this color instance to that value. * @param color The new color value. */ - setColor(color: string): Color; - /** - * Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object and sets this color instance to that value. - * @param color The new color value. - */ - setColor(color: number[]): Color; - /** - * Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another Color object and sets this color instance to that value. - * @param color The new color value. - */ - setColor(color: any): Color; + setColor(color: string | number[] | any): Color; /** * Returns a css color string in rgb(a) representation. * @param includeAlpha If true, the alpha value will be included in the result. @@ -2258,13 +2399,42 @@ declare module "esri/IdentityManagerBase" { export = IdentityManagerBase; } +declare module "esri/ImageSpatialReference" { + import esri = require("esri"); + import SpatialReference = require("esri/SpatialReference"); + + /** Defines the Image Coordinate System (ICS) for ImageServices. */ + class ImageSpatialReference extends SpatialReference { + /** The full Image Coordinate System, which includes transformations and map spatial reference information specific to each image. */ + ics: any; + /** The OBJECTID of the image in a mosaic dataset. */ + icsid: number; + /** + * Creates an instance of ImageSpatialReference. + * @param params Options that may be passed into the constructor. + */ + constructor(params: esri.ImageSpatialReferenceOptions); + /** + * Tests whether the input image coordinate system equals the image coordinate system of the instance calling this method. + * @param inSR The ImageSpatialReference to test the equality against this instance. + */ + equals(inSR: ImageSpatialReference): boolean; + /** + * Converts the ImageSpatialReference instance to a JSON object. + * @param preserveUrl Indicates whether to preserve the URL in the output JSON object. + */ + toJson(preserveUrl?: boolean): boolean; + } + export = ImageSpatialReference; +} + declare module "esri/InfoTemplate" { /** An InfoTemplate contains a title and content template string used to transform Graphic.attributes into an HTML representation. */ class InfoTemplate { /** The template for defining how to format the content used in an InfoWindow. */ - content: any; + content: string | Function; /** The template for defining how to format the title used in an InfoWindow. */ - title: any; + title: string | Function; /** Creates a new empty InfoTemplate object. */ constructor(); /** @@ -2272,7 +2442,7 @@ declare module "esri/InfoTemplate" { * @param title The template for defining how to format the title used in an InfoWindow. * @param content The template for defining how to format the content used in an InfoWindow. */ - constructor(title: string, content: string); + constructor(title: string | Function, content: string | Function); /** * Creates a new InfoTemplate object using a JSON object. * @param json JSON object representing the InfoTemplate. @@ -2282,22 +2452,12 @@ declare module "esri/InfoTemplate" { * Sets the content template. * @param template The template for the content. */ - setContent(template: string): InfoTemplate; - /** - * Sets the content template. - * @param template The template for the content. - */ - setContent(template: Function): InfoTemplate; + setContent(template: string | Function): InfoTemplate; /** * Sets the title template. * @param template The template for the title. */ - setTitle(template: string): InfoTemplate; - /** - * Sets the title template. - * @param template The template for the title. - */ - setTitle(template: Function): InfoTemplate; + setTitle(template: string | Function): InfoTemplate; /** Converts object to its ArcGIS Server JSON representation. */ toJson(): any; } @@ -2324,13 +2484,7 @@ declare module "esri/InfoWindowBase" { * @param value A string with HTML tags or a DOM node. * @param parentNode The parent node where the value will be placed. */ - place(value: string, parentNode: Node): void; - /** - * Helper method. - * @param value A string with HTML tags or a DOM node. - * @param parentNode The parent node where the value will be placed. - */ - place(value: HTMLElement, parentNode: Node): void; + place(value: string | HTMLElement, parentNode: Node): void; /** * Resize the info window to the specified width and height (in pixels). * @param width The new width of the InfoWindow in pixels. @@ -2341,12 +2495,7 @@ declare module "esri/InfoWindowBase" { * Define the info window content. * @param content The content argument can be any of the following. */ - setContent(content: string): void; - /** - * Define the info window content. - * @param content The content argument can be any of the following. - */ - setContent(content: any): void; + setContent(content: string | any): void; /** * This method is called by the map when the object is set as its info window. * @param map The map object. @@ -2356,12 +2505,7 @@ declare module "esri/InfoWindowBase" { * Set the input value as the title for the info window. * @param title In most cases the title will be a string value but the same options are available as for the setContent method. */ - setTitle(title: string): void; - /** - * Set the input value as the title for the info window. - * @param title In most cases the title will be a string value but the same options are available as for the setContent method. - */ - setTitle(title: any): void; + setTitle(title: string | any): void; /** * Display the info window at the specified location. * @param location Location is an instance of esri.geometry.Point. @@ -2927,8 +3071,6 @@ declare module "esri/arcgis/Portal" { } declare module "esri/arcgis/utils" { - import Layer = require("esri/layers/layer"); - /** Utility methods to work with content from ArcGIS.com. */ var utils: { /** Specify the domain where the map associated with the webmap id is located. */ @@ -2939,14 +3081,7 @@ declare module "esri/arcgis/utils" { * @param mapDiv Container ID for referencing map. * @param options Optional parameters that define the map functionality. */ - createMap(itemIdOrItemInfo: string, mapDiv: string, options?: any): any; - /** - * Create a map using information from an ArcGIS.com item. - * @param itemIdOrItemInfo An itemId for an ArcGIS.com item or the response object obtained from calling the arcgisUtils.getItem method. - * @param mapDiv Container ID for referencing map. - * @param options Optional parameters that define the map functionality. - */ - createMap(itemIdOrItemInfo: any, mapDiv: string, options?: any): any; + createMap(itemIdOrItemInfo: string | any, mapDiv: string, options?: any): any; /** * Get details about the input ArcGIS.com item. * @param itemId The itemId for a publicly shared ArcGIS.com item. @@ -2956,13 +3091,13 @@ declare module "esri/arcgis/utils" { * Can be used with esri.dijit.Legend to get the layerInfos list to be passed into the Legend constructor. * @param createMapResponse Object returned by .createMap() in the .then() callback. */ - getLegendLayers(createMapResponse: any): Layer[]; + getLegendLayers(createMapResponse: any): any[]; }; export = utils; } declare module "esri/basemaps" { - /** Contains properties referencing default basemaps used in the JS API. */ + /** This class contains properties referencing default basemaps used in the JS API that allow you to add map services as default basemaps in web applications. */ var basemaps: { /** The Light Gray Canvas basemap is designed to be used as a neutral background map for overlaying and emphasizing other map layers. */ gray: any; @@ -3010,13 +3145,7 @@ declare module "esri/dijit/AttributeInspector" { * @param params See options list. * @param srcNodeRef HTML element where the attribute inspector should be rendered. */ - constructor(params: esri.AttributeInspectorOptions, srcNodeRef: Node); - /** - * Creates a new Attribute Inspector object. - * @param params See options list. - * @param srcNodeRef HTML element where the attribute inspector should be rendered. - */ - constructor(params: esri.AttributeInspectorOptions, srcNodeRef: string); + constructor(params: esri.AttributeInspectorOptions, srcNodeRef: Node | string); /** Destroys the widget, used for page clean up. */ destroy(): void; /** Moves to the first feature. */ @@ -3061,13 +3190,7 @@ declare module "esri/dijit/Attribution" { * @param options An object that defines the attribution options. * @param srcNodeRef HTML element where the time slider should be rendered. */ - constructor(options: esri.AttributionOptions, srcNodeRef: Node); - /** - * Creates a new Attribution object. - * @param options An object that defines the attribution options. - * @param srcNodeRef HTML element where the time slider should be rendered. - */ - constructor(options: esri.AttributionOptions, srcNodeRef: string); + constructor(options: esri.AttributionOptions, srcNodeRef: Node | string); /** Destroy the attribution widget. */ destroy(): void; /** Finalizes the creation of the widget. */ @@ -3118,13 +3241,7 @@ declare module "esri/dijit/BasemapGallery" { * @param params Parameters used to configure the widget. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.BasemapGalleryOptions, srcNodeRef?: Node); - /** - * Creates a new BasemapGallery dijit. - * @param params Parameters used to configure the widget. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: esri.BasemapGalleryOptions, srcNodeRef?: string); + constructor(params: esri.BasemapGalleryOptions, srcNodeRef?: Node | string); /** * Add a new basemap to the BasemapGallery's list of basemaps. * @param basemap The basemap to add to the map. @@ -3204,7 +3321,7 @@ declare module "esri/dijit/BasemapToggle" { class BasemapToggle { /** The secondary basemap to toggle to. */ basemap: string; - /** Object containing the labels and URLs for the image of each basemap. */ + /** Object containing the title and thumbnailURL for the image of each basemap. */ basemaps: any; /** Whether the widget has been loaded. */ loaded: boolean; @@ -3219,13 +3336,7 @@ declare module "esri/dijit/BasemapToggle" { * @param params Various parameters to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.BasemapToggleOptions, srcNodeRef: Node); - /** - * Creates a new BasemapToggle dijit using the given DOM node. - * @param params Various parameters to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.BasemapToggleOptions, srcNodeRef: string); + constructor(params: esri.BasemapToggleOptions, srcNodeRef: Node | string); /** Destroys the widget. */ destroy(): void; /** Hides the widget. */ @@ -3273,13 +3384,7 @@ declare module "esri/dijit/Bookmarks" { * @param params See options list for parameters. * @param srcNodeRef HTML element where the bookmark widget should be rendered. */ - constructor(params: esri.BookmarksOptions, srcNodeRef: Node); - /** - * Creates a new Bookmark widget - * @param params See options list for parameters. - * @param srcNodeRef HTML element where the bookmark widget should be rendered. - */ - constructor(params: esri.BookmarksOptions, srcNodeRef: string); + constructor(params: esri.BookmarksOptions, srcNodeRef: Node | string); /** * Add a new bookmark to the bookmark widget. * @param bookmarkItem A BookmarkItem or json object with the same structure that defines the new location. @@ -3354,13 +3459,7 @@ declare module "esri/dijit/ClassedColorSlider" { * @param params Set of parameters used to specify the ClassedColorSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.ClassedColorSliderOptions, srcNodeRef: Node); - /** - * Creates a new ClassedColorSlider widget. - * @param params Set of parameters used to specify the ClassedColorSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.ClassedColorSliderOptions, srcNodeRef: string); + constructor(params: esri.ClassedColorSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the ClassedColorSlider widget properties change. */ @@ -3415,13 +3514,7 @@ declare module "esri/dijit/ClassedSizeSlider" { * @param params Set of parameters used to specify the ClassedSizeSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.ClassedSizeSliderOptions, srcNodeRef: Node); - /** - * Creates a new ClassedSizeSlider widget within the provided DOM node srcNodeRef. - * @param params Set of parameters used to specify the ClassedSizeSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.ClassedSizeSliderOptions, srcNodeRef: string); + constructor(params: esri.ClassedSizeSliderOptions, srcNodeRef: Node | string); /** Fires when ClassedSizeSlider changes. */ on(type: "change", listener: (event: { breakInfos: any; target: ClassedSizeSlider }) => void): esri.Handle; /** Fires when minValue or maxValue changes in ClassedSizeSlider. */ @@ -3478,13 +3571,7 @@ declare module "esri/dijit/ColorInfoSlider" { * @param params Set of parameters used to specify the ColorInfoSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.ColorInfoSliderOptions, srcNodeRef: Node); - /** - * Creates a new ColorInfoSlider widget within the provided DOM node srcNodeRef. - * @param params Set of parameters used to specify the ColorInfoSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.ColorInfoSliderOptions, srcNodeRef: string); + constructor(params: esri.ColorInfoSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when ColorInfoSlider changes. */ @@ -3515,13 +3602,7 @@ declare module "esri/dijit/ColorPicker" { * @param params Set of parameters used to specify the ColorPicker widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.ColorPickerOptions, srcNodeRef: Node); - /** - * Creates a new ColorPicker widget. - * @param params Set of parameters used to specify the ColorPicker widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.ColorPickerOptions, srcNodeRef: string); + constructor(params: esri.ColorPickerOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the selected color has changed. */ @@ -3544,8 +3625,6 @@ declare module "esri/dijit/Directions" { class Directions { /** Read-only: Get the directions to all the locations along the route. */ directions: DirectionsFeatureSet; - /** An array of objects that defines the potential matches for the input locations. */ - geocoderResults: any[]; /** Indicates whether the Directions widget adds a stop on each map click. */ mapClickActive: boolean; /** Read-only: When true, the maximum number of stops for the route has been reached. */ @@ -3577,13 +3656,7 @@ declare module "esri/dijit/Directions" { * @param options Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(options: esri.DirectionsOptions, srcNodeRef: Node); - /** - * Creates a new Directions dijit using the given DOM node. - * @param options Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(options: esri.DirectionsOptions, srcNodeRef: string); + constructor(options: esri.DirectionsOptions, srcNodeRef: Node | string); /** Deprecated at v3.13. */ activate(): void; /** @@ -3591,49 +3664,13 @@ declare module "esri/dijit/Directions" { * @param stop A point that defines the stop location. * @param index The index location where the stop should be added. */ - addStop(stop: Point, index?: number): any; - /** - * Add a stop to the directions widget at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index location where the stop should be added. - */ - addStop(stop: number[], index?: number): any; - /** - * Add a stop to the directions widget at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index location where the stop should be added. - */ - addStop(stop: string, index?: number): any; - /** - * Add a stop to the directions widget at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index location where the stop should be added. - */ - addStop(stop: any, index?: number): any; + addStop(stop: Point | number[] | string | any, index?: number): any; /** * Add multiple stops to the directions list starting at the specified location. * @param stops An array of points that define the stop locations. * @param index The index location where the stops will be added. */ - addStops(stops: Point[], index?: number): any; - /** - * Add multiple stops to the directions list starting at the specified location. - * @param stops An array of points that define the stop locations. - * @param index The index location where the stops will be added. - */ - addStops(stops: number[][], index?: number): any; - /** - * Add multiple stops to the directions list starting at the specified location. - * @param stops An array of points that define the stop locations. - * @param index The index location where the stops will be added. - */ - addStops(stops: string[], index?: number): any; - /** - * Add multiple stops to the directions list starting at the specified location. - * @param stops An array of points that define the stop locations. - * @param index The index location where the stops will be added. - */ - addStops(stops: any[], index?: number): any; + addStops(stops: Point[] | number[][] | string[] | any[], index?: number): any; /** * Center the map at the start of the specified route segment. * @param index The index of the segment where the map should be centered. @@ -3677,45 +3714,12 @@ declare module "esri/dijit/Directions" { * @param stop A point that defines the stop location. * @param index The index of the stop to update. */ - updateStop(stop: Point, index: number): any; - /** - * Update the existing stop at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index of the stop to update. - */ - updateStop(stop: number[], index: number): any; - /** - * Update the existing stop at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index of the stop to update. - */ - updateStop(stop: string, index: number): any; - /** - * Update the existing stop at the specified index location. - * @param stop A point that defines the stop location. - * @param index The index of the stop to update. - */ - updateStop(stop: any, index: number): any; + updateStop(stop: Point | number[] | string | any, index: number): any; /** * Update multiple stops in the directions widget by specifying an array of stops information. * @param stops An array of points that define the stop locations. */ - updateStops(stops: Point[]): any; - /** - * Update multiple stops in the directions widget by specifying an array of stops information. - * @param stops An array of points that define the stop locations. - */ - updateStops(stops: number[][]): any; - /** - * Update multiple stops in the directions widget by specifying an array of stops information. - * @param stops An array of points that define the stop locations. - */ - updateStops(stops: string[]): any; - /** - * Update multiple stops in the directions widget by specifying an array of stops information. - * @param stops An array of points that define the stop locations. - */ - updateStops(stops: any[]): any; + updateStops(stops: Point[] | number[][] | string[] | any[]): any; /** * Sets the corresponding stop to point at the user's current location. * @param stopIndex Index of the stop that will point to the user's current location. @@ -3751,12 +3755,45 @@ declare module "esri/dijit/Directions" { export = Directions; } +declare module "esri/dijit/ElevationProfile" { + import esri = require("esri"); + import Geometry = require("esri/geometry/Geometry"); + + /** (Currently in beta)The Elevation Profile widget allows a user to create an elevation profile based on a polyline geometry input parameter or existing features.NOTE: Currently there is a known issue when creating an elevation profile that crosses the international dateline multiple times. */ + class ElevationProfile { + /** The measurement unit of the polyline geometry. */ + measureUnits: string; + /** The polyline input geometry used to create the elevation profile. */ + profileGeometry: Geometry; + /** + * Create a new ElevationProfile widget using the given DOM node. + * @param options See options table below for the full descriptions of the properties needed for this object. + * @param srcNode Reference or id of the HTML element where the widget should be rendered. + */ + constructor(options: esri.ElevationProfileOptions, srcNode: Node | string); + /** Clears the elevation profile chart. */ + clearProfile(): void; + /** Destroy the widget. */ + destroy(): void; + /** Finalizes the creation of the ElevationProfile widget. */ + startup(): void; + /** Fires when the elevation profile is cleared. */ + on(type: "clear-profile", listener: (event: { target: ElevationProfile }) => void): esri.Handle; + /** Fires when the widget has fully loaded. */ + on(type: "load", listener: (event: { target: ElevationProfile }) => void): esri.Handle; + /** Fires when the elevation profile is updated. */ + on(type: "update-profile", listener: (event: { profileResults: any; target: ElevationProfile }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ElevationProfile; +} + declare module "esri/dijit/FeatureTable" { import esri = require("esri"); import FeatureLayer = require("esri/layers/FeatureLayer"); import Map = require("esri/map"); - /** (Beta at v3.12) Creates an instance of the FeatureTable widget within the provided DOM node. */ + /** (Currently in beta) Creates an instance of the FeatureTable widget within the provided DOM node. */ class FeatureTable { /** An optional dGrid property. */ allowSelectAll: boolean; @@ -3784,8 +3821,6 @@ declare module "esri/dijit/FeatureTable" { noDataMessage: string; /** Attribute fields to include in the FeatureTable. */ outFields: string[]; - /** Indicates whether the data is editable via the widget. */ - readOnly: boolean; /** A dGrid property. */ selectionMode: string; /** @@ -3793,13 +3828,7 @@ declare module "esri/dijit/FeatureTable" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.FeatureTableOptions, srcNodeRef: Node); - /** - * Creates an instance of the FeatureTable widget within the provided DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.FeatureTableOptions, srcNodeRef: string); + constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fired when a row is deselected. */ @@ -3825,13 +3854,7 @@ declare module "esri/dijit/Gallery" { * @param params See options list. * @param srcNodeRef HTML element where the gallery should be rendered. */ - constructor(params: esri.GalleryOptions, srcNodeRef: Node); - /** - * Creates a new mobile Gallery. - * @param params See options list. - * @param srcNodeRef HTML element where the gallery should be rendered. - */ - constructor(params: esri.GalleryOptions, srcNodeRef: string); + constructor(params: esri.GalleryOptions, srcNodeRef: Node | string); /** Removes any object references and associated objects created by the gallery. */ destroy(): void; /** Gets the item with the current focus. */ @@ -3874,38 +3897,20 @@ declare module "esri/dijit/Gauge" { * @param params See options list for parameters. * @param srcNodeRef HTML element where the gauge should be rendered. */ - constructor(params: esri.GaugeOptions, srcNodeRef: Node); - /** - * Create a new Gauge object. - * @param params See options list for parameters. - * @param srcNodeRef HTML element where the gauge should be rendered. - */ - constructor(params: esri.GaugeOptions, srcNodeRef: string); + constructor(params: esri.GaugeOptions, srcNodeRef: Node | string); /** Destroy the gauge. */ destroy(): void; /** * Get the value of the property from the Gauge. * @param name Property to get value. */ - get(name: string): any; + get(name: string): string | Graphic | number; /** * Set the value of a property from the Gauge. * @param name Property to set value. * @param value Value to set. */ - set(name: string, value: string): Gauge; - /** - * Set the value of a property from the Gauge. - * @param name Property to set value. - * @param value Value to set. - */ - set(name: string, value: Graphic): Gauge; - /** - * Set the value of a property from the Gauge. - * @param name Property to set value. - * @param value Value to set. - */ - set(name: string, value: number): Gauge; + set(name: string, value: string | Graphic | number): Gauge; /** Finalizes the creation of the gauge. */ startup(): void; } @@ -3917,7 +3922,7 @@ declare module "esri/dijit/Geocoder" { import GraphicsLayer = require("esri/layers/GraphicsLayer"); import Symbol = require("esri/symbols/Symbol"); - /** Add a geographic search box to an application. */ + /** Starting with version 3.13, the Search Widget supersedes the Geocoder Widget and is deprecated. */ class Geocoder { /** Currently selected locator object. */ activeGeocoder: any; @@ -3958,13 +3963,7 @@ declare module "esri/dijit/Geocoder" { * @param params Set of parameters used to specify Geocoder options. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.GeocoderOptions, srcNodeRef: Node); - /** - * Create a new Geocoder widget using the given DOM node. - * @param params Set of parameters used to specify Geocoder options. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: esri.GeocoderOptions, srcNodeRef: string); + constructor(params: esri.GeocoderOptions, srcNodeRef: Node | string); /** Unfocus the widget's text input. */ blur(): void; /** Clears the values currently set in the widget. */ @@ -4028,13 +4027,7 @@ declare module "esri/dijit/HeatmapSlider" { * @param params Set of parameters used to specify the HeatmapSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.HeatmapSliderOptions, srcNodeRef: Node); - /** - * Creates a new HeatmapSlider widget within the provided DOM node srcNodeRef. - * @param params Set of parameters used to specify the HeatmapSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.HeatmapSliderOptions, srcNodeRef: string); + constructor(params: esri.HeatmapSliderOptions, srcNodeRef: Node | string); /** Fires when HeatmapSlider changes. */ on(type: "change", listener: (event: { colorStops: any; target: HeatmapSlider }) => void): esri.Handle; /** Fires when HeatmapSlider handle is moved. */ @@ -4054,13 +4047,7 @@ declare module "esri/dijit/HistogramTimeSlider" { * @param params Input parameters. * @param srcNodeRef HTML element where the tool should be rendered. */ - constructor(params: esri.HistogramTimeSliderOptions, srcNodeRef: Node); - /** - * Creates a new HistogramTimeSlider dijit using the given DOM node. - * @param params Input parameters. - * @param srcNodeRef HTML element where the tool should be rendered. - */ - constructor(params: esri.HistogramTimeSliderOptions, srcNodeRef: string); + constructor(params: esri.HistogramTimeSliderOptions, srcNodeRef: Node | string); /** Set related objects as null and hide the widget. */ destroy(): void; /** Finalizes the creation of the widget. */ @@ -4096,13 +4083,7 @@ declare module "esri/dijit/HomeButton" { * @param params Various parameters to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.HomeButtonOptions, srcNodeRef: Node); - /** - * Creates a new HomeButton dijit using the given DOM node. - * @param params Various parameters to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.HomeButtonOptions, srcNodeRef: string); + constructor(params: esri.HomeButtonOptions, srcNodeRef: Node | string); /** Destroys the widget. */ destroy(): void; /** Hides the widget. */ @@ -4134,19 +4115,36 @@ declare module "esri/dijit/HorizontalSlider" { * @param params Set of parameters used to specify the HorizontalSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.HorizontalSliderOptions, srcNodeRef: Node); - /** - * Creates a new HorizontalSlider widget. - * @param params Set of parameters used to specify the HorizontalSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.HorizontalSliderOptions, srcNodeRef: string); + constructor(params: esri.HorizontalSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } export = HorizontalSlider; } +declare module "esri/dijit/ImageServiceMeasure" { + import esri = require("esri"); + import SimpleFillSymbol = require("esri/symbols/SimpleFillSymbol"); + import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); + import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); + + /** This widget allows you to perform measurements on image services. */ + class ImageServiceMeasure { + /** Symbol to be used when drawing a polygon or extent. */ + fillSymbol: SimpleFillSymbol; + /** Symbol to be used when drawing a line. */ + lineSymbol: SimpleLineSymbol; + /** Symbol to be used when drawing a point. */ + markerSymbol: SimpleMarkerSymbol; + /** + * Creates an instance of the ImageServiceMeasure widget. + * @param params An Object containing constructor options. + */ + constructor(params: esri.ImageServiceMeasureOptions); + } + export = ImageServiceMeasure; +} + declare module "esri/dijit/InfoWindow" { import esri = require("esri"); import InfoWindowBase = require("esri/InfoWindowBase"); @@ -4175,13 +4173,7 @@ declare module "esri/dijit/InfoWindow" { * @param params Optional parameters. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: any, srcNodeRef: Node); - /** - * Create a new Info Window. - * @param params Optional parameters. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Hides the InfoWindow. */ hide(): void; /** @@ -4288,6 +4280,49 @@ declare module "esri/dijit/InfoWindowLite" { export = InfoWindowLite; } +declare module "esri/dijit/LayerList" { + import esri = require("esri"); + import Map = require("esri/map"); + + /** (Currently in beta) The LayerList widget provides a list of layers that allows the toggling of layer visibility. */ + class LayerList { + /** An array of operational layers. */ + layers: any[]; + /** Indicates whether the widget has been loaded. */ + loaded: boolean; + /** Reference to the map. */ + map: Map; + /** Indicates whether to remove underscores from the layer title */ + removeUnderscores: boolean; + /** Indicates whether to show sublayers in the list of layers. */ + sublayers: boolean; + /** CSS Class for uniquely styling the widget. */ + theme: string; + /** Indicates whether to show the widget. */ + visible: boolean; + /** + * Create a new LayerList widget using the given DOM node. + * @param options Set of options used to specify LayerList options. + * @param srcNode Reference or id of the HTML element where the widget should be rendered. + */ + constructor(options: esri.LayerListOptions, srcNode: Node | string); + /** Destroy the LayerList widget. */ + destroy(): void; + /** Reloads all layers and properties that may have changed. */ + refresh(): void; + /** Finalizes the creation of the LayerList widget. */ + startup(): void; + /** Fired when the LayerList widget has fully loaded. */ + on(type: "load", listener: (event: { target: LayerList }) => void): esri.Handle; + /** Fired when refresh is called on the LabelList widget. */ + on(type: "refresh", listener: (event: { target: LayerList }) => void): esri.Handle; + /** Fired when the layer is toggled on/off within the widget. */ + on(type: "toggle", listener: (event: { layerIndex: number; subLayerIndex: number; visible: boolean; target: LayerList }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = LayerList; +} + declare module "esri/dijit/LayerSwipe" { import esri = require("esri"); import Layer = require("esri/layers/layer"); @@ -4320,13 +4355,7 @@ declare module "esri/dijit/LayerSwipe" { * @param params Various parameters to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.LayerSwipeOptions, srcNodeRef: Node); - /** - * Creates a new LayerSwipe dijit using the given DOM node. - * @param params Various parameters to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.LayerSwipeOptions, srcNodeRef: string); + constructor(params: esri.LayerSwipeOptions, srcNodeRef: Node | string); /** Destroys the widget. */ destroy(): void; /** Disables the widget. */ @@ -4356,13 +4385,7 @@ declare module "esri/dijit/Legend" { * @param params Parameters used to configure the dijit. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.LegendOptions, srcNodeRef: Node); - /** - * Creates a new Legend dijit. - * @param params Parameters used to configure the dijit. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: esri.LegendOptions, srcNodeRef: string); + constructor(params: esri.LegendOptions, srcNodeRef: Node | string); /** Destroys the legend. */ destroy(): void; /** Refresh the legend. */ @@ -4418,13 +4441,7 @@ declare module "esri/dijit/LocateButton" { * @param params Various parameters to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.LocateButtonOptions, srcNodeRef: Node); - /** - * Creates a new LocateButton dijit using the given DOM node. - * @param params Various parameters to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.LocateButtonOptions, srcNodeRef: string); + constructor(params: esri.LocateButtonOptions, srcNodeRef: Node | string); /** Clears the point graphic. */ clear(): void; /** Destroys the widget. */ @@ -4460,13 +4477,7 @@ declare module "esri/dijit/Measurement" { * @param params See options list for parameters. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.MeasurementOptions, srcNodeRef: Node); - /** - * Creates a new Measurement widget. - * @param params See options list for parameters. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: esri.MeasurementOptions, srcNodeRef: string); + constructor(params: esri.MeasurementOptions, srcNodeRef: Node | string); /** Remove the measurement graphics and results. */ clearResult(): void; /** Destroy the measurement widget. */ @@ -4486,17 +4497,7 @@ declare module "esri/dijit/Measurement" { * Invoke the measurement functionality of the widget by passing in a previously created geometry. * @param geometry Geometry to be measured. */ - measure(geometry: Point): void; - /** - * Invoke the measurement functionality of the widget by passing in a previously created geometry. - * @param geometry Geometry to be measured. - */ - measure(geometry: Polyline): void; - /** - * Invoke the measurement functionality of the widget by passing in a previously created geometry. - * @param geometry Geometry to be measured. - */ - measure(geometry: Polygon): void; + measure(geometry: Point | Polyline | Polygon): void; /** * Activate or deactivate a tool. * @param toolName The name of the tool to activate or deactivate. @@ -4515,7 +4516,7 @@ declare module "esri/dijit/Measurement" { /** Fires when a measurement is made but the measurement is not complete (single-click). */ on(type: "measure", listener: (event: { geometry: Geometry; toolName: string; unitName: string; values: number; target: Measurement }) => void): esri.Handle; /** Fired when the measurement is complete. */ - on(type: "measure-end", listener: (event: { geometry: Geometry; toolName: string; unitName: string; values: any; target: Measurement }) => void): esri.Handle; + on(type: "measure-end", listener: (event: { geometry: Geometry; toolName: string; unitName: string; values: number[] | number; target: Measurement }) => void): esri.Handle; /** Fires when a measurement operation begins (single-click). */ on(type: "measure-start", listener: (event: { toolName: string; unitName: string; target: Measurement }) => void): esri.Handle; /** Fires when the primary tool is changed. */ @@ -4527,6 +4528,94 @@ declare module "esri/dijit/Measurement" { export = Measurement; } +declare module "esri/dijit/ObliqueViewer" { + import esri = require("esri"); + import ArcGISImageServiceLayer = require("esri/layers/ArcGISImageServiceLayer"); + import Map = require("esri/map"); + import Geometry = require("esri/geometry/Geometry"); + import SpatialReference = require("esri/SpatialReference"); + import Extent = require("esri/geometry/Extent"); + + /** (Currently in beta) The oblique viewer widget, displays images in their native coordinate system using an Image Coordinate System (ICS). */ + class ObliqueViewer { + /** Indicates the current azimuth angle of the viewer. */ + azimuthAngle: number; + /** Image service field that denotes the sensor azimuth value for a record. */ + azimuthField: string; + /** Indicates the tolerance value applied when selecting images for a given azimuth angle value. */ + azimuthTolerance: number; + /** Image service field that denotes the sensor elevation value for a record. */ + elevationField: string; + /** Elevation value between 0 and 90 that differentiates an image as oblique or nadir. */ + elevationThreshold: number; + /** Subset of records, filtered based on current azimuth angle. */ + filteredRecords: any[]; + /** Image service layer to be used as source for oblique images. */ + imageServiceLayer: ArcGISImageServiceLayer; + /** Indicates whether current view is nadir. */ + isNadir: boolean; + /** Map object associated with the widget. */ + map: Map; + /** When true, the widget doesn't refresh itself with new oblique records when the map's extent changes. */ + noQueryOnExtentChange: boolean; + /** Raster info fields to be queried and displayed in the raster list. */ + rasterInfoFields: any[]; + /** When true, the list is populated on data refresh. */ + rasterListRefresh: boolean; + /** Oblique image data that is currently being used by the viewer. */ + records: any[]; + /** Object containing additional information about the raster. */ + selectedRaster: any; + /** Id of the raster currently being displayed. */ + selectedRasterId: number; + /** When true, thumbnail images for records are displayed in the list. */ + showThumbnail: boolean; + /** + * Creates an instance of the ObliqueViewer widget. + * @param params Constructor options. + */ + constructor(params: esri.ObliqueViewerOptions); + /** + * Projects the input geometry to the specified spatial reference. + * @param geometry The geometry to project. + * @param outSpatialReference The spatial reference to project the geometry to. + */ + projectGeometry(geometry: Geometry, outSpatialReference: SpatialReference): any; + /** + * Performs a query on the image service for oblique images covering the input geometry. + * @param geometry The input geometry to use for the search. + */ + search(geometry: Geometry): any; + /** + * Sets the records and extent on the viewer. + * @param records An array of raster data objects. + * @param extent The extent to set the viewer to. + */ + setData(records: any[], extent: Extent): void; + /** + * Projects the given extent to the map's spatial reference and sets the extent. + * @param extent The extent to project the map's spatial reference to. + */ + setExtent(extent: Extent): any; + /** + * Sets the input image (based on the image ID) to the given extent. + * @param id The ID of the raster image. + * @param extent The extent to set the raster image to. + */ + setImage(id: number, extent: Extent): void; + /** Sets the map extent to the currently selected image. */ + zoomToSelectedImage(): void; + /** Fires when the azimuth is changed. */ + on(type: "azimuth-change", listener: (event: { azimuth: number; target: ObliqueViewer }) => void): esri.Handle; + /** Fires when the selected raster is changed. */ + on(type: "raster-select", listener: (event: { selectedRasterId: number; target: ObliqueViewer }) => void): esri.Handle; + /** Fires when the viewer records are refreshed. */ + on(type: "records-refresh", listener: (event: { filteredRecords: any[]; records: any[]; target: ObliqueViewer }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ObliqueViewer; +} + declare module "esri/dijit/OpacitySlider" { import esri = require("esri"); import RendererSlider = require("esri/dijit/RendererSlider"); @@ -4566,13 +4655,7 @@ declare module "esri/dijit/OpacitySlider" { * @param params Set of parameters used to specify the OpacitySlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.OpacitySliderOptions, srcNodeRef: Node); - /** - * Creates a new OpacitySlider widget within the provided DOM node srcNodeRef. - * @param params Set of parameters used to specify the OpacitySlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.OpacitySliderOptions, srcNodeRef: string); + constructor(params: esri.OpacitySliderOptions, srcNodeRef: Node | string); /** Fires when OpacitySlider changes. */ on(type: "change", listener: (event: { opacityInfo: any; target: OpacitySlider }) => void): esri.Handle; /** Fires when minValue or maxValue of OpacitySlider changes. */ @@ -4586,21 +4669,18 @@ declare module "esri/dijit/OpacitySlider" { declare module "esri/dijit/OverviewMap" { import esri = require("esri"); + import Map = require("esri/map"); /** The OverviewMap widget displays the current extent of the map within the context of a larger area. */ class OverviewMap { + /** The Map instance displayed in the OverviewMap widget's container. */ + overviewMap: Map; /** * Creates a new OverviewMap object. * @param params Parameters that define the functionality of the OverviewMap widget. * @param srcNodeRef HTML element where the widget should be rendered. */ - constructor(params: esri.OverviewMapOptions, srcNodeRef: Node); - /** - * Creates a new OverviewMap object. - * @param params Parameters that define the functionality of the OverviewMap widget. - * @param srcNodeRef HTML element where the widget should be rendered. - */ - constructor(params: esri.OverviewMapOptions, srcNodeRef: string); + constructor(params: esri.OverviewMapOptions, srcNodeRef: Node | string); /** Releases the resources used by the dijit. */ destroy(): void; /** Hide the overview map. */ @@ -4682,13 +4762,7 @@ declare module "esri/dijit/Popup" { * @param options Optional parameters. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(options: esri.PopupOptions, srcNodeRef: Node); - /** - * Create a new Popup object. - * @param options Optional parameters. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(options: esri.PopupOptions, srcNodeRef: string); + constructor(options: esri.PopupOptions, srcNodeRef: Node | string); /** Removes all features and destroys any pending deferreds. */ clearFeatures(): void; /** Destroy the popup. */ @@ -4728,32 +4802,17 @@ declare module "esri/dijit/Popup" { * Set the content for the info window. * @param content The content for the info window. */ - setContent(content: string): void; - /** - * Set the content for the info window. - * @param content The content for the info window. - */ - setContent(content: Function): void; + setContent(content: string | Function): void; /** * Associate an array of features or an array of deferreds that return features with the info window. * @param features An array of features or deferreds. */ - setFeatures(features: Graphic[]): void; - /** - * Associate an array of features or an array of deferreds that return features with the info window. - * @param features An array of features or deferreds. - */ - setFeatures(features: any[]): void; + setFeatures(features: Graphic[] | any[]): void; /** * Sets the info window title. * @param title The text for the title. */ - setTitle(title: string): void; - /** - * Sets the info window title. - * @param title The text for the title. - */ - setTitle(title: Function): void; + setTitle(title: string | Function): void; /** * Display the info window at the specified location. * @param location An instance of esri.geometry.Point that represents the geographic location to display the popup. @@ -4796,13 +4855,7 @@ declare module "esri/dijit/PopupMobile" { * @param options Optional parameters. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(options: esri.PopupMobileOptions, srcNodeRef: Node); - /** - * Create a new PopupMobile object. - * @param options Optional parameters. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(options: esri.PopupMobileOptions, srcNodeRef: string); + constructor(options: esri.PopupMobileOptions, srcNodeRef: Node | string); /** Removes all features and destroys any pending deferreds. */ clearFeatures(): void; /** Destroy the popup. */ @@ -4824,32 +4877,17 @@ declare module "esri/dijit/PopupMobile" { * Set the content for the info window. * @param content The content for the info window. */ - setContent(content: string): void; - /** - * Set the content for the info window. - * @param content The content for the info window. - */ - setContent(content: Function): void; + setContent(content: string | Function): void; /** * Associate an array of features or an array of deferreds that return features with the info window. * @param features An array of features or deferreds. */ - setFeatures(features: Graphic[]): any; - /** - * Associate an array of features or an array of deferreds that return features with the info window. - * @param features An array of features or deferreds. - */ - setFeatures(features: any[]): any; + setFeatures(features: Graphic[] | any[]): void; /** * Sets the info window title. * @param title The text for the title. */ - setTitle(title: string): void; - /** - * Sets the info window title. - * @param title The text for the title. - */ - setTitle(title: Function): void; + setTitle(title: string | Function): void; /** * Display the info window at the specified location. * @param location An instance of esri.geometry.Point that represents the geographic location to display the popup. @@ -4901,13 +4939,7 @@ declare module "esri/dijit/Print" { * @param params Parameters for the print widget. * @param srcNodeRef HTML element where the print widget button and drop down list will be rendered. */ - constructor(params: esri.PrintOptions, srcNodeRef: Node); - /** - * Creates a new Print widget. - * @param params Parameters for the print widget. - * @param srcNodeRef HTML element where the print widget button and drop down list will be rendered. - */ - constructor(params: esri.PrintOptions, srcNodeRef: string); + constructor(params: esri.PrintOptions, srcNodeRef: Node | string); /** Destroys the print widget. */ destroy(): void; /** Hide the print widget. */ @@ -4950,7 +4982,7 @@ declare module "esri/dijit/RendererSlider" { /** Toggle for showing the black handle bars. */ showHandles: boolean; /** Flexible toggle for showing labels e.g. */ - showLabels: any; + showLabels: boolean | string[]; /** Toggle for showing the horizontal line indicators from the center of the handle. */ showTicks: boolean; /** Handle positions represented as numbers that fall between minimum and maximum. */ @@ -4960,13 +4992,7 @@ declare module "esri/dijit/RendererSlider" { * @param params Set of parameters used to specify the RendererSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.RendererSliderOptions, srcNodeRef: Node); - /** - * Creates a new RendererSlider widget. - * @param params Set of parameters used to specify the RendererSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.RendererSliderOptions, srcNodeRef: string); + constructor(params: esri.RendererSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the user actively slides the handle. */ @@ -4988,13 +5014,7 @@ declare module "esri/dijit/Scalebar" { * @param params Parameters used to configure the widget. * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.ScalebarOptions, srcNodeRef?: Node); - /** - * Creates a new Scalebar dijit. - * @param params Parameters used to configure the widget. - * @param srcNodeRef Reference or id of the HTML element where the widget should be rendered. - */ - constructor(params: esri.ScalebarOptions, srcNodeRef?: string); + constructor(params: esri.ScalebarOptions, srcNodeRef?: Node | string); /** Destroy the scalebar. */ destroy(): void; /** Hide the scalebar dijit. */ @@ -5026,7 +5046,7 @@ declare module "esri/dijit/Search" { addLayersFromMap: boolean; /** Indicates whether to automatically navigate to the selected result. */ autoNavigate: boolean; - /** Indicates whether to automatically select the first result. */ + /** Indicates whether to automatically select and zoom to the first geocoded result. */ autoSelect: boolean; /** Indicates whether to enable an option to collapse/expand the search into a button. */ enableButtonMode: boolean; @@ -5089,13 +5109,7 @@ declare module "esri/dijit/Search" { * @param options Set of options used to specify Search options. * @param srcNode Reference or id of the HTML element where the widget should be rendered. */ - constructor(options: esri.SearchOptions, srcNode: Node); - /** - * Create a new Search widget using the given DOM node. - * @param options Set of options used to specify Search options. - * @param srcNode Reference or id of the HTML element where the widget should be rendered. - */ - constructor(options: esri.SearchOptions, srcNode: string); + constructor(options: esri.SearchOptions, srcNode: Node | string); /** Unfocus the widget's text input. */ blur(): void; /** Clears the current value, search results, suggest results, graphic, and/or graphics layer. */ @@ -5112,39 +5126,25 @@ declare module "esri/dijit/Search" { * Get the value of the property from the Search widget. * @param name String value indicating the property to get. */ - get(name: string): any; + get(name: string): any | boolean | Layer | Graphic | InfoTemplate | number | TextSymbol | Map | any[] | string; /** Hides the Search widget. */ hide(): void; /** * Depending on the sources specified, search() queries the feature layer(s) and/or performs address matching using any specified Locator(s) and returns any applicable results. * @param value This value can be a string, geometry, suggest candidate object, or an array of [latitude,longitude]. */ - search(value?: string): any; - /** - * Depending on the sources specified, search() queries the feature layer(s) and/or performs address matching using any specified Locator(s) and returns any applicable results. - * @param value This value can be a string, geometry, suggest candidate object, or an array of [latitude,longitude]. - */ - search(value?: Geometry): any; - /** - * Depending on the sources specified, search() queries the feature layer(s) and/or performs address matching using any specified Locator(s) and returns any applicable results. - * @param value This value can be a string, geometry, suggest candidate object, or an array of [latitude,longitude]. - */ - search(value?: any): any; - /** - * Depending on the sources specified, search() queries the feature layer(s) and/or performs address matching using any specified Locator(s) and returns any applicable results. - * @param value This value can be a string, geometry, suggest candidate object, or an array of [latitude,longitude]. - */ - search(value?: any[]): any; + search(value?: string | Geometry | any | number[]): any; /** * Selects a result. * @param value The result object to select. */ select(value: any): void; /** - * Set the value of a non "read-only" property from the widget. + * Sets the value of a non "read-only" property from the widget. * @param name The string value to set. + * @param value The value to set the specified property to. */ - set(name: string): any; + set(name: string, value: any | boolean | Layer | Graphic | InfoTemplate | number | TextSymbol | Map | any[] | string): void; /** Show the Search widget. */ show(): void; /** Finalizes the creation of the Search widget. */ @@ -5162,12 +5162,12 @@ declare module "esri/dijit/Search" { on(type: "focus", listener: (event: { target: Search }) => void): esri.Handle; /** Fired when the search widget has fully loaded. */ on(type: "load", listener: (event: { target: Search }) => void): esri.Handle; - /** Fired when the search method is called and returns its results. */ - on(type: "search-results", listener: (event: { activeSourceIndex: number; error: Error; numResults: number; results: any; value: string; target: Search }) => void): esri.Handle; + /** Fires when the search method is called and returns its results. */ + on(type: "search-results", listener: (event: { activeSourceIndex: number; errors: Error[]; numErrors: number; numResults: number; results: any[]; value: string; target: Search }) => void): esri.Handle; /** Fired when a search result is selected. */ on(type: "select-result", listener: (event: { result: any; source: any; sourceIndex: number; target: Search }) => void): esri.Handle; /** Fired when the suggest method is called and returns its results. */ - on(type: "suggest-results", listener: (event: { activeSourceIndex: number; error: Error; numResults: number; results: any; value: string; target: Search }) => void): esri.Handle; + on(type: "suggest-results", listener: (event: { activeSourceIndex: number; errors: Error[]; numErrors: number; numResults: number; results: any[]; value: string; target: Search }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; } export = Search; @@ -5215,13 +5215,7 @@ declare module "esri/dijit/SizeInfoSlider" { * @param params Set of parameters used to specify the SizeInfoSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.SizeInfoSliderOptions, srcNodeRef: Node); - /** - * Creates a new SizeInfoSlider widget. - * @param params Set of parameters used to specify the SizeInfoSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.SizeInfoSliderOptions, srcNodeRef: string); + constructor(params: esri.SizeInfoSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the SizeInfoSlider properties change. */ @@ -5248,13 +5242,7 @@ declare module "esri/dijit/SymbolStyler" { * @param params Set of parameters used to specify the SymbolStyler widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: esri.SymbolStylerOptions, srcNodeRef: Node); - /** - * Creates a new SymbolStyler widget. - * @param params Set of parameters used to specify the SymbolStyler widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: esri.SymbolStylerOptions, srcNodeRef: string); + constructor(params: esri.SymbolStylerOptions, srcNodeRef: Node | string); /** * Sets the symbol to edit. * @param symbol Symbol to edit. @@ -5292,13 +5280,7 @@ declare module "esri/dijit/TimeSlider" { * @param params Parameters for the time slider object. * @param srcNodeRef HTML element where the time slider should be rendered. */ - constructor(params: esri.TimeSliderOptions, srcNodeRef: Node); - /** - * Creates a new TimeSlider object. - * @param params Parameters for the time slider object. - * @param srcNodeRef HTML element where the time slider should be rendered. - */ - constructor(params: esri.TimeSliderOptions, srcNodeRef: string); + constructor(params: esri.TimeSliderOptions, srcNodeRef: Node | string); /** * The specified number of time stops are created for the input time extent. * @param timeExtent The time extent used to define the time slider's start and end time stops. @@ -5395,13 +5377,7 @@ declare module "esri/dijit/VisibleScaleRangeSlider" { * @param params Set of parameters used to specify the VisibleScaleRangeSlider widget options. * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new VisibleScaleRangeSlider widget. - * @param params Set of parameters used to specify the VisibleScaleRangeSlider widget options. - * @param srcNodeRef Reference or ID of the HTMLElement where the widget should be rendered. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: esri.VisibleScaleRangeSliderOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Dispatched whenever minScale or maxScale changes. */ @@ -5441,10 +5417,14 @@ declare module "esri/dijit/analysis/AggregatePoints" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** An array of attribute field names and statistic types that you would like to aggregate for all points within each polygon. */ @@ -5454,13 +5434,7 @@ declare module "esri/dijit/analysis/AggregatePoints" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.AggregatePointsOptions, srcNodeRef: Node); - /** - * Creates a new AggregatePoints dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.AggregatePointsOptions, srcNodeRef: string); + constructor(params: esri.AggregatePointsOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5478,8 +5452,14 @@ declare module "esri/dijit/analysis/AnalysisBase" { folderId: string; /** Sets the selected folder of the select folder dropdown, based on the provided folderName, when showSelectFolder is true. */ folderName: string; + /** The self response of the Portal. */ + portalSelf: any; /** The URL to the ArcGIS.com site or in-house portal where the GP server is hosted, for example "http://www.arcgis.com". */ portalUrl: string; + /** When true, adds an option to the UI that allows users to choose ready to use analysis layers from the Living Atlas Analysis Layers. */ + showReadyToUseLayers: boolean; + /** Overrides the default widget title with a custom title. */ + title: string; /** * Cancels an analysis job that is being processed. * @param jobInfo An object containing job information including job ID, status, message, etc returned by the job-status event. @@ -5554,10 +5534,14 @@ declare module "esri/dijit/analysis/CalculateDensity" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5565,13 +5549,7 @@ declare module "esri/dijit/analysis/CalculateDensity" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new CalculateDensity dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5602,10 +5580,14 @@ declare module "esri/dijit/analysis/ConnectOriginsToDestinations" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5613,13 +5595,7 @@ declare module "esri/dijit/analysis/ConnectOriginsToDestinations" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.ConnectOriginsToDestinationsOptions, srcNodeRef: Node); - /** - * Creates a new ConnectOriginsToDestinations dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.ConnectOriginsToDestinationsOptions, srcNodeRef: string); + constructor(params: esri.ConnectOriginsToDestinationsOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5646,10 +5622,14 @@ declare module "esri/dijit/analysis/CreateBuffers" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** The linear unit to be used with the distance value(s). */ @@ -5659,13 +5639,7 @@ declare module "esri/dijit/analysis/CreateBuffers" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.CreateBuffersOptions, srcNodeRef: Node); - /** - * Creates a new CreateBuffers dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.CreateBuffersOptions, srcNodeRef: string); + constructor(params: esri.CreateBuffersOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5698,10 +5672,14 @@ declare module "esri/dijit/analysis/CreateDriveTimeAreas" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5709,13 +5687,7 @@ declare module "esri/dijit/analysis/CreateDriveTimeAreas" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.CreateDriveTimeAreasOptions, srcNodeRef: Node); - /** - * Creates a new CreateDriveTimeAreas dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.CreateDriveTimeAreasOptions, srcNodeRef: string); + constructor(params: esri.CreateDriveTimeAreasOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5748,10 +5720,14 @@ declare module "esri/dijit/analysis/CreateViewshed" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** The height of structures or people on the ground used to establish visibility. */ @@ -5763,13 +5739,7 @@ declare module "esri/dijit/analysis/CreateViewshed" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.CreateViewshedOptions, srcNodeRef: Node); - /** - * Creates a new CreateViewshed dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.CreateViewshedOptions, srcNodeRef: string); + constructor(params: esri.CreateViewshedOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5796,10 +5766,14 @@ declare module "esri/dijit/analysis/CreateWatersheds" { searchUnits: string; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5807,13 +5781,7 @@ declare module "esri/dijit/analysis/CreateWatersheds" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.CreateWatershedsOptions, srcNodeRef: Node); - /** - * Creates a new CreateWatersheds dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.CreateWatershedsOptions, srcNodeRef: string); + constructor(params: esri.CreateWatershedsOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5836,10 +5804,14 @@ declare module "esri/dijit/analysis/DeriveNewLocations" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5847,13 +5819,7 @@ declare module "esri/dijit/analysis/DeriveNewLocations" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new DeriveNewLocations dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5880,10 +5846,14 @@ declare module "esri/dijit/analysis/DissolveBoundaries" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** An array of field names and statistical summary types that you wish to calculate from the polygons that are dissolved together. */ @@ -5893,13 +5863,7 @@ declare module "esri/dijit/analysis/DissolveBoundaries" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.DissolveBoundariesOptions, srcNodeRef: Node); - /** - * Creates a new DissolveBoundaries dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.DissolveBoundariesOptions, srcNodeRef: string); + constructor(params: esri.DissolveBoundariesOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5928,10 +5892,14 @@ declare module "esri/dijit/analysis/EnrichLayer" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** When true, you can specify a time for traffic condition under Define areas to enrich - Driving Time. */ @@ -5941,13 +5909,7 @@ declare module "esri/dijit/analysis/EnrichLayer" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.EnrichLayerOptions, srcNodeRef: Node); - /** - * Creates a new EnrichLayer dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.EnrichLayerOptions, srcNodeRef: string); + constructor(params: esri.EnrichLayerOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -5976,10 +5938,14 @@ declare module "esri/dijit/analysis/ExtractData" { outputLayerName: string; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -5987,13 +5953,7 @@ declare module "esri/dijit/analysis/ExtractData" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.ExtractDataOptions, srcNodeRef: Node); - /** - * Creates a new ExtractData dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.ExtractDataOptions, srcNodeRef: string); + constructor(params: esri.ExtractDataOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6016,10 +5976,14 @@ declare module "esri/dijit/analysis/FindExistingLocations" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6027,13 +5991,7 @@ declare module "esri/dijit/analysis/FindExistingLocations" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new FindExistingLocations dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6068,10 +6026,14 @@ declare module "esri/dijit/analysis/FindHotSpots" { returnProcessInfo: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6079,13 +6041,7 @@ declare module "esri/dijit/analysis/FindHotSpots" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.FindHotSpotsOptions, srcNodeRef: Node); - /** - * Creates a new FindHotSpots dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.FindHotSpotsOptions, srcNodeRef: string); + constructor(params: esri.FindHotSpotsOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6122,10 +6078,14 @@ declare module "esri/dijit/analysis/FindNearest" { searchCutoffUnits: string; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6133,13 +6093,7 @@ declare module "esri/dijit/analysis/FindNearest" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.FindNearestOptions, srcNodeRef: Node); - /** - * Creates a new FindNearest dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.FindNearestOptions, srcNodeRef: string); + constructor(params: esri.FindNearestOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6165,10 +6119,14 @@ declare module "esri/dijit/analysis/FindSimilarLocations" { searchLayers: FeatureLayer[]; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6176,13 +6134,7 @@ declare module "esri/dijit/analysis/FindSimilarLocations" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new FindSimilarLocations dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the select tool option is activated. */ @@ -6222,10 +6174,14 @@ declare module "esri/dijit/analysis/InterpolatePoints" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6233,13 +6189,7 @@ declare module "esri/dijit/analysis/InterpolatePoints" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new InterpolatePoints dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6270,10 +6220,14 @@ declare module "esri/dijit/analysis/MergeLayers" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** @@ -6281,13 +6235,7 @@ declare module "esri/dijit/analysis/MergeLayers" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.MergeLayersOptions, srcNodeRef: Node); - /** - * Creates a new MergeLayers dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.MergeLayersOptions, srcNodeRef: string); + constructor(params: esri.MergeLayersOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6316,10 +6264,14 @@ declare module "esri/dijit/analysis/OverlayLayers" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** When the distance between features is less than the tolerance, the features in the overlay layer will snap to the features in the input layer. */ @@ -6331,13 +6283,7 @@ declare module "esri/dijit/analysis/OverlayLayers" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.OverlayLayersOptions, srcNodeRef: Node); - /** - * Creates a new OverlayLayers dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.OverlayLayersOptions, srcNodeRef: string); + constructor(params: esri.OverlayLayersOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6370,10 +6316,14 @@ declare module "esri/dijit/analysis/PlanRoutes" { routeCount: number; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** Provide the locations where the people or vehicles start their routes. */ @@ -6385,13 +6335,7 @@ declare module "esri/dijit/analysis/PlanRoutes" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new PlanRoutes dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6428,10 +6372,14 @@ declare module "esri/dijit/analysis/SummarizeNearby" { shapeUnits: string; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** An array of possible statistics attribute field names and summary types that you wish to calculate for all nearby features. */ @@ -6451,13 +6399,7 @@ declare module "esri/dijit/analysis/SummarizeNearby" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.SummarizeNearbyOptions, srcNodeRef: Node); - /** - * Creates a new SummarizeNearby dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.SummarizeNearbyOptions, srcNodeRef: string); + constructor(params: esri.SummarizeNearbyOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6486,10 +6428,14 @@ declare module "esri/dijit/analysis/SummarizeWithin" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** A list of field names and statistical summary type that you wish to calculate for all features in SummaryLayer that are within each polygon in sumWithinLayer. */ @@ -6505,13 +6451,7 @@ declare module "esri/dijit/analysis/SummarizeWithin" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: esri.SummarizeWithinOptions, srcNodeRef: Node); - /** - * Creates a new SummarizeWithin dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: esri.SummarizeWithinOptions, srcNodeRef: string); + constructor(params: esri.SummarizeWithinOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6538,10 +6478,14 @@ declare module "esri/dijit/analysis/TraceDownstream" { returnFeatureCollection: boolean; /** When true, the choose extent checkbox will be shown. */ showChooseExtent: boolean; + /** Indicates whether to show the close icon on the widget's user interface. */ + showCloseIcon: boolean; /** When true, the show credit option is visible. */ showCredits: boolean; /** When true, the help links will be shown. */ showHelp: boolean; + /** Indicates whether to display a drop down menu listing valid input analysis layers. */ + showSelectAnalysisLayer: boolean; /** When true, the select folder dropdown will be shown. */ showSelectFolder: boolean; /** The trace line will be split into multiple lines where each line is of the specified length. */ @@ -6553,13 +6497,7 @@ declare module "esri/dijit/analysis/TraceDownstream" { * @param params Various options to configure this dijit. * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new TraceDownstream dijit using the given DOM node. - * @param params Various options to configure this dijit. - * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; } @@ -6596,13 +6534,7 @@ declare module "esri/dijit/editing/AttachmentEditor" { * @param params No parameter options. * @param srcNodeRef HTML element where the widget is rendered. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new AttachmentEditor object. - * @param params No parameter options. - * @param srcNodeRef HTML element where the widget is rendered. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** * Display the attachment editor. * @param graphic Graphic, with attachments, to display in the attachment editor. @@ -6655,6 +6587,7 @@ declare module "esri/dijit/editing/Delete" { declare module "esri/dijit/editing/Editor" { import esri = require("esri"); + import Edit = require("esri/toolbars/edit"); /** The Editor widget provides out-of-the-box editing capabilities using an editable layer in a Feature Service. */ class Editor { @@ -6678,18 +6611,14 @@ declare module "esri/dijit/editing/Editor" { static CREATE_TOOL_RECTANGLE: any; /** Triangle tool */ static CREATE_TOOL_TRIANGLE: any; + /** The default Edit toolbar instance. */ + editToolbar: Edit; /** * Creates a new Editor object. * @param params Parameters that define the functionality of the editor widget. * @param srcNodeRef HTML element where the widget should be rendered. */ - constructor(params: esri.EditorOptions, srcNodeRef: Node); - /** - * Creates a new Editor object. - * @param params Parameters that define the functionality of the editor widget. - * @param srcNodeRef HTML element where the widget should be rendered. - */ - constructor(params: esri.EditorOptions, srcNodeRef: string); + constructor(params: esri.EditorOptions, srcNodeRef: Node | string); /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the widget has fully loaded. */ @@ -6713,13 +6642,7 @@ declare module "esri/dijit/editing/TemplatePicker" { * @param params FeatureLayers or items are required all other parameters are optional. * @param srcNodeRef HTML element where the TemplatePicker will be rendered. */ - constructor(params: esri.TemplatePickerOptions, srcNodeRef: Node); - /** - * Creates a new TemplatePicker object that displays a gallery of templates from the input feature layers or items. - * @param params FeatureLayers or items are required all other parameters are optional. - * @param srcNodeRef HTML element where the TemplatePicker will be rendered. - */ - constructor(params: esri.TemplatePickerOptions, srcNodeRef: string); + constructor(params: esri.TemplatePickerOptions, srcNodeRef: Node | string); /** * Get or set the properties of the template picker. * @param name Name of the attribute of interest. @@ -6791,13 +6714,7 @@ declare module "esri/dijit/geoenrichment/DataBrowser" { * @param options Optional parameters used to create the layer. * @param srcNodeRef Reference or id of an HTML element where the DataBrowser should be rendered. */ - constructor(options: esri.DataBrowserOptions, srcNodeRef: Node); - /** - * Creates a new DataBrowser dijit using the given DOM node. - * @param options Optional parameters used to create the layer. - * @param srcNodeRef Reference or id of an HTML element where the DataBrowser should be rendered. - */ - constructor(options: esri.DataBrowserOptions, srcNodeRef: string); + constructor(options: esri.DataBrowserOptions, srcNodeRef: Node | string); /** Finalizes the creation of the DataBrowser. */ startup(): void; /** Fires when user clicks the Back button. */ @@ -6816,6 +6733,9 @@ declare module "esri/dijit/geoenrichment/DataBrowser" { declare module "esri/dijit/geoenrichment/InfoGraphic" { import esri = require("esri"); import GeometryStudyArea = require("esri/tasks/geoenrichment/GeometryStudyArea"); + import RingBuffer = require("esri/tasks/geoenrichment/RingBuffer"); + import DriveBuffer = require("esri/tasks/geoenrichment/DriveBuffer"); + import IntersectingGeographies = require("esri/tasks/geoenrichment/IntersectingGeographies"); import FeatureSet = require("esri/tasks/FeatureSet"); /** Displays an Infographic of one or more variables that describe the geographic context of a location. */ @@ -6833,7 +6753,7 @@ declare module "esri/dijit/geoenrichment/InfoGraphic" { /** The study area for this Infographic. */ studyArea: GeometryStudyArea; /** The options to apply to the study area. */ - studyAreaOptions: any; + studyAreaOptions: RingBuffer | DriveBuffer | IntersectingGeographies; /** An HTML template string used to define the Infographic subtitle. */ subtitle: string; /** The title of the Infographic. */ @@ -6847,13 +6767,7 @@ declare module "esri/dijit/geoenrichment/InfoGraphic" { * @param params Various optional parameters that can be used to configure the dijit. * @param srcNodeRef Reference or id of an HTML element where the Infographic should be rendered. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new Infographic dijit using the given DOM node. - * @param params Various optional parameters that can be used to configure the dijit. - * @param srcNodeRef Reference or id of an HTML element where the Infographic should be rendered. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** * Define the infographic data. * @param data Specify the FeatureSet containing the custom data to display in the Infographic. @@ -6901,13 +6815,7 @@ declare module "esri/dijit/geoenrichment/InfographicsCarousel" { * @param params Various optional parameters that can be used to configure the dijit. * @param srcNodeRef Reference or id of an HTML element where the Directions widget should be rendered. */ - constructor(params: any, srcNodeRef: Node); - /** - * Creates a new InfographicsCarousel dijit using the given DOM node. - * @param params Various optional parameters that can be used to configure the dijit. - * @param srcNodeRef Reference or id of an HTML element where the Directions widget should be rendered. - */ - constructor(params: any, srcNodeRef: string); + constructor(params: any, srcNodeRef: Node | string); /** Finalizes the creation of this dijit. */ startup(): void; /** Fires if an error occurs in retrieving data for the study area. */ @@ -6924,10 +6832,14 @@ declare module "esri/dijit/geoenrichment/InfographicsCarousel" { } declare module "esri/dijit/geoenrichment/InfographicsOptions" { + import RingBuffer = require("esri/tasks/geoenrichment/RingBuffer"); + import DriveBuffer = require("esri/tasks/geoenrichment/DriveBuffer"); + import IntersectingGeographies = require("esri/tasks/geoenrichment/IntersectingGeographies"); + /** InfographicsOptions is used to customize and configure the Infographic's included in a InfographicCarousel. */ class InfographicsOptions { /** The options to apply to the study area. */ - studyAreaOptions: any; + studyAreaOptions: RingBuffer | DriveBuffer | IntersectingGeographies; /** The name of the css theme used to format the InfographicsCarousel. */ theme: string; /** @@ -6977,19 +6889,7 @@ declare module "esri/dijit/util/busyIndicator" { * @param target The String (Node id, dijit/_WidgetBase id), HTMLElement reference (Node), or dijit/_WidgetBase. * @param params (Optional) The params options can be used when needing more fine-grained control. */ - create(target: string, params?: any): any; - /** - * Creates a busy indicator on a target. - * @param target The String (Node id, dijit/_WidgetBase id), HTMLElement reference (Node), or dijit/_WidgetBase. - * @param params (Optional) The params options can be used when needing more fine-grained control. - */ - create(target: HTMLElement, params?: any): any; - /** - * Creates a busy indicator on a target. - * @param target The String (Node id, dijit/_WidgetBase id), HTMLElement reference (Node), or dijit/_WidgetBase. - * @param params (Optional) The params options can be used when needing more fine-grained control. - */ - create(target: any, params?: any): any; + create(target: string | HTMLElement | any, params?: any): any; }; export = busyIndicator; } @@ -7003,42 +6903,22 @@ declare module "esri/domUtils" { * Returns the DOM node from HTMLElement or dijit/_WidgetBase. * @param target The HTMLElement or dijit/_WidgetBase to retrieve. */ - getNode(target: HTMLElement): Node; - /** - * Returns the DOM node from HTMLElement or dijit/_WidgetBase. - * @param target The HTMLElement or dijit/_WidgetBase to retrieve. - */ - getNode(target: any): Node; + getNode(target: HTMLElement | any): Node; /** * Hides the HTMLElement or dijit/_WidgetBase. * @param target The HTMLElement or dijit/_WidgetBase. */ - hide(target: HTMLElement): void; - /** - * Hides the HTMLElement or dijit/_WidgetBase. - * @param target The HTMLElement or dijit/_WidgetBase. - */ - hide(target: any): void; + hide(target: HTMLElement | any): void; /** * Shows the HTMLElement or dijit/_WidgetBase. * @param target The HTMLElement or dijit/_WidgetBase. */ - show(target: HTMLElement): void; - /** - * Shows the HTMLElement or dijit/_WidgetBase. - * @param target The HTMLElement or dijit/_WidgetBase. - */ - show(target: any): void; + show(target: HTMLElement | any): void; /** * If the target (HTMLElement or dijit/_WidgetBase) is currently visible, the target is hidden. * @param target The HTMLElement or dijit/_WidgetBase. */ - toggle(target: HTMLElement): void; - /** - * If the target (HTMLElement or dijit/_WidgetBase) is currently visible, the target is hidden. - * @param target The HTMLElement or dijit/_WidgetBase. - */ - toggle(target: any): void; + toggle(target: HTMLElement | any): void; }; export = domUtils; } @@ -7046,13 +6926,13 @@ declare module "esri/domUtils" { declare module "esri/geometry/Circle" { import esri = require("esri"); import Polygon = require("esri/geometry/Polygon"); - import SpatialReference = require("esri/SpatialReference"); import Point = require("esri/geometry/Point"); + import SpatialReference = require("esri/SpatialReference"); /** A circle (Polygon) created by a specified center point. */ class Circle extends Polygon { /** Center point of the circle. */ - center: any; + center: Point | number[]; /** The radius of the circle based. */ radius: number; /** Unit of the radius. */ @@ -7066,13 +6946,7 @@ declare module "esri/geometry/Circle" { * @param center Center point of the circle. * @param options See options descriptions for further information. */ - constructor(center: Point, options?: esri.CircleOptions1); - /** - * Create a new Circle by specifying an input center location using either an esri.geometry.Point object or a latitude/longitude array and an object with the following optional properties: radius, radiusUnits, geodesic and numberOfPoints. - * @param center Center point of the circle. - * @param options See options descriptions for further information. - */ - constructor(center: number[], options?: esri.CircleOptions1); + constructor(center: Point | number[], options?: esri.CircleOptions1); /** * Create a new Circle by specifying an object with a required center location, defined as a longitude/latitude array or an esri.geometry.Point, and the following additional optional parameters: radius, radiusUnits, geodesic, and numberOfPoints. * @param params If no center parameter is provided, it must be set within the options. @@ -7133,22 +7007,22 @@ declare module "esri/geometry/Extent" { /** Distance between xmin and xmax. */ getWidth(): number; /** - * Returns the interesection extent if the input geometry is an extent that intersects this extent. + * Returns the intersection extent if the input geometry is an extent that intersects this extent. * @param geometry The geometry used to test the intersection. */ - intersects(geometry: Geometry): any; + intersects(geometry: Geometry): Extent | boolean; /** Returns an array with either one Extent that's been shifted to within +/- 180 or two Extents if the original extent intersects the dateline. */ normalize(): Extent[]; /** * Returns a new Extent with x and y offsets. - * @param dx The offset distance in map units for the y-coordinate. - * @param dy The offset distance in map units for the x-coordinate. + * @param dx The offset distance in map units for the x-coordinate. + * @param dy The offset distance in map units for the y-coordinate. */ offset(dx: number, dy: number): Extent; /** Returns an extent with a spatial reference with a custom shifted central meridian if the extent intersects the dateline. */ shiftCentralMeridian(): Extent; /** - * Expands this extent to include the extent of the argument. + * Expands this extent to include the extent of the argument.NOTE: Performing a Union returns a new extent as opposed to modifying the existing extent. * @param extent The minx, miny, maxx, and maxy bounding box. */ union(extent: Extent): Extent; @@ -7224,12 +7098,7 @@ declare module "esri/geometry/Multipoint" { * Adds a point to the Multipoint. * @param point The point to add. */ - addPoint(point: Point): Multipoint; - /** - * Adds a point to the Multipoint. - * @param point The point to add. - */ - addPoint(point: number[]): Multipoint; + addPoint(point: Point | number[]): Multipoint; /** Gets the extent of all the points. */ getExtent(): Extent; /** @@ -7362,22 +7231,12 @@ declare module "esri/geometry/Polygon" { * Create a new polygon by providing an array of geographic coordinate pairs. * @param coordinates An array of geographic coordinates that define the polygon. */ - constructor(coordinates: number[][]); - /** - * Create a new polygon by providing an array of geographic coordinate pairs. - * @param coordinates An array of geographic coordinates that define the polygon. - */ - constructor(coordinates: number[][][]); + constructor(coordinates: number[][] | number[][][]); /** * Adds a ring to the Polygon. * @param ring A polygon ring. */ - addRing(ring: Point[]): Polygon; - /** - * Adds a ring to the Polygon. - * @param ring A polygon ring. - */ - addRing(ring: number[][]): Polygon; + addRing(ring: Point[] | number[][]): Polygon; /** * Checks on the client if the specified point is inside the polygon. * @param point The location defined by an X- and Y- coordinate in map units. @@ -7409,12 +7268,7 @@ declare module "esri/geometry/Polygon" { * Checks if a Polygon ring is clockwise. * @param ring A polygon ring. */ - isClockwise(ring: Point[]): boolean; - /** - * Checks if a Polygon ring is clockwise. - * @param ring A polygon ring. - */ - isClockwise(ring: number[][]): boolean; + isClockwise(ring: Point[] | number[][]): boolean; /** * When true, the polygon is self-intersecting which means that the ring of the polygon crosses itself. * @param polygon The polygon to test for self-intersection. @@ -7466,22 +7320,12 @@ declare module "esri/geometry/Polyline" { * Create a new polyline by providing an array of geographic coordinates. * @param coordinates An array of geographic coordinates that define the polyline. */ - constructor(coordinates: number[][]); - /** - * Create a new polyline by providing an array of geographic coordinates. - * @param coordinates An array of geographic coordinates that define the polyline. - */ - constructor(coordinates: number[][][]); + constructor(coordinates: number[][] | number[][][]); /** * Adds a path to the Polyline. * @param path Path to add to the Polyline. */ - addPath(path: Point[]): Polyline; - /** - * Adds a path to the Polyline. - * @param path Path to add to the Polyline. - */ - addPath(path: number[][]): Polyline; + addPath(path: Point[] | number[][]): Polyline; /** Returns the extent of the Polyline. */ getExtent(): Extent; /** @@ -7601,45 +7445,22 @@ declare module "esri/geometry/geodesicUtils" { declare module "esri/geometry/geometryEngine" { import Geometry = require("esri/geometry/Geometry"); + import Polygon = require("esri/geometry/Polygon"); import Extent = require("esri/geometry/Extent"); import Polyline = require("esri/geometry/Polyline"); import SpatialReference = require("esri/SpatialReference"); import Point = require("esri/geometry/Point"); - /** (Beta at v3.13) A client-side geometry engine. */ + /** (Currently in beta) A client-side geometry engine. */ var geometryEngine: { /** - * Creates buffer polygons at a specified distance around the given geometries. + * Creates planar (or Euclidean) buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. + * @param unit Unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ - buffer(geometry: Geometry, distance: number[], unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry[], distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry, distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry[], distance: number[], unit?: number, unionResults?: boolean): any; + buffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): Polygon | Polygon[]; /** * Calculates the clipped geometry from a target geometry by an envelope. * @param geometry The geometry to be clipped. @@ -7657,13 +7478,7 @@ declare module "esri/geometry/geometryEngine" { * @param geometry The input geometry. * @param merge Whether to merge output geometries. */ - convexHull(geometry: Geometry, merge?: boolean): any; - /** - * Calculates the convex hull of the input geometry. - * @param geometry The input geometry. - * @param merge Whether to merge output geometries. - */ - convexHull(geometry: Geometry[], merge?: boolean): any; + convexHull(geometry: Geometry | Geometry[], merge?: boolean): Geometry | Geometry[]; /** * Indicates if one geometry crosses another geometry. * @param geometry1 The geometry to cross. @@ -7671,7 +7486,7 @@ declare module "esri/geometry/geometryEngine" { */ crosses(geometry1: Geometry, geometry2: Geometry): boolean; /** - * Split the input polyline or polygon where it crosses a cutting polyline. + * Split the input Polyline or Polygon where it crosses a cutting Polyline. * @param geometry The geometry to be cut. * @param cutter The polyline to cut the geometry. */ @@ -7682,36 +7497,30 @@ declare module "esri/geometry/geometryEngine" { * @param maxSegmentLength The maximum segment length allowed. * @param maxSegmentLengthUnit Unit for the maximum segment length. */ - densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit?: number): Geometry; + densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit: string | number): Geometry; /** * Creates the difference of two geometries. - * @param geometry The input geometry. - * @param subtractor The geometry being subtracted. + * @param inputGeometry The input geometry to subtract from. + * @param subtractor The geometry being subtracted from inputGeometry. */ - difference(geometry: Geometry, subtractor: Geometry): any; + difference(inputGeometry: Geometry | Geometry[], subtractor: Geometry): Geometry | Geometry[]; /** - * Creates the difference of two geometries. - * @param geometry The input geometry. - * @param subtractor The geometry being subtracted. - */ - difference(geometry: Geometry[], subtractor: Geometry): any; - /** - * Indicates if one geometry is disjoint from another geometry. - * @param geometry1 The base geometry that is tested for within relationship to the other geometry. + * Indicates if one geometry is disjoint (doesn't intersect in any way) with another geometry. + * @param geometry1 The base geometry that is tested for the "disjoint" relationship to the other geometry. * @param geometry2 The comparison geometry that is tested for the disjoint relationship to the other geometry. */ disjoint(geometry1: Geometry, geometry2: Geometry): boolean; /** - * Calculates the 2D planar shortest distance between two geometries. - * @param geometry1 - * @param geometry2 + * Calculates the shortest planar distance between two geometries. + * @param geometry1 First input geometry. + * @param geometry2 Second input geometry. * @param distanceUnit Units of the return value. */ - distance(geometry1: Geometry, geometry2: Geometry, distanceUnit?: number): number; + distance(geometry1: Geometry, geometry2: Geometry, distanceUnit: string | number): number; /** * Indicates if two geometries are equal. - * @param geometry1 - * @param geometry2 + * @param geometry1 First input geometry. + * @param geometry2 Second input geometry. */ equals(geometry1: Geometry, geometry2: Geometry): boolean; /** @@ -7738,63 +7547,33 @@ declare module "esri/geometry/geometryEngine" { * @param removeDegenerateParts When true, the degenerate parts of the geometry will be removed from the output (may be undesired for drawing). * @param maxDeviationUnit A unit for maximum deviation. */ - generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: number): Geometry; + generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: string | number): Geometry; /** - * Calculates area of input geometry using geographic (geodesic) coordinates. - * @param geometry + * Calculates the area of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - geodesicArea(geometry: Geometry, unit?: number): number; + geodesicArea(geometry: Geometry, unit: string | number): number; /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. + * Creates geodesic buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. + * @param unit Unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ - geodesicBuffer(geometry: Geometry, distance: number[], unit?: number, unionResults?: boolean): any; + geodesicBuffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): Polygon | Polygon[]; /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry[], distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry, distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry[], distance: number[], unit?: number, unionResults?: boolean): any; - /** - * Calculates length of the input geometry using geographic (geodesic) coordinates. - * @param geometry + * Calculates the length of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - geodesicLength(geometry: Geometry, unit?: number): number; + geodesicLength(geometry: Geometry, unit: string | number): number; /** * Creates a new geometry through intersection between two geometries. * @param geometry The input geometry. * @param intersector The geometry being intersected. */ - intersect(geometry: Geometry, intersector: Geometry): any; - /** - * Creates a new geometry through intersection between two geometries. - * @param geometry The input geometry. - * @param intersector The geometry being intersected. - */ - intersect(geometry: Geometry[], intersector: Geometry): any; + intersect(geometry: Geometry | Geometry[], intersector: Geometry): Geometry | Geometry[]; /** * Indicates if one geometry intersects another geometry. * @param geometry1 The geometry that is tested for the intersects relationship to the other geometry. @@ -7802,26 +7581,26 @@ declare module "esri/geometry/geometryEngine" { */ intersects(geometry1: Geometry, geometry2: Geometry): boolean; /** - * Indicates if the given geometry is simple. + * Indicates if the given geometry is topologically simple. * @param geometry Geometry */ isSimple(geometry: Geometry): boolean; /** * Finds the coordinate of the geometry which is closest to the specified point. * @param geometry The geometry to consider. - * @param inputPoint The point to find the nearest coordinate in the geometry for. + * @param inputPoint The point used to search the nearest coordinate in the geometry. */ nearestCoordinate(geometry: Geometry, inputPoint: Point): any; /** * Finds vertex on the geometry nearest to the specified point. * @param geometry The geometry to consider. - * @param inputPoint The point to find the nearest vertex in the geometry for. + * @param inputPoint The point used to search the nearest vertex in the geometry. */ nearestVertex(geometry: Geometry, inputPoint: Point): any; /** * Finds all vertices in the given distance from the specified point, sorted from the closest to the furthest and returns them as an array of objects. * @param geometry The geometry to consider. - * @param inputPoint The point to start from. + * @param inputPoint The point from which to measure. * @param searchRadius The search radius. * @param maxVertexCountToReturn The maximum number number of vertices to return. */ @@ -7829,23 +7608,13 @@ declare module "esri/geometry/geometryEngine" { /** * Creates offset version of the input geometry. * @param geometry The geometries to offset. - * @param distance The offset distance for the Geometries. + * @param offsetDistance The offset distance for the Geometries. * @param offsetUnit Unit for the offset. * @param joinType The join type. * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. */ - offset(geometry: Geometry, distance: number, offsetUnit: number, joinType: number, bevelRatio?: number, flattenError?: number): any; - /** - * Creates offset version of the input geometry. - * @param geometry The geometries to offset. - * @param distance The offset distance for the Geometries. - * @param offsetUnit Unit for the offset. - * @param joinType The join type. - * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. - * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. - */ - offset(geometry: Geometry[], distance: number, offsetUnit: number, joinType: number, bevelRatio?: number, flattenError?: number): any; + offset(geometry: Geometry | Geometry[], offsetDistance: number, offsetUnit: string | number, joinType: string, bevelRatio?: number, flattenError?: number): Geometry | Geometry[]; /** * Indicates if one geometry overlaps another geometry. * @param geometry1 The base geometry that is tested for overlaps relationship to the other geometry. @@ -7853,22 +7622,22 @@ declare module "esri/geometry/geometryEngine" { */ overlaps(geometry1: Geometry, geometry2: Geometry): boolean; /** - * Calculates the area of the input geometry using projected (planar) coordinates. - * @param geometry + * Calculates the area of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - planarArea(geometry: Geometry, unit?: number): number; + planarArea(geometry: Geometry, unit: string | number): number; /** - * Calculates the length of the input geometry using projected (planar) coordinates. - * @param geometry + * Calculates the length of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - planarLength(geometry: Geometry, unit: number): number; + planarLength(geometry: Geometry, unit: string | number): number; /** - * Indicates if the given relation holds for the two geometries. + * Indicates if the given DE-9IM relation holds for the two geometries. * @param geometry1 The first geometry for the relation. * @param geometry2 The second geometry for the relation. - * @param relation The DE-9IM matrix relation encoded as a string. + * @param relation The Dimensionally Extended 9 Intersection Model (DE-9IM) matrix relation (encoded as a string) to test against the relationship of the two geometries. */ relate(geometry1: Geometry, geometry2: Geometry, relation: string): boolean; /** @@ -7880,7 +7649,7 @@ declare module "esri/geometry/geometryEngine" { rotate(geometry: Geometry, angle: number, rotationOrigin?: Point): Geometry; /** * Performs the simplify operation on the geometry which alters the given geometries to make their definitions topologically legal with respect to their geometry type. - * @param geometry Geometry + * @param geometry The geometry to be simplified. */ simplify(geometry: Geometry): Geometry; /** @@ -7888,13 +7657,7 @@ declare module "esri/geometry/geometryEngine" { * @param leftGeometry One of the Geometry instances in the XOR operation. * @param rightGeometry One of the Geometry instances in the XOR operation. */ - symmetricDifference(leftGeometry: Geometry, rightGeometry: Geometry): any; - /** - * Creates the symmetric difference of two geometries. - * @param leftGeometry One of the Geometry instances in the XOR operation. - * @param rightGeometry One of the Geometry instances in the XOR operation. - */ - symmetricDifference(leftGeometry: Geometry[], rightGeometry: Geometry): any; + symmetricDifference(leftGeometry: Geometry | Geometry[], rightGeometry: Geometry): Geometry | Geometry[]; /** * Indicates if one geometry touches another geometry. * @param geometry1 The geometry which may be touching another geometry. @@ -7923,40 +7686,16 @@ declare module "esri/geometry/geometryEngineAsync" { import SpatialReference = require("esri/SpatialReference"); import Point = require("esri/geometry/Point"); - /** (Beta at v3.13) A client-side asynchronous geometry engine. */ + /** (Currently in beta) A client-side asynchronous geometry engine. */ var geometryEngineAsync: { /** - * Creates buffer polygons at a specified distance around the given geometries. + * Creates planar (or Euclidean) buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. + * @param unit Unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ - buffer(geometry: Geometry, distance: number[], unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry[], distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry, distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - buffer(geometry: Geometry[], distance: number[], unit?: number, unionResults?: boolean): any; + buffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): any; /** * Calculates the clipped geometry from a target geometry by an envelope. * @param geometry The geometry to be clipped. @@ -7974,13 +7713,7 @@ declare module "esri/geometry/geometryEngineAsync" { * @param geometry The input geometry. * @param merge Whether to merge output geometries. */ - convexHull(geometry: Geometry, merge?: boolean): any; - /** - * Calculates the convex hull of the input geometry. - * @param geometry The input geometry. - * @param merge Whether to merge output geometries. - */ - convexHull(geometry: Geometry[], merge?: boolean): any; + convexHull(geometry: Geometry | Geometry[], merge?: boolean): any; /** * Indicates if one geometry crosses another geometry. * @param geometry1 The geometry to cross. @@ -7997,43 +7730,37 @@ declare module "esri/geometry/geometryEngineAsync" { * Densify geometries by plotting points between existing vertices. * @param geometry The geometry to be densified. * @param maxSegmentLength The maximum segment length allowed. - * @param maxSegmentLengthUnit Unit for the maximum segment length. + * @param maxSegmentLengthUnit Defaults to the units of the input geometries. */ - densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit?: number): any; + densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit: string | number): any; /** * Creates the difference of two geometries. - * @param geometry The input geometry. + * @param inputGeometry The input geometry to subtract from. * @param subtractor The geometry being subtracted. */ - difference(geometry: Geometry, subtractor: Geometry): any; + difference(inputGeometry: Geometry | Geometry[], subtractor: Geometry): any; /** - * Creates the difference of two geometries. - * @param geometry The input geometry. - * @param subtractor The geometry being subtracted. - */ - difference(geometry: Geometry[], subtractor: Geometry): any; - /** - * Indicates if one geometry is disjoint from another geometry. - * @param geometry1 The base geometry that is tested for within relationship to the other geometry. + * Indicates if one geometry is disjoint (doesn't intersect in any way) with another geometry. + * @param geometry1 The base geometry that is tested for the "disjoint" relationship to the other geometry. * @param geometry2 The comparison geometry that is tested for the disjoint relationship to the other geometry. */ disjoint(geometry1: Geometry, geometry2: Geometry): any; /** - * Calculates the 2D planar shortest distance between two geometries. - * @param geometry1 - * @param geometry2 + * Calculates the shortest planar distance between two geometries. + * @param geometry1 First input geometry. + * @param geometry2 Second input geometry. * @param distanceUnit Units of the return value. */ - distance(geometry1: Geometry, geometry2: Geometry, distanceUnit?: number): any; + distance(geometry1: Geometry, geometry2: Geometry, distanceUnit: string | number): any; /** * Indicates if two geometries are equal. - * @param geometry1 - * @param geometry2 + * @param geometry1 First input geometry. + * @param geometry2 Second input geometry. */ equals(geometry1: Geometry, geometry2: Geometry): any; /** * Returns an object containing additional information about the input spatial reference. - * @param spatialReference The spatial Reference. + * @param spatialReference The input spatial reference. */ extendedSpatialReferenceInfo(spatialReference: SpatialReference): any; /** @@ -8053,65 +7780,35 @@ declare module "esri/geometry/geometryEngineAsync" { * @param geometry The geometry to be generalized. * @param maxDeviation The maximum allowed deviation from the generalized geometry to the original geometry. * @param removeDegenerateParts When true, the degenerate parts of the geometry will be removed from the output (may be undesired for drawing). - * @param maxDeviationUnit A unit for maximum deviation. + * @param maxDeviationUnit Defaults to the units of the input geometries. */ - generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: number): any; + generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: string | number): any; /** - * Calculates area of input geometry using geographic (geodesic) coordinates. - * @param geometry + * Calculates the area of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - geodesicArea(geometry: Geometry, unit?: number): any; + geodesicArea(geometry: Geometry, unit: string | number): any; /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. + * Creates geodesic buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. + * @param unit Unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ - geodesicBuffer(geometry: Geometry, distance: number[], unit?: number, unionResults?: boolean): any; + geodesicBuffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): any; /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry[], distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry, distance: number, unit?: number, unionResults?: boolean): any; - /** - * Creates buffer polygons at a specified distance around the given geometries using geographic (geodesic) coordinates. - * @param geometry The buffer input geometry. - * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distances. - * @param unionResults Whether the output geometries should be unioned into a single polygon. - */ - geodesicBuffer(geometry: Geometry[], distance: number[], unit?: number, unionResults?: boolean): any; - /** - * Calculates length of the input geometry using geographic (geodesic) coordinates. - * @param geometry + * Calculates the length of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - geodesicLength(geometry: Geometry, unit?: number): any; + geodesicLength(geometry: Geometry, unit: string | number): any; /** * Creates a new geometry through intersection between two geometries. * @param geometry The input geometry. * @param intersector The geometry being intersected. */ - intersect(geometry: Geometry, intersector: Geometry): any; - /** - * Creates a new geometry through intersection between two geometries. - * @param geometry The input geometry. - * @param intersector The geometry being intersected. - */ - intersect(geometry: Geometry[], intersector: Geometry): any; + intersect(geometry: Geometry | Geometry[], intersector: Geometry): any; /** * Indicates if one geometry intersects another geometry. * @param geometry1 The geometry that is tested for the intersects relationship to the other geometry. @@ -8119,26 +7816,26 @@ declare module "esri/geometry/geometryEngineAsync" { */ intersects(geometry1: Geometry, geometry2: Geometry): any; /** - * Indicates if the given geometry is simple. + * Indicates if the given geometry is topologically simple. * @param geometry Geometry */ isSimple(geometry: Geometry): any; /** * Finds the coordinate of the geometry which is closest to the specified point. * @param geometry The geometry to consider. - * @param inputPoint The point used to find the nearest coordinate in the geometry. + * @param inputPoint The point used to search the nearest coordinate in the geometry. */ nearestCoordinate(geometry: Geometry, inputPoint: Point): any; /** * Finds vertex on the geometry nearest to the specified point. * @param geometry The geometry to consider. - * @param inputPoint The point to find the nearest vertex in the geometry for. + * @param inputPoint The point used to search the nearest vertex in the geometry. */ nearestVertex(geometry: Geometry, inputPoint: Point): any; /** * Finds all vertices in the given distance from the specified point, sorted from the closest to the furthest and returns them as an array of objects once resolved. * @param geometry The geometry to consider. - * @param inputPoint The point to start from. + * @param inputPoint The point from which to measure. * @param searchRadius The search radius. * @param maxVertexCountToReturn The maximum number number of vertices to return. */ @@ -8146,23 +7843,13 @@ declare module "esri/geometry/geometryEngineAsync" { /** * Creates offset version of the input geometry. * @param geometry The geometries to offset. - * @param distance The offset distance for the Geometries. + * @param offsetDistance The offset distance for the Geometries. * @param offsetUnit Unit for the offset. * @param joinType The join type. * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. */ - offset(geometry: Geometry, distance: number, offsetUnit: number, joinType: number, bevelRatio?: number, flattenError?: number): any; - /** - * Creates offset version of the input geometry. - * @param geometry The geometries to offset. - * @param distance The offset distance for the Geometries. - * @param offsetUnit Unit for the offset. - * @param joinType The join type. - * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. - * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. - */ - offset(geometry: Geometry[], distance: number, offsetUnit: number, joinType: number, bevelRatio?: number, flattenError?: number): any; + offset(geometry: Geometry | Geometry[], offsetDistance: number, offsetUnit: string | number, joinType: string, bevelRatio?: number, flattenError?: number): any; /** * Indicates if one geometry overlaps another geometry. * @param geometry1 The base geometry that is tested for overlaps relationship to the other geometry. @@ -8170,22 +7857,22 @@ declare module "esri/geometry/geometryEngineAsync" { */ overlaps(geometry1: Geometry, geometry2: Geometry): any; /** - * Calculates the area of the input geometry using projected (planar) coordinates. - * @param geometry + * Calculates the area of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - planarArea(geometry: Geometry, unit?: number): any; + planarArea(geometry: Geometry, unit: string | number): any; /** - * Calculates the length of the input geometry using projected (planar) coordinates. - * @param geometry + * Calculates the length of the input geometry. + * @param geometry The input geometry. * @param unit Units of the return value. */ - planarLength(geometry: Geometry, unit: number): any; + planarLength(geometry: Geometry, unit: string | number): any; /** - * Indicates if the given relation holds for the two geometries. + * Indicates if the given DE-9IM relation holds for the two geometries. * @param geometry1 The first geometry for the relation. * @param geometry2 The second geometry for the relation. - * @param relation The DE-9IM matrix relation encoded as a string. + * @param relation The Dimensionally Extended 9 Intersection Model (DE-9IM) matrix relation (encoded as a string) to test against the relationship of the two geometries. */ relate(geometry1: Geometry, geometry2: Geometry, relation: string): any; /** @@ -8197,7 +7884,7 @@ declare module "esri/geometry/geometryEngineAsync" { rotate(geometry: Geometry, angle: number, rotationOrigin?: Point): any; /** * Performs the simplify operation on the geometry which alters the given geometries to make their definitions topologically legal with respect to their geometry type. - * @param geometry Geometry + * @param geometry The geometry to be simplified. */ simplify(geometry: Geometry): any; /** @@ -8205,13 +7892,7 @@ declare module "esri/geometry/geometryEngineAsync" { * @param leftGeometry One of the Geometry instances in the XOR operation. * @param rightGeometry One of the Geometry instances in the XOR operation. */ - symmetricDifference(leftGeometry: Geometry, rightGeometry: Geometry): any; - /** - * Creates the symmetric difference of two geometries. - * @param leftGeometry One of the Geometry instances in the XOR operation. - * @param rightGeometry One of the Geometry instances in the XOR operation. - */ - symmetricDifference(leftGeometry: Geometry[], rightGeometry: Geometry): any; + symmetricDifference(leftGeometry: Geometry | Geometry[], rightGeometry: Geometry): any; /** * Indicates if one geometry touches another geometry. * @param geometry1 The geometry which may be touching another geometry. @@ -8315,17 +7996,7 @@ declare module "esri/geometry/scaleUtils" { * Returns the value of one map unit for the given spatial reference (in meters). * @param sr The spatial reference represented as a SpatialReference class, Number, or String. */ - getUnitValueForSR(sr: SpatialReference): number; - /** - * Returns the value of one map unit for the given spatial reference (in meters). - * @param sr The spatial reference represented as a SpatialReference class, Number, or String. - */ - getUnitValueForSR(sr: number): number; - /** - * Returns the value of one map unit for the given spatial reference (in meters). - * @param sr The spatial reference represented as a SpatialReference class, Number, or String. - */ - getUnitValueForSR(sr: string): number; + getUnitValueForSR(sr: SpatialReference | number | string): number; }; export = scaleUtils; } @@ -8341,8 +8012,8 @@ declare module "esri/geometry/screenUtils" { /** * Converts the geometry argument to map coordinates based on the extent, width, and height of the Map. * @param extent The current extent of the map in map coordinates. - * @param width The current width of the map in map units. - * @param height The current width of the map in map units. + * @param width The current width of the map in screen units. + * @param height The current height of the map in screen units. * @param screenGeometry The geometry to convert from screen to map units. */ toMapGeometry(extent: Extent, width: number, height: number, screenGeometry: Geometry): Geometry; @@ -8350,7 +8021,7 @@ declare module "esri/geometry/screenUtils" { * Converts and returns the argument screen point in map coordinates. * @param extent The current extent of the map in map coordinates. * @param width The current width of the map in screen units. - * @param height The current width of the map in screen units. + * @param height The current height of the map in screen units. * @param screenPoint The screenPoint to convert from screen to map units. */ toMapPoint(extent: Extent, width: number, height: number, screenPoint: ScreenPoint): Point; @@ -8358,7 +8029,7 @@ declare module "esri/geometry/screenUtils" { * Converts the geometry argument to screen coordinates based on the extent, width, and height of the Map. * @param extent The current extent of the map in map coordinates. * @param width The current width of the map in screen units. - * @param height The current width of the map in screen units. + * @param height The current height of the map in screen units. * @param mapGeometry The geometry to convert from map to screen units. */ toScreenGeometry(extent: Extent, width: number, height: number, mapGeometry: Geometry): Geometry; @@ -8366,7 +8037,7 @@ declare module "esri/geometry/screenUtils" { * Converts and returns the argument map point in screen coordinates. * @param extent The current extent of the map in map coordinates. * @param width The current width of the map in screen units. - * @param height The current width of the map in screen units. + * @param height The current height of the map in screen units. * @param mapPoint The point to convert from map to screen units. */ toScreenPoint(extent: Extent, width: number, height: number, mapPoint: Point): ScreenPoint; @@ -8385,25 +8056,7 @@ declare module "esri/geometry/webMercatorUtils" { * @param source An input of type SpatialReference or an object with spatialReference property such as Geometry or Map. * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. */ - canProject(source: SpatialReference, target: any): boolean; - /** - * Returns true if the 'source' can be projected to 'target' by the project() function, or if the 'source' and 'target' is the same spatialReference. - * @param source An input of type SpatialReference or an object with spatialReference property such as Geometry or Map. - * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. - */ - canProject(source: any, target: SpatialReference): boolean; - /** - * Returns true if the 'source' can be projected to 'target' by the project() function, or if the 'source' and 'target' is the same spatialReference. - * @param source An input of type SpatialReference or an object with spatialReference property such as Geometry or Map. - * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. - */ - canProject(source: SpatialReference, target: SpatialReference): boolean; - /** - * Returns true if the 'source' can be projected to 'target' by the project() function, or if the 'source' and 'target' is the same spatialReference. - * @param source An input of type SpatialReference or an object with spatialReference property such as Geometry or Map. - * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. - */ - canProject(source: any, target: any): boolean; + canProject(source: SpatialReference | any, target: SpatialReference | any): boolean; /** * Converts geometry from geographic units to Web Mercator units. * @param geometry The geometry to convert. @@ -8420,13 +8073,7 @@ declare module "esri/geometry/webMercatorUtils" { * @param geometry An input geometry. * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. */ - project(geometry: Geometry, target: SpatialReference): any; - /** - * Project the geometry clientside (if possible). - * @param geometry An input geometry. - * @param target The target spatial reference, of type SpatialReference or an object with spatialReference property such as Map. - */ - project(geometry: Geometry, target: any): any; + project(geometry: Geometry, target: SpatialReference | any): any; /** * Converts geometry from Web Mercator units to geographic units. * @param geometry The geometry to convert. @@ -8474,7 +8121,7 @@ declare module "esri/graphic" { */ constructor(json: Object); /** - * Adds a new attribute or changes the value of an existing attribute on the graphic's node. + * Adds a new attribute or changes the value of an existing attribute on the graphic's DOM node. * @param name The name of the attribute. * @param value The value of the attribute. */ @@ -8578,12 +8225,7 @@ declare module "esri/lang" { * Strips HTML tags from a String or Object. * @param value Object or String to be stripped of HTML tags. */ - stripTags(value: any): any; - /** - * Strips HTML tags from a String or Object. - * @param value Object or String to be stripped of HTML tags. - */ - stripTags(value: string): any; + stripTags(value: any | string): any | string; /** * A wrapper around dojo.string.substitute that can also handle wildcard substitution. * @param data The data object used in the substitution. @@ -8628,6 +8270,8 @@ declare module "esri/layers/ArcGISDynamicMapServiceLayer" { dpi: number; /** Array of DynamicLayerInfos used to change the layer ordering or redefine the map. */ dynamicLayerInfos: DynamicLayerInfo[]; + /** The geodatabase version. */ + gdbVersion: string; /** When true, the layer has attribution data. */ hasAttributionData: boolean; /** The output image type. */ @@ -9133,12 +8777,7 @@ declare module "esri/layers/CodedValueDomain" { * Returns the name of the coded-value associated with the specified code. * @param code The code in which you wish to search for the name. */ - getName(code: number): string; - /** - * Returns the name of the coded-value associated with the specified code. - * @param code The code in which you wish to search for the name. - */ - getName(code: string): string; + getName(code: number | string): string; } export = CodedValueDomain; } @@ -9148,7 +8787,7 @@ declare module "esri/layers/DataAdapterFeatureLayer" { import FeatureLayer = require("esri/layers/FeatureLayer"); import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); - /** (Beta at v3.12) Display features using data that contains location information such as X and Y coordinates, Street address, place names etc using a DataAdapter object to retrieve the features and a LocationProvider to generate their geometries. */ + /** (Currently in beta) Display features using data that contains location information such as X and Y coordinates, Street address, place names etc using a DataAdapter object to retrieve the features and a LocationProvider to generate their geometries. */ class DataAdapterFeatureLayer extends FeatureLayer { /** The DataAdapter object points to data sources that contain non-spatial tables. */ dataAdapter: any; @@ -9357,6 +8996,8 @@ declare module "esri/layers/FeatureLayer" { fields: Field[]; /** The full extent of the layer. */ fullExtent: Extent; + /** The geodatabase version. */ + gdbVersion: string; /** Geometry type of the features in the layer. */ geometryType: string; /** The globalIdField for the layer. */ @@ -9842,7 +9483,7 @@ declare module "esri/layers/GraphicsLayer" { /** A layer that contains one or more Graphic features. */ class GraphicsLayer extends Layer { /** List of attribute fields added as custom data attributes to graphics node. */ - dataAttributes: any; + dataAttributes: string | string[]; /** The array of graphics that make up the layer. */ graphics: Graphic[]; /** The info template for the layer. */ @@ -10212,21 +9853,7 @@ declare module "esri/layers/LabelLayer" { * @param renderer The renderer used to render text labels. * @param textExpression An expression determining what text and field(s) will be displayed as in labels. */ - addFeatureLayer(featureLayer: FeatureLayer, renderer?: SimpleRenderer, textExpression?: any): void; - /** - * Adds reference to the feature layer which is labeled. - * @param featureLayer The feature layer to be added to the label layer. - * @param renderer The renderer used to render text labels. - * @param textExpression An expression determining what text and field(s) will be displayed as in labels. - */ - addFeatureLayer(featureLayer: FeatureLayer, renderer?: UniqueValueRenderer, textExpression?: any): void; - /** - * Adds reference to the feature layer which is labeled. - * @param featureLayer The feature layer to be added to the label layer. - * @param renderer The renderer used to render text labels. - * @param textExpression An expression determining what text and field(s) will be displayed as in labels. - */ - addFeatureLayer(featureLayer: FeatureLayer, renderer?: ClassBreaksRenderer, textExpression?: any): void; + addFeatureLayer(featureLayer: FeatureLayer, renderer?: SimpleRenderer | UniqueValueRenderer | ClassBreaksRenderer, textExpression?: any): void; /** * Returns reference to the feature layer which features will be labeled. * @param index Index of the referenced feature layer. @@ -10440,6 +10067,8 @@ declare module "esri/layers/MosaicRule" { static OPERATION_MEAN: any; /** Takes the minimum value of all overlapping pixels. */ static OPERATION_MIN: any; + /** Takes the sum of all overlapping pixels. */ + static OPERATION_SUM: any; /** Indicates whether the sort should be ascending or not. */ ascending: boolean; /** An array of raster Ids. */ @@ -10493,7 +10122,7 @@ declare module "esri/layers/OpenStreetMapLayer" { declare module "esri/layers/PixelBlock" { import esri = require("esri"); - /** (Beta at v3.13) The PixelBlock is used to hold pixels. */ + /** The PixelBlock is used to hold pixels. */ class PixelBlock { /** Number of rows. */ height: number; @@ -10596,6 +10225,8 @@ declare module "esri/layers/RasterFunction" { functionArguments: any; /** The raster function name. */ functionName: string; + /** Defines the output image's pixel type. */ + outputPixelType: string; /** Variable name for the raster function. */ variableName: string; /** Creates a new RasterFunction object. */ @@ -10615,7 +10246,7 @@ declare module "esri/layers/RasterLayer" { import esri = require("esri"); import Layer = require("esri/layers/layer"); - /** (Beta at v3.13) The RasterLayer is used to display image services. */ + /** The RasterLayer is used to display image services. */ class RasterLayer extends Layer { /** * Creates a new RasterLayer object. @@ -10625,6 +10256,18 @@ declare module "esri/layers/RasterLayer" { constructor(url: string, options?: esri.RasterLayerOptions); /** Returns the context of the Canvas. */ getContext(): any; + /** + * Sets the image format. + * @param imageFormat The image format to set. + * @param doNotRefresh Use true to avoid refreshing the layer; false to refresh it. + */ + setImageFormat(imageFormat: string, doNotRefresh?: boolean): void; + /** + * Determines if the layer will update its content based on the map's current time extent. + * @param use Use true to update the layer's content based on the map's current time extent. + * @param doNotRefresh Use true to avoid refreshing the layer; false to refresh the layer. + */ + setUseMapTime(use: boolean, doNotRefresh?: boolean): void; } export = RasterLayer; } @@ -10633,6 +10276,7 @@ declare module "esri/layers/StreamLayer" { import esri = require("esri"); import FeatureLayer = require("esri/layers/FeatureLayer"); import Extent = require("esri/geometry/Extent"); + import Graphic = require("esri/graphic"); import Layer = require("esri/layers/layer"); /** The stream layer extends the feature layer to add the ability to connect to a stream of data using HTML5 WebSockets. */ @@ -10671,6 +10315,8 @@ declare module "esri/layers/StreamLayer" { getDefinitionExpression(): string; /** Gets the spatial filter set on the layer. */ getGeometryDefinition(): Extent; + /** Gets the latest observation for each track in the layer. */ + getLatestObservations(): Graphic; /** * Gets the unique values of the graphics (in the StreamLayer) based on the `fieldName` parameter. * @param fieldName Field to get the unique values from. @@ -10859,6 +10505,64 @@ declare module "esri/layers/TimeReference" { export = TimeReference; } +declare module "esri/layers/WFSLayer" { + import esri = require("esri"); + import Field = require("esri/layers/Field"); + import Extent = require("esri/geometry/Extent"); + import Graphic = require("esri/graphic"); + import InfoTemplate = require("esri/InfoTemplate"); + import Renderer = require("esri/renderers/Renderer"); + + /** (Currently in beta)A layer for OGC Web Feature Services (WFS). */ + class WFSLayer { + /** An array of fields in the layer. */ + fields: Field[]; + /** The full extent of the layer. */ + fullExtent: Extent; + /** The geometry type of the features in the layer. */ + geometryType: string; + /** An array of features in the layer. */ + graphics: Graphic[]; + /** ID assigned to the layer. */ + id: string; + /** The InfoTemplate for the layer. */ + infoTemplate: InfoTemplate; + /** The renderer to apply to the layer. */ + renderer: Renderer; + /** The visibility of the layer. */ + visible: boolean; + /** + * Creates a new WFSLayer object + * @param options See options table below for full descriptions of the properties needed for this object. + */ + constructor(options: esri.WFSLayerOptions); + /** Creates the getFeature parameter based on the version, nsLayerName, nsGeometryFieldName, mode, wkid, inverseFilter, maxFeatures constructor parameters. */ + buildRequest(): string; + /** + * Gets the WFS layer capabilities. + * @param callback An array of WFS layers in JSON format. + */ + getCapabilities(callback?: Function): void; + /** Performs the getFeature request. */ + getFeature(): void; + /** Returns a JSON Object containing all of the WFS parameters. */ + getWFSParameters(): any; + /** Redraws all the graphics in the layer. */ + redraw(): void; + /** Refreshes the features in the WFS layer. */ + refresh(): void; + /** Sets the default line symbol to be used if no renderer is specified. */ + setLineSymbol(): void; + /** Sets the default point symbol to be used if no renderer is specified. */ + setPointSymbol(): void; + /** Sets the default polygon symbol to be used if no renderer is specified. */ + setPolygonSymbol(): void; + /** Sets the WFS parameters using the provided JSON Object. */ + setWFSParameters(): void; + } + export = WFSLayer; +} + declare module "esri/layers/WMSLayer" { import esri = require("esri"); import DynamicMapServiceLayer = require("esri/layers/DynamicMapServiceLayer"); @@ -10868,6 +10572,8 @@ declare module "esri/layers/WMSLayer" { /** A layer for OGC Web Map Services (WMS). */ class WMSLayer extends DynamicMapServiceLayer { + /** All bounding boxes defined for the layer. */ + allExtents: Extent[]; /** Copyright of the WMS service. */ copyright: string; /** Description of the WMS service. */ @@ -10886,6 +10592,8 @@ declare module "esri/layers/WMSLayer" { maxWidth: number; /** Spatial reference of the WMS service. */ spatialReference: SpatialReference; + /** An array of WKIDs of all spatial references defined for the layer. */ + spatialReferences: number[]; /** Title of the WMS service. */ title: string; /** Version of the WMS service. */ @@ -10920,6 +10628,8 @@ declare module "esri/layers/WMSLayerInfo" { /** The WMSLayerInfo class defines and provides information about layers in a WMS service. */ class WMSLayerInfo { + /** All bounding boxes defined for the layer. */ + allExtents: Extent[]; /** The layer description defines the value of the Abstract capabilities property. */ description: string; /** The layer extent. */ @@ -10928,6 +10638,10 @@ declare module "esri/layers/WMSLayerInfo" { legendURL: string; /** The layer name. */ name: string; + /** An array of WKIDs of all spatial references defined for the layer. */ + spatialReferences: number[]; + /** WMSLayerInfos of the layer's sub layers. */ + subLayers: WMSLayerInfo[]; /** The layer title. */ title: string; /** @@ -11246,7 +10960,7 @@ declare module "esri/map" { * @param divId Container id for the referencing map. * @param options Optional parameters. */ - constructor(divId: string, options?: esri.MapOptions); + constructor(divId: Node | string, options?: esri.MapOptions); /** * Adds an Esri Layer to the map. * @param layer Layer to be added to the map. @@ -11474,7 +11188,7 @@ declare module "esri/map" { /** Fires when a map layer resumes drawing. */ on(type: "layer-resume", listener: (event: { layer: Layer; target: Map }) => void): esri.Handle; /** Fires after all layers are added to the map using the map.addLayers method. */ - on(type: "layers-add-result", listener: (event: { layers: Layer[]; target: Map }) => void): esri.Handle; + on(type: "layers-add-result", listener: (event: { layers: any[]; target: Map }) => void): esri.Handle; /** Fires after all the layers have been removed. */ on(type: "layers-removed", listener: (event: { target: Map }) => void): esri.Handle; /** Fires when all the layers have been reordered. */ @@ -11530,7 +11244,495 @@ declare module "esri/map" { export = Map; } +declare module "esri/opsdashboard/DataSourceProxy" { + import Field = require("esri/layers/Field"); + import FeatureType = require("esri/layers/FeatureType"); + import Query = require("esri/tasks/query"); + import Graphic = require("esri/graphic"); + + /** DataSourceProxy is a proxy class that represents a operations dashboard data source. */ + class DataSourceProxy { + /** Read-only: The name of the display field. */ + displayFieldName: string; + /** Read-only: The collection of fields. */ + fields: Field[]; + /** The geometry type. */ + geometryType: string; + /** Read-only: The id of the data source. */ + id: string; + /** Read-only: Indicates if the last query failed and the data source is in a broken state. */ + isBroken: boolean; + /** Read-only: The name of the data source. */ + name: string; + /** Read-only: The name of the object id field. */ + objectIdFieldName: string; + /** Read-only: Indicates if the data source supports selections. */ + supportsSelection: boolean; + /** Read-only: The name of the type id field. */ + typeIdFieldName: string; + /** Read-only: The collection of feature types. */ + types: FeatureType[]; + /** Clear the selection. */ + clearSelection(): void; + /** + * Executes a query and get the result. + * @param query The query object to apply. + */ + executeQuery(query: Query): any; + /** Retrieve the associated data source that supports selection. */ + getAssociatedSelectionDataSourceProxy(): any; + /** Get the associated popupInfo for the data source if any available. */ + getPopupInfo(): any; + /** Get the associated render object for the data source if any available. */ + getRenderer(): any; + /** + * Get the feature type from a feature coming from the data source. + * @param feature A feature coming from the data source + */ + getTypeFromFeature(feature: Graphic): number; + /** + * Returns the value corresponding to a field name from a feature coming from the data source. + * @param feature A feature coming from the data source + * @param fieldName The name of the field for which the value should be returned. + */ + getValueFromFeature(feature: Graphic, fieldName: string): number | string; + /** + * Select features in the data source using a query. + * @param query The query object to apply + */ + selectFeatures(query: Query): void; + /** + * Select features in the data source using a collection of object ids. + * @param objectIds The collection of object ids of the features to select. + */ + selectFeaturesByObjectIds(objectIds: string[]): void; + } + export = DataSourceProxy; +} + +declare module "esri/opsdashboard/ExtensionBase" { + import esri = require("esri"); + import MapWidgetProxy = require("esri/opsdashboard/MapWidgetProxy"); + + /** ExtensionBase is a base class used by all the extension proxies. */ + class ExtensionBase { + /** "circle" */ + static CIRCLE: any; + /** "extent" */ + static EXTENT: any; + /** "freehandpolygon" */ + static FREEHAND_POLYGON: any; + /** "freehandpolyline" */ + static FREEHAND_POLYLINE: any; + /** "line" */ + static LINE: any; + /** "point" */ + static POINT: any; + /** "polygon" */ + static POLYGON: any; + /** "polyline" */ + static POLYLINE: any; + /** Read-only: Indicates if the host application is the Windows Operations Dashboard. */ + isNative: boolean; + /** Get the collection of data sources from the host application. */ + getDataSourceProxies(): any; + /** Get the collection of data sources from the host application. */ + getDataSourceProxies(): any; + /** Get the data source corresponding to the data source id from the host application. */ + getDataSourceProxy(): any; + /** Get the collection of map widgets from the host application. */ + getMapWidgetProxies(): any; + /** + * Get the map widget corresponding to the map widget id from the host application. + * @param mapWidgetId A map widget id + */ + getMapWidgetProxy(mapWidgetId: string): any; + /** + * Called when an error occurred during the initialization process with the host application. + * @param err The error that occurred. + */ + hostInitializationError(err: Error): void; + /** Called by the host application when the relationship has been established with the extension. */ + hostReady(): void; + /** + * Called by the host application when a map widget has been added to the current view. + * @param mapWidgetProxy A map widget id. + */ + mapWidgetAdded(mapWidgetProxy: MapWidgetProxy): void; + /** + * Called by the host application when a map widget has been removed from the current view. + * @param mapWidgetId A map widget id. + */ + mapWidgetRemoved(mapWidgetId: string): void; + /** Event indicating that a new data source has been added into the host operation view. */ + on(type: "data-source-added", listener: (event: { dataSourceProxy: any; target: ExtensionBase }) => void): esri.Handle; + /** Event indicating that a data source has been removed from the host operation view. */ + on(type: "data-source-removed", listener: (event: { dataSourceId: string; target: ExtensionBase }) => void): esri.Handle; + /** Event indicating that the initialization process was successful. */ + on(type: "host-ready", listener: (event: { target: ExtensionBase }) => void): esri.Handle; + /** Event indicating that the initialization process encountered an error. */ + on(type: "initialization-error", listener: (event: { error: Error; target: ExtensionBase }) => void): esri.Handle; + /** Event indicating that a new map widget has been added into the host operation view. */ + on(type: "map-widget-added", listener: (event: { mapWidgetProxy: MapWidgetProxy; target: ExtensionBase }) => void): esri.Handle; + /** Event indicating that a map widget has been removed from the host operation view. */ + on(type: "map-widget-removed", listener: (event: { mapWidgetId: string; target: ExtensionBase }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ExtensionBase; +} + +declare module "esri/opsdashboard/ExtensionConfigurationBase" { + import ExtensionBase = require("esri/opsdashboard/ExtensionBase"); + + /** ExtensionConfigurationBase is a base class used by all the extension configuration proxies. */ + class ExtensionConfigurationBase extends ExtensionBase { + /** Indicates that the configuration is ready to be persisted or not. */ + readyToPersistConfig: boolean; + } + export = ExtensionConfigurationBase; +} + +declare module "esri/opsdashboard/FeatureActionConfigurationProxy" { + import ExtensionConfigurationBase = require("esri/opsdashboard/ExtensionConfigurationBase"); + + /** FeatureActionConfigurationProxy is a class used to provide the configuration user experience for an operations dashboard extension feature action. */ + class FeatureActionConfigurationProxy extends ExtensionConfigurationBase { + } + export = FeatureActionConfigurationProxy; +} + +declare module "esri/opsdashboard/FeatureActionFeatures" { + import DataSourceProxy = require("esri/opsdashboard/DataSourceProxy"); + import Graphic = require("esri/graphic"); + + /** FeatureActionFeatures is a specialized collection of features used by WidgetProxy to hold the collection of features for the associated feature actions. */ + class FeatureActionFeatures { + /** The DataSourceProxy from which the collection of features belongs to. */ + dataSourceProxy: DataSourceProxy; + /** + * Add a feature to the host collection. + * @param featureOrObjectId + */ + addFeature(featureOrObjectId: Graphic | number): void; + /** + * Add a collection of features or collection of object id in the host collection. + * @param featuresOrObjectIds + */ + addFeatures(featuresOrObjectIds: Graphic[] | number[]): void; + /** Remove all the features from the host collection. */ + clear(): void; + /** + * Test if a feature exists in the host collection. + * @param featureOrObjectId Feature to test existance for. + */ + contains(featureOrObjectId: Graphic | number): boolean; + /** + * Returns the index of a feature in the host collection. + * @param featureOrObjectId Feature to return index from. + */ + indexOf(featureOrObjectId: Graphic | number): number; + /** + * Remove a collection of features from the host collection. + * @param featureOrObjectId Feature to remove. + */ + removeFeature(featureOrObjectId: Graphic | number): void; + /** + * Remove a feature from the host collection. + * @param featuresOrObjectIds Features to remove. + */ + removeFeatures(featuresOrObjectIds: Graphic[] | number[]): void; + } + export = FeatureActionFeatures; +} + +declare module "esri/opsdashboard/GraphicsLayerProxy" { + import Renderer = require("esri/renderers/Renderer"); + import Graphic = require("esri/graphic"); + + /** GraphicsLayerProxy is a proxy class that represents a graphics layer in a map widget in the host application. */ + class GraphicsLayerProxy { + /** Read-only: The current host graphics layer maximum visible scale. */ + maxScale: number; + /** Read-only: The current host graphics layer minimum visible scale. */ + minScale: number; + /** Read-only: The current host graphics layer opacity ratio. */ + opacity: number; + /** The current renderer used by the host graphics layer. */ + renderer: Renderer; + /** Read-only: The current host graphics layer visibility. */ + visible: boolean; + /** + * Update a graphic in the host graphics layer with a new version. + * @param graphic The graphic to update in the host graphics layer. + */ + addOrUpdateGraphic(graphic: Graphic): void; + /** + * Update a graphic in the host graphics layer with a new version. + * @param graphic The graphic to update in the host graphics layer. + */ + addOrUpdateGraphics(graphic: Graphic): void; + /** Removes all the graphics from the host graphics layer. */ + clear(): void; + /** + * Removes from the host graphics layer a graphic. + * @param graphic The graphic to remove from the host graphics layer. + */ + removeGraphic(graphic: Graphic): void; + /** + * Sets the host graphics layer maximum scale. + * @param maxScale + */ + setMaxScale(maxScale: number): void; + /** + * Sets the host graphics layer minimum scale. + * @param minScale + */ + setMinScale(minScale: number): void; + /** + * Sets the host graphics layer opacity ratio. + * @param opacity An opacity ratio between 0 and 1. + */ + setOpacity(opacity: number): void; + /** + * Sets the host graphics layer renderer. + * @param renderer Since the Windows operations dashboard is built using ArcGIS Runtime SDK for WPF, only renderers supported by the WPF should be used, such as SimpleRenderer, UniqueValueRenderer and ClassBreaksRenderer. + */ + setRenderer(renderer: Renderer): void; + /** + * Set the visibility of the host graphics layer. + * @param visibility The new visibility value. + */ + setVisibility(visibility: boolean): void; + } + export = GraphicsLayerProxy; +} + +declare module "esri/opsdashboard/MapToolConfigurationProxy" { + import ExtensionConfigurationBase = require("esri/opsdashboard/ExtensionConfigurationBase"); + + /** MapToolConfigurationProxy is a class used to provide the configuration user experience for an operations dashboard extension map tool. */ + class MapToolConfigurationProxy extends ExtensionConfigurationBase { + } + export = MapToolConfigurationProxy; +} + +declare module "esri/opsdashboard/MapToolProxy" { + import esri = require("esri"); + import MapWidgetProxy = require("esri/opsdashboard/MapWidgetProxy"); + import Geometry = require("esri/geometry/Geometry"); + + /** MapToolProxy is a class used to define an operations dashboard extension map tool. */ + class MapToolProxy { + /** Read-only: The available size for the map tool user experience on the host map widget. */ + availableDisplaySize: number; + /** Read-only: The map tool user experience size in pixels. */ + displaySize: any; + /** Read-only: The map widget that is hosting the map tool user experience. */ + mapWidgetProxy: MapWidgetProxy; + /** Read-only: The previous map tool user experience state that was passed the last time the map tool was deactivated. */ + previousState: any; + /** + * Activates a drawing activity on the host map widget. + * @param options Drawing options. + */ + activateMapDrawing(options: any): void; + /** + * Called by the host application when the available size for the map tool user experience has changed (user resizes the application or the map widget). + * @param availableSize The size available on the host map widget for the map tool user experience. + */ + availableDisplaySizeChanged(availableSize: any): void; + /** Deactivates the drawing activity on the host map widget. */ + deactivateMapDrawing(): void; + /** + * Deactivate the map tool user experience. + * @param state A JSON object that needs to be persisted in the host until the next activation of the map tool user experience. + */ + deactivateMapTool(state: any): void; + /** + * Called by the host application when the user has completed the drawing activity on the map. + * @param geometry The geometry captured by the user during the drawing activity. + */ + mapDrawComplete(geometry: Geometry): void; + /** + * Change the size of the user experience area in the host application for this map tool user experience. + * @param size The new size for the user experience. + */ + setDisplaySize(size: any): any; + /** Event indicating that the available display size for the map tool user experience has changed. */ + on(type: "available-display-size-changed", listener: (event: { size: any; target: MapToolProxy }) => void): esri.Handle; + /** Event indicating that a previously activate drawing activity has been completed by the user. */ + on(type: "draw-complete", listener: (event: { geometry: Geometry; target: MapToolProxy }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = MapToolProxy; +} + +declare module "esri/opsdashboard/MapWidgetProxy" { + import esri = require("esri"); + import SpatialReference = require("esri/SpatialReference"); + import GraphicsLayerProxy = require("esri/opsdashboard/GraphicsLayerProxy"); + import Point = require("esri/geometry/Point"); + import Extent = require("esri/geometry/Extent"); + + /** MapWidgetProxy is a proxy class that represents a operations dashboard map widget. */ + class MapWidgetProxy { + /** Read-only: The map id. */ + id: string; + /** Read-only: The name of the map. */ + name: string; + /** Read-only: The spatial reference of the map. */ + spatialReference: SpatialReference; + /** + * Creates a graphics layer in the host map. + * @param options The options for the new graphics layer + */ + createGraphicsLayerProxy(options?: any): any; + /** + * Destroys in the host map a host graphics layer. + * @param graphicsLayerProxy The host graphics layer to destroy. + */ + destroyGraphicsLayerProxy(graphicsLayerProxy: GraphicsLayerProxy): void; + /** Gets the current host map extent. */ + getMapExtent(): any; + /** Called by the host application when the extent of the host map has changed. */ + mapExtentChanged(): void; + /** + * Pans the map to a new location. + * @param mapPoint A new location with the same spatial reference as the host map. + */ + panTo(mapPoint: Point): void; + /** + * Sets an extent on the host map extent. + * @param extent A new map extent. + */ + setExtent(extent: Extent): void; + /** Subscribes to the host map events. */ + subscribeToMapEvents(): void; + /** Unsubscribes from the host map events. */ + unsubscribeFromMapEvents(): void; + /** Event indicating that the host map extent has changed. */ + on(type: "map-extent-change", listener: (event: { extent: Extent; target: MapWidgetProxy }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = MapWidgetProxy; +} + +declare module "esri/opsdashboard/WidgetConfigurationProxy" { + import esri = require("esri"); + import ExtensionConfigurationBase = require("esri/opsdashboard/ExtensionConfigurationBase"); + import DataSourceProxy = require("esri/opsdashboard/DataSourceProxy"); + import MapWidgetProxy = require("esri/opsdashboard/MapWidgetProxy"); + + /** WidgetConfigurationProxy is a class used to provide the configuration user experience for an operations dashboard extension widget. */ + class WidgetConfigurationProxy extends ExtensionConfigurationBase { + /** The object that will store the widget configuration. */ + config: any; + /** + * Called by the host application when the user has changed the selected data source in the data source selector. + * @param dataSourceProxy The selected data source. + * @param dataSourceConfig The associated data source config. + */ + dataSourceSelectionChanged(dataSourceProxy: DataSourceProxy, dataSourceConfig: any): void; + /** + * Get the data source config for a data source. + * @param dataSourceProxyOrDataSourceId A data source or a data source id. + */ + getDataSourceConfig(dataSourceProxyOrDataSourceId: DataSourceProxy | string): any; + /** + * Called by the host application when the user has changed the slected map widget in the map widget selector. + * @param mapWidgetProxy The selected map widget. + */ + mapWidgetSelectionChanged(mapWidgetProxy: MapWidgetProxy): void; + /** Event indicating the user has changed the selected data source for the configuration. */ + on(type: "data-source-selection-changed", listener: (event: { dataSourceConfig: any; dataSourceProxy: DataSourceProxy; target: WidgetConfigurationProxy }) => void): esri.Handle; + /** Event indicating the user has changed the selected map widget for the configuration. */ + on(type: "map-widget-selection-changed", listener: (event: { mapWidgetProxy: MapWidgetProxy; target: WidgetConfigurationProxy }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = WidgetConfigurationProxy; +} + +declare module "esri/opsdashboard/WidgetProxy" { + import esri = require("esri"); + import ExtensionBase = require("esri/opsdashboard/ExtensionBase"); + import FeatureActionFeatures = require("esri/opsdashboard/FeatureActionFeatures"); + import MapWidgetProxy = require("esri/opsdashboard/MapWidgetProxy"); + import DataSourceProxy = require("esri/opsdashboard/DataSourceProxy"); + import Graphic = require("esri/graphic"); + import Geometry = require("esri/geometry/Geometry"); + + /** WidgetProxy is a class used to define an operations dashboard extension widget. */ + class WidgetProxy extends ExtensionBase { + /** Read-only: If the widget was configured to consume data sources, the dataSourceConfig array will hold a collection of dataSourceConfig objects. */ + dataSourceConfigs: any[]; + /** Read-only: The host collection of features used by the widget feature actions. */ + featureActionFeatures: FeatureActionFeatures; + /** Read-only: Indicates if the widget has a default feature action associated with. */ + hasDefaultFeatureAction: boolean; + /** Read-only: Indicates if the widget has feature actions associated with it. */ + hasFeatureActions: boolean; + /** + * Activate a drawing toolbar on a map widget. + * @param options + * @param mapWidgetProxy The target map widget. + */ + activateDrawingToolbar(options?: any, mapWidgetProxy?: MapWidgetProxy): any; + /** + * Called by the host application when a data source state has expired. + * @param dataSourceProxy + * @param associated dataSourceConfig + */ + dataSourceExpired(dataSourceProxy: DataSourceProxy, associated?: any): void; + /** + * Deactivate the drawing toolbar on the map widget. + * @param mapWidgetProxy The target map widget. + */ + deactivateDrawingToolbar(mapWidgetProxy?: MapWidgetProxy): void; + /** Called by the host application when the user has canceled the drawing activity. */ + drawingToolbarDeactivated(): void; + /** + * Execute the default feature action. + * @param featuresOrObjectIds + */ + executeDefaultFeatureAction(featuresOrObjectIds: Graphic[] | number[]): void; + /** + * Get the data source config for a data source. + * @param dataSourceProxyOrDataSourceId A data source or a data source id. + */ + getDataSourceConfig(dataSourceProxyOrDataSourceId: DataSourceProxy | string): any; + /** + * Called by the host application when the user has finished the drawing activity. + * @param geometry + */ + toolbarDrawComplete(geometry: Geometry): void; + /** Event indicating that a data source validity has expired. */ + on(type: "data-source-expired", listener: (event: { dataSourceConfig: any; dataSourceProxy: DataSourceProxy; target: WidgetProxy }) => void): esri.Handle; + /** Event indicating that the user has deactivated the previously activated drawing toolbar on the map widget. */ + on(type: "drawing-toolbar-deactivated", listener: (event: { target: WidgetProxy }) => void): esri.Handle; + /** Event indicating the user has finished a drawing activity with the previously activated drawing toolbar. */ + on(type: "toolbar-draw-complete", listener: (event: { geometry: Geometry; target: WidgetProxy }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = WidgetProxy; +} + +declare module "esri/opsdashboard/featureActionProxy" { + import esri = require("esri"); + import ExtensionBase = require("esri/opsdashboard/ExtensionBase"); + import DataSourceProxy = require("esri/opsdashboard/DataSourceProxy"); + import FeatureSet = require("esri/tasks/FeatureSet"); + + /** featureActionProxy is a singleton object that allows implementing an operations dashboard Feature Action extension. */ + class featureActionProxy extends ExtensionBase { + /** Event raised when the feature action should execute for a set of features. */ + on(type: "execute", listener: (event: { config: any; dataSourceProxy: DataSourceProxy; featureSet: FeatureSet; target: featureActionProxy }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = featureActionProxy; +} + declare module "esri/plugins/FeatureLayerStatistics" { + import esri = require("esri"); import FeatureLayer = require("esri/layers/FeatureLayer"); /** This module defines a class and a feature layer plugin that is used to calculate feature layer statistics. */ @@ -11539,7 +11741,7 @@ declare module "esri/plugins/FeatureLayerStatistics" { * Creates a new object that is used to calculate statistics about features in a feature layer. * @param params Parameters that define the FeatureLayerStatistics. */ - constructor(params: any); + constructor(params: esri.FeatureLayerStatisticsOptions); /** * This function is called internally when the plugin is added to a feature layer. * @param layer The target FeatureLayer that have the plugin added. @@ -11601,13 +11803,7 @@ declare module "esri/plugins/spatialIndex" { * @param target The map or feature layer to which the index is connected. * @param options See the object specifications table below for the structure of the index options object. */ - add(target: Map, options?: any): void; - /** - * Adds an index property to the target instance. - * @param target The map or feature layer to which the index is connected. - * @param options See the object specifications table below for the structure of the index options object. - */ - add(target: FeatureLayer, options?: any): void; + add(target: Map | FeatureLayer, options?: any): void; /** Removes the index plugin. */ remove(): void; }; @@ -11686,28 +11882,7 @@ declare module "esri/process/SpatialIndex" { * @param layerId ID assigned to the layer. * @param getRects Whether to get the rectangle object with data in leaf, otherwise just get the stored data. */ - intersects(test: Point, layerId?: string, getRects?: boolean): any; - /** - * Searches index for items which intersect the test object. - * @param test The point or area to intersect. - * @param layerId ID assigned to the layer. - * @param getRects Whether to get the rectangle object with data in leaf, otherwise just get the stored data. - */ - intersects(test: Graphic, layerId?: string, getRects?: boolean): any; - /** - * Searches index for items which intersect the test object. - * @param test The point or area to intersect. - * @param layerId ID assigned to the layer. - * @param getRects Whether to get the rectangle object with data in leaf, otherwise just get the stored data. - */ - intersects(test: Extent, layerId?: string, getRects?: boolean): any; - /** - * Searches index for items which intersect the test object. - * @param test The point or area to intersect. - * @param layerId ID assigned to the layer. - * @param getRects Whether to get the rectangle object with data in leaf, otherwise just get the stored data. - */ - intersects(test: number[], layerId?: string, getRects?: boolean): any; + intersects(test: Point | Graphic | Extent | number[], layerId?: string, getRects?: boolean): any; /** * Searches for the nearest point(s) to the passed point within the specified criteria. * @param criteria See the object specifications table below for the structure of the criteria object. @@ -11718,6 +11893,56 @@ declare module "esri/process/SpatialIndex" { export = SpatialIndex; } +declare module "esri/renderers/BlendRenderer" { + import esri = require("esri"); + import Symbol = require("esri/symbols/Symbol"); + + /** (Currently in beta) BlendRenderer allows you to easily identify a predominant attribute among two or more competing attributes in a feature. */ + class BlendRenderer { + /** This determines how colors are blended together. */ + blendMode: string; + /** An array of objects to blend containing the field name and color to use. */ + fields: any[]; + /** The field to normalize. */ + normalizationField: string; + /** An array of objects which determines opacity. */ + opacityStops: any[]; + /** The BlendRenderer applies to the color of the symbol. */ + symbol: Symbol; + /** + * Creates a new BlendRenderer object. + * @param params Required and optional parameters. + */ + constructor(params?: esri.BlendRendererOptions); + /** + * Sets the mode that determines how colors are blended together. + * @param blendMode The blend mode used to determine how colors are blended together. + */ + setBlendMode(blendMode: string): void; + /** + * Sets an array of objects to blend containing the field name and color to use. + * @param fields An array of objects to blend containing the field name and color to use. + */ + setFields(fields: any[]): void; + /** + * Sets the field to normalize + * @param field The field to normalize. + */ + setNormalizationField(field: string): void; + /** + * Sets an array of objects which determines opacity. + * @param opacityStops Sets an array of objects which determines opacity. + */ + setOpacityStops(opacityStops: any[]): void; + /** + * Sets the symbol to blend. + * @param symbol The symbol to blend. + */ + setSymbol(symbol: Symbol): void; + } + export = BlendRenderer; +} + declare module "esri/renderers/ClassBreaksRenderer" { import Renderer = require("esri/renderers/Renderer"); import FillSymbol = require("esri/symbols/FillSymbol"); @@ -11751,13 +11976,7 @@ declare module "esri/renderers/ClassBreaksRenderer" { * @param defaultSymbol Default symbol for the renderer. * @param attributeField Specify either the attribute field the renderer uses to match values or starting at version 3.3, a function that returns a value to be compared against class breaks. */ - constructor(defaultSymbol: Symbol, attributeField: string); - /** - * Creates a new ClassBreaksRenderer object. - * @param defaultSymbol Default symbol for the renderer. - * @param attributeField Specify either the attribute field the renderer uses to match values or starting at version 3.3, a function that returns a value to be compared against class breaks. - */ - constructor(defaultSymbol: Symbol, attributeField: Function); + constructor(defaultSymbol: Symbol, attributeField: string | Function); /** * Creates a new ClassBreaksRenderer. * @param json JSON object representing the ClassBreaksRenderer. @@ -11769,14 +11988,7 @@ declare module "esri/renderers/ClassBreaksRenderer" { * @param maxValue Maximum value in the break. * @param symbol Symbol used for the break. */ - addBreak(minValueOrInfo: number, maxValue?: number, symbol?: Symbol): void; - /** - * Adds a class break. - * @param minValueOrInfo The value can be provided as individual arguments or as an info object. - * @param maxValue Maximum value in the break. - * @param symbol Symbol used for the break. - */ - addBreak(minValueOrInfo: any, maxValue?: number, symbol?: Symbol): void; + addBreak(minValueOrInfo: number | any, maxValue?: number, symbol?: Symbol): void; /** Remove all existing class breaks for this renderer. */ clearBreaks(): void; /** @@ -11927,6 +12139,8 @@ declare module "esri/renderers/Renderer" { rotationInfo: any; /** Defines the size of the symbol where feature size is proportional to data value. */ sizeInfo: any; + /** This property allows you to define how to render values in a layer. */ + visualVariables: any[]; /** * Gets the color for the Graphic. * @param graphic Graphic to get color from. @@ -11952,6 +12166,13 @@ declare module "esri/renderers/Renderer" { * @param graphic Graphic to symbolize. */ getSymbol(graphic: Graphic): Symbol; + /** + * Returns the visual variable of the specified type. + * @param type The type of visual variable desired. + */ + getVisualVariablesForType(type: string): any; + /** Indicates if the renderer has defined visualVariables. */ + hasVisualVariables(): boolean; /** * Sets the colorInfo property. * @param info An info object that defines the color. @@ -11969,6 +12190,11 @@ declare module "esri/renderers/Renderer" { setRotationInfo(info: any): Renderer; /** Set size info of the renderer to modify the symbol size based on data value. */ setSizeInfo(): Renderer; + /** + * Sets the renderer with the specified visualVariables. + * @param visualParams The specified visualVariables. + */ + setVisualVariables(visualParams: any[]): void; /** Converts object to its ArcGIS Server JSON representation. */ toJson(): any; } @@ -12088,6 +12314,7 @@ declare module "esri/renderers/TemporalRenderer" { } declare module "esri/renderers/TimeClassBreaksAger" { + import esri = require("esri"); import SymbolAger = require("esri/renderers/SymbolAger"); import Symbol = require("esri/symbols/Symbol"); import Graphic = require("esri/graphic"); @@ -12112,10 +12339,10 @@ declare module "esri/renderers/TimeClassBreaksAger" { static UNIT_YEARS: any; /** * Creates a new TimeClassBreaksAgerObject with the specified time breaks inforamtion. - * @param infos Each element in the array is an object that describes the class breaks information. + * @param params Each element in the array is an object that describes the class breaks information. * @param timeUnits The unit in which the minimum and maximum break values are measured. */ - constructor(infos: any[], timeUnits?: string); + constructor(params: esri.TimeClassBreaksAgerOptions[], timeUnits?: string); /** * Calculates aging and returns the appropriate symbol. * @param symbol The symbol to age. @@ -12182,16 +12409,7 @@ declare module "esri/renderers/UniqueValueRenderer" { * @param attributeField3 If needed, specify an additional attribute field the renderer uses to match values. * @param fieldDelimeter String inserted between the values of different fields. */ - constructor(defaultSymbol: Symbol, attributeField: string, attributeField2?: string, attributeField3?: string, fieldDelimeter?: string); - /** - * Creates a new UniqueValueRenderer object. - * @param defaultSymbol Default symbol for the renderer. - * @param attributeField Specify either the attribute field the renderer uses to match values or starting at version 3.3, a function that returns a value to be compared against unique values. - * @param attributeField2 If needed, specify an additional attribute field the renderer uses to match values. - * @param attributeField3 If needed, specify an additional attribute field the renderer uses to match values. - * @param fieldDelimeter String inserted between the values of different fields. - */ - constructor(defaultSymbol: Symbol, attributeField: Function, attributeField2?: string, attributeField3?: string, fieldDelimeter?: string); + constructor(defaultSymbol: Symbol, attributeField: string | Function, attributeField2?: string, attributeField3?: string, fieldDelimeter?: string); /** * Creates a new Unique Value Renderer. * @param json JSON object representing the UniqueValueRenderer. @@ -12202,13 +12420,7 @@ declare module "esri/renderers/UniqueValueRenderer" { * @param valueOrInfo Value to match with. * @param symbol Symbol used for the value. */ - addValue(valueOrInfo: string, symbol?: Symbol): void; - /** - * Adds a unique value and symbol. - * @param valueOrInfo Value to match with. - * @param symbol Symbol used for the value. - */ - addValue(valueOrInfo: any, symbol?: Symbol): void; + addValue(valueOrInfo: string | any, symbol?: Symbol): void; /** * Returns rendering and legend information (as defined by the renderer) associated with the given graphic. * @param graphic The graphic whose rendering and legend information will be returned. @@ -12301,6 +12513,11 @@ declare module "esri/renderers/smartMapping" { * @param params See the object specifications table below for the structure of the params object. */ createHeatmapRenderer(params: any): any; + /** + * Creates an object that describes how opacity of features is calculated. + * @param params See the object specifications table below for the structure of the params object. + */ + createOpacityInfo(params: any): any; /** * Creates a renderer for visualizing features by varying their size based on data. * @param params See the object specifications table below for the structure of the params object. @@ -12477,16 +12694,7 @@ declare module "esri/symbols/Font" { * @param weight Font weight. * @param family Font family. */ - constructor(size?: number, style?: string, variant?: string, weight?: string, family?: string); - /** - * Creates a new Font object. - * @param size Font size. - * @param style Font style. - * @param variant Font variant. - * @param weight Font weight. - * @param family Font family. - */ - constructor(size?: string, style?: string, variant?: string, weight?: string, family?: string); + constructor(size?: number | string, style?: string, variant?: string, weight?: string, family?: string); /** * Creates a new Font object using a JSON object. * @param json JSON object representing the font. @@ -12506,12 +12714,7 @@ declare module "esri/symbols/Font" { * Sets the font size. * @param size Font size. */ - setSize(size: number): Font; - /** - * Sets the font size. - * @param size Font size. - */ - setSize(size: string): Font; + setSize(size: number | string): Font; /** * Sets the font style. * @param style Font style. @@ -12694,8 +12897,8 @@ declare module "esri/symbols/PictureMarkerSymbol" { declare module "esri/symbols/SimpleFillSymbol" { import FillSymbol = require("esri/symbols/FillSymbol"); - import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); import Color = require("esri/Color"); + import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); /** Fill symbols are used to draw polygon features on the graphics layer. */ class SimpleFillSymbol extends FillSymbol { @@ -12715,6 +12918,8 @@ declare module "esri/symbols/SimpleFillSymbol" { static STYLE_SOLID: any; /** The fill is vertical lines. */ static STYLE_VERTICAL: any; + /** Symbol color - only applies when SimpleFillSymbol.style = 'STYLE_SOLID'. */ + color: Color; /** The fill style. */ style: string; /** Creates a new empty SimpleFillSymbol object. */ @@ -12731,6 +12936,11 @@ declare module "esri/symbols/SimpleFillSymbol" { * @param json JSON object representing the SimpleFillSymbol. */ constructor(json: Object); + /** + * Sets the symbol color - only applies when style is STYLE_SOLID. + * @param color Symbol color. + */ + setColor(color: Color): SimpleFillSymbol; /** * Sets the fill symbol style. * @param style Fill style. @@ -13046,18 +13256,18 @@ declare module "esri/tasks/AlgorithmicColorRamp" { } declare module "esri/tasks/AreasAndLengthsParameters" { - import Geometry = require("esri/geometry/Geometry"); + import Polygon = require("esri/geometry/Polygon"); /** Input parameters for the areasAndLengths() method on the Geometry Service. */ class AreasAndLengthsParameters { /** The area unit in which areas of polygons will be calculated. */ - areaUnit: any; + areaUnit: number | string; /** Defines the type of calculation for the geometry. */ calculationType: string; /** The length unit in which perimeters of polygons will be calculated. */ - lengthUnit: any; + lengthUnit: number | string; /** Polygon geometries for which to compute areas and lengths */ - polygons: Geometry[]; + polygons: Polygon[]; /** Creates a new AreasAndLengthsParameters object. */ constructor(); } @@ -13083,7 +13293,7 @@ declare module "esri/tasks/BufferParameters" { /** If true, all geometries buffered at a given distance are unioned into a single (possibly multipart) polygon, and the unioned geometry is placed in the output array. */ unionResults: boolean; /** The units for calculating each buffer distance. */ - unit: string; + unit: number; /** Creates a new BufferParameters object. */ constructor(); } @@ -13165,7 +13375,7 @@ declare module "esri/tasks/ClosestFacilityParameters" { /** The set of facilities loaded as network locations during analysis. */ facilities: any; /** The network attribute field name used as the impedance attribute during analysis. */ - impedenceAttribute: string; + impedanceAttribute: string; /** The set of incidents loaded as network locations during analysis. */ incidents: any; /** The output geometry precision. */ @@ -13206,6 +13416,8 @@ declare module "esri/tasks/ClosestFacilityParameters" { timeOfDayUsage: string; /** Options for traveling to or from the facility. */ travelDirection: string; + /** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */ + travelMode: any; /** If true, the hierarchy attribute for the network will be used in analysis. */ useHierarchy: boolean; /** Creates a new ClosestFacilityParameters object */ @@ -13256,6 +13468,8 @@ declare module "esri/tasks/ClosestFacilityTask" { * @param url URL to the ArcGIS Server REST resource that represents a network analysis service. */ constructor(url: string); + /** Returns an object describing a Closest Facility service endpoint (URL of the endpoint is specified in the constructor). */ + getServiceDescription(): any; /** * Solve the closest facility. * @param params The ClosestFacilityParameters object. @@ -13350,7 +13564,7 @@ declare module "esri/tasks/DensifyParameters" { /** The array of geometries to be densified. */ geometries: Geometry[]; /** The length unit of maxSegmentLength, can be any esriUnits constant. */ - lengthUnit: any; + lengthUnit: number | string; /** All segments longer than maxSegmentLength are replaced with sequences of lines no longer than maxSegmentLength. */ maxSegmentLength: number; /** Converts object to its JSON representation. */ @@ -13392,10 +13606,10 @@ declare module "esri/tasks/DistanceParameters" { /** Input parameters for the distance method on the GeometryService. */ class DistanceParameters { /** Specifies the units for measuring distance between geometry1 and geometry2. */ - distanceUnit: any; + distanceUnit: number | string; /** When true, the geodesic distance between geometry1 and geometry2 is measured. */ geodesic: boolean; - /** The geometry from which the distance is to measured. */ + /** The geometry from which the distance is to be measured. */ geometry1: Geometry; /** The geometry to which the distance is measured. */ geometry2: Geometry; @@ -13547,7 +13761,7 @@ declare module "esri/tasks/GeneralizeParameters" { /** Sets the geometries, maximum deviation and units for the generalize operation. */ class GeneralizeParameters { /** The maximum deviation unit. */ - deviationUnit: any; + deviationUnit: number | string; /** The array of input geometries to generalize. */ geometries: Geometry[]; /** The maximum deviation for constructing a generalized geometry based on the input geometries. */ @@ -13625,6 +13839,7 @@ declare module "esri/tasks/GeometryService" { import ProjectParameters = require("esri/tasks/ProjectParameters"); import RelationParameters = require("esri/tasks/RelationParameters"); import TrimExtendParameters = require("esri/tasks/TrimExtendParameters"); + import Point = require("esri/geometry/Point"); /** Represents a geometry service resource exposed by the ArcGIS Server REST API. */ class GeometryService { @@ -13758,7 +13973,7 @@ declare module "esri/tasks/GeometryService" { * @param callback The function to call when the method has completed. * @param errback An error object is returned if an error occurs on the Server during task execution. */ - labelPoints(polygons: Geometry[], callback?: Function, errback?: Function): any; + labelPoints(polygons: Polygon[], callback?: Function, errback?: Function): any; /** * Gets the lengths for a Geometry[] when the geometry type is Polyline. * @param lengthsParameter Specify the polylines and optionally the length unit and the geodesic length option. @@ -13828,7 +14043,7 @@ declare module "esri/tasks/GeometryService" { /** Fires when the autoComplete operation is complete. */ on(type: "auto-complete-complete", listener: (event: { geometries: Polygon[]; target: GeometryService }) => void): esri.Handle; /** Fires when the buffer operation is complete. */ - on(type: "buffer-complete", listener: (event: { geometries: Geometry[]; target: GeometryService }) => void): esri.Handle; + on(type: "buffer-complete", listener: (event: { geometries: Polygon[]; target: GeometryService }) => void): esri.Handle; /** Fires when the convexHull operation is complete. */ on(type: "convex-hull-complete", listener: (event: { geometry: Geometry; target: GeometryService }) => void): esri.Handle; /** Fires when the cut operation is complete. */ @@ -13846,7 +14061,7 @@ declare module "esri/tasks/GeometryService" { /** Fires when the intersect operation is complete. */ on(type: "intersect-complete", listener: (event: { geometries: Geometry[]; target: GeometryService }) => void): esri.Handle; /** Fires when the labelPoints operation is complete. */ - on(type: "label-points-complete ", listener: (event: { geometries: Geometry[]; target: GeometryService }) => void): esri.Handle; + on(type: "label-points-complete ", listener: (event: { geometries: Point[]; target: GeometryService }) => void): esri.Handle; /** Fires when the lengths operation is complete. */ on(type: "lengths-complete", listener: (event: { result: any; target: GeometryService }) => void): esri.Handle; /** Fires when the offset operation is complete. */ @@ -14108,7 +14323,7 @@ declare module "esri/tasks/ImageServiceIdentifyParameters" { /** Specifies the mosaic rules defining the image sorting order. */ mosaicRule: MosaicRule; /** The pixel or RGB color value representing no information. */ - noData: any; + noData: string | number; /** Used along with the noData property. */ noDataInterpretation: string; /** Specify the pixel level being identified on the x and y axis. */ @@ -14160,7 +14375,7 @@ declare module "esri/tasks/ImageServiceIdentifyTask" { import ImageServiceIdentifyParameters = require("esri/tasks/ImageServiceIdentifyParameters"); import ImageServiceIdentifyResult = require("esri/tasks/ImageServiceIdentifyResult"); - /** Performs an identify operation on an image service resource . */ + /** Performs an identify operation on an image service resource. */ class ImageServiceIdentifyTask { /** * Creates a new ImageServiceIdentifyTask object. @@ -14181,6 +14396,60 @@ declare module "esri/tasks/ImageServiceIdentifyTask" { export = ImageServiceIdentifyTask; } +declare module "esri/tasks/ImageServiceMeasureParameters" { + import Geometry = require("esri/geometry/Geometry"); + import MosaicRule = require("esri/layers/MosaicRule"); + import Point = require("esri/geometry/Point"); + + /** Defines parameters for the ImageServiceMeasureTask. */ + class ImageServiceMeasureParameters { + /** The angular unit in which directions of line segments will be calculated. */ + angularUnit: string; + /** The area unit in which areas of polygons will be calculated. */ + areaUnit: string; + /** A geometry that defines the "from" location of the measurement. */ + fromGeometry: Geometry; + /** The linear unit in which height, length, or perimeters will be calculated. */ + linearUnit: string; + /** Specifies the mosaic rule when defining how individual images should be mosaicked. */ + mosaicRule: MosaicRule; + /** The mensuration rule to apply to the measure operation. */ + operation: string; + /** The pixel resolution being measured. */ + pixelSize: Point; + /** A geometry that defines the "to" location of the measurement. */ + toGeometry: Geometry; + /** Converts the ImageServiceMeasureParameters instance to a JSON object. */ + toJson(): any; + } + export = ImageServiceMeasureParameters; +} + +declare module "esri/tasks/ImageServiceMeasureTask" { + import esri = require("esri"); + import ImageServiceMeasureParameters = require("esri/tasks/ImageServiceMeasureParameters"); + + /** Performs a measure operation on an Image Service. */ + class ImageServiceMeasureTask { + /** + * Creates a new instance of ImageServiceMeasureTask + * @param url URL to the ArcGIS Server REST resource that represents an image service. + */ + constructor(url: string); + /** + * Sends a request to an image service to perform the designated measure operation. + * @param params Parameters to pass to the server to execute the task. + * @param callback The function to call when the method has completed. + * @param errback An error object is returned if an error occurs on the Server during task execution. + */ + execute(params: ImageServiceMeasureParameters, callback?: Function, errback?: Function): any; + /** Fires when measure completes. */ + on(type: "complete", listener: (event: { target: ImageServiceMeasureTask }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ImageServiceMeasureTask; +} + declare module "esri/tasks/JobInfo" { import GPMessage = require("esri/tasks/GPMessage"); @@ -14241,7 +14510,7 @@ declare module "esri/tasks/LengthsParameters" { /** If polylines are in geographic coordinate system, then geodesic needs to be set to true in order to calculate the ellipsoidal shortest path distance between each pair of the vertices in the polylines. */ geodesic: boolean; /** The length unit in which perimeters of polygons will be calculated. */ - lengthUnit: any; + lengthUnit: number | string; /** The array of polylines whose lengths are to be computed. */ polylines: Geometry[]; /** Creates a new LengthsParameter object. */ @@ -14408,7 +14677,7 @@ declare module "esri/tasks/PrintTemplate" { exportOptions: any; /** The print output format. */ format: string; - /** The text that appears on the PrintWidget's print button. */ + /** The text that appears on the Print widget's print button. */ label: string; /** The layout used for the print output. */ layout: string; @@ -14420,6 +14689,8 @@ declare module "esri/tasks/PrintTemplate" { preserveScale: boolean; /** When false, attribution is not displayed on the printout. */ showAttribution: boolean; + /** Indicates whether visible LabelLayers in the map are displayed or not. */ + showLabels: boolean; /** Creates a new PrintTemplate object. */ constructor(); } @@ -14666,6 +14937,8 @@ declare module "esri/tasks/RouteParameters" { startTimeIsUTC: boolean; /** The set of stops loaded as network locations during analysis. */ stops: any; + /** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */ + travelMode: any; /** If true, the hierarchy attribute for the network should be used in analysis. */ useHierarchy: boolean; /** A useful feature of the RouteTask is the ability to constrain stop visits to certain times of day, or "time windows". */ @@ -14707,6 +14980,8 @@ declare module "esri/tasks/RouteTask" { * @param url URL to the ArcGIS Server REST resource that represents a network analysis service. */ constructor(url: string); + /** Returns an object describing a Route service endpoint (URL of the endpoint is specified in the constructor). */ + getServiceDescription(): any; /** * Solves the route against the route layer with the route parameters. * @param params Route parameters used as input to generate the route. @@ -14784,6 +15059,8 @@ declare module "esri/tasks/ServiceAreaParameters" { timeOfDay: Date; /** Options for traveling to or from the facility. */ travelDirection: string; + /** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */ + travelMode: any; /** If true, the outermost polygon (at the maximum break value) will be trimmed. */ trimOuterPolygon: boolean; /** If polygons are being trimmed, provides the distance to trim. */ @@ -14837,6 +15114,8 @@ declare module "esri/tasks/ServiceAreaTask" { * @param url URL to the ArcGIS Server REST resource that represents a network analysis service. */ constructor(url: string); + /** Returns an object describing a Service Area service endpoint (URL of the endpoint is specified in the constructor). */ + getServiceDescription(): any; /** * Solve the service area. * @param params The ServiceAreaParameters object. @@ -14871,8 +15150,20 @@ declare module "esri/tasks/TrimExtendParameters" { /** Sets the polylines and other parameters for the trimExtend operation. */ class TrimExtendParameters { + /** Default value. */ + static DEFAULT_CURVE_EXTENSION: any; + /** When an extension is performed at an end, do not extrapolate the end segments attributes for the new point. */ + static KEEP_END_ATTRIBUTES: any; + /** When an extension is performed at an end, do not extrapolate the end segment's attributes for the new point. */ + static NO_END_ATTRIBUTES: any; + /** Do not extend the 'from' end of any path. */ + static NO_EXTEND_AT_FROM: any; + /** Do not extend the 'to' end of any path. */ + static NO_EXTEND_AT_TO: any; + /** When an extension is performed at an end, relocate the end point to the new position. */ + static RELOCATE_ENDS: any; /** A flag used along with the trimExtend operation. */ - extendHow: string; + extendHow: number; /** The array of polylines to trim or extend. */ polylines: Polyline[]; /** A polyline used as a guide for trimming or extending input polylines. */ @@ -14908,6 +15199,550 @@ declare module "esri/tasks/UniqueValueDefinition" { export = UniqueValueDefinition; } +declare module "esri/tasks/datareviewer/BatchValidationJob" { + import BatchValidationJobInfo = require("esri/tasks/datareviewer/BatchValidationJobInfo"); + import BatchValidationParameters = require("esri/tasks/datareviewer/BatchValidationParameters"); + + /** Encapsulates a Batch Validation Job. */ + class BatchValidationJob { + /** Contains a list of batch run IDs, one for each batch validation execution associated with this batch validation job. */ + batchRunIds : string[]; + /** Gets job creation date. */ + creationDate: Date; + /** Gets the Job Id. */ + jobId: string; + /** Gets batch job execution details. */ + jobInfo: BatchValidationJobInfo; + /** Gets batch job parameters. */ + parameters: BatchValidationParameters; + /** Gets the job status. */ + status: string; + /** Gets the job type. */ + type: string; + } + export = BatchValidationJob; +} + +declare module "esri/tasks/datareviewer/BatchValidationJobInfo" { + /** Encapsulates batch validation job execution details. */ + class BatchValidationJobInfo { + /** Gets the batch run Id of the job execution. */ + batchRunId: string; + /** Gets the finish time of the job execution. */ + finishTimeUTC: Date; + /** Gets the job's geoprocessing Job Id. */ + gpJobId: string; + /** Gets the URL of the geoprocessing service that executed the batch validation. */ + gpUrl: string; + /** Gets batch validation messages. */ + messages: string; + /** Gets the start time of the job execution. */ + startTimeUTC: Date; + /** Gets the batch validation status. */ + status: string; + } + export = BatchValidationJobInfo; +} + +declare module "esri/tasks/datareviewer/BatchValidationParameters" { + import Polygon = require("esri/geometry/Polygon"); + + /** Encapsulates batch job parameters including session Id, production workspace and analysis area. */ + class BatchValidationParameters { + /** A geometry that defines the validation extent. */ + analysisArea: Polygon; + /** Read-only: Gets the uploaded batch job name. */ + batchJobFileName: string; + /** Controls validation type on enterprise geodatabases. */ + changedFeaturesOnly: boolean; + /** Read-only: Gets the name of the web user that created the batch job schedule. */ + createdBy: string; + /** Gets or sets the batch validation execution schedule. */ + cronExpression: string; + /** Gets or sets the ending date for a batch validation schedule. */ + executionsEndDate: Date; + /** Gets or sets the ID of the uploaded batch job. */ + fileItemId: string; + /** Gets or sets the maximum number of batch validation executions that can run. */ + maxNumberOfExecutions: number; + /** Gets or sets the production workspace path. */ + productionWorkspace: string; + /** Gets or sets the ArcGIS Data Reviewer session. */ + sessionString: string; + /** Gets or sets the batch validation title. */ + title: string; + /** Gets or sets the user name under which records are written to the reviewer workspace. */ + userName: string; + } + export = BatchValidationParameters; +} + +declare module "esri/tasks/datareviewer/BatchValidationTask" { + import esri = require("esri"); + import SessionOptions = require("esri/tasks/datareviewer/SessionOptions"); + import BatchValidationParameters = require("esri/tasks/datareviewer/BatchValidationParameters"); + import ReviewerSession = require("esri/tasks/datareviewer/ReviewerSession"); + import BatchValidationJob = require("esri/tasks/datareviewer/BatchValidationJob"); + import BatchValidationJobInfo = require("esri/tasks/datareviewer/BatchValidationJobInfo"); + + /** Exposes functions for executing and scheduling Batch Validation in ArcGIS Data Reviewer for Server. */ + class BatchValidationTask { + /** + * Creates a new BatchValidationTask object. + * @param url The DataReviewerServer Server Object Extension (SOE) URL. + */ + constructor(url: string); + /** + * Cancels an executing job. + * @param jobId Job Id of the batch validation job to cancel. + */ + cancelJobExecution(jobId: string): any; + /** + * Creates a new Reviewer session. + * @param sessionName Name of the session to be created. + * @param sessionOptions Session properties to be used to create the session. + */ + createReviewerSession(sessionName: string, sessionOptions: SessionOptions): any; + /** + * Deletes an existing scheduled Batch Validation Job. + * @param jobId Job Id of the batch validation job to delete. + */ + deleteJob(jobId: string): any; + /** + * Pauses an existing Batch Validation Job's schedule. + * @param jobId Job Id of the batch validation job to be disabled. + */ + disableJob(jobId: string): any; + /** + * Edits the schedule, settings and title of an existing Batch Validation Job. + * @param jobId Job Id of the batch validation job to edit. + * @param parameters Parameters to change in an existing batch job. + */ + editJob(jobId: string, parameters: BatchValidationParameters): any; + /** + * Restarts an existing Batch Validation Job's schedule. + * @param jobId Job Id of the batch validation job to enable. + */ + enableJob(jobId: string): any; + /** + * Executes an adhoc job. + * @param parameters Parameters specifying the details of a job to execute. + */ + executeJob(parameters: BatchValidationParameters): any; + /** Retrieves all adhoc jobs from the server and returns an array of BatchValidationJob with the information. */ + getAdhocJobsList(): any; + /** + * Fetches Batch Validation Job details. + * @param jobId Job Id of the batch validation job. + */ + getJobDetails(jobId: string): any; + /** + * Fetches the Job Execution details of a Batch Validation Job. + * @param jobId Job Id of the batch validation job. + */ + getJobExecutionDetails(jobId: string): any; + /** Returns an object that contains Scheduled and AdhocJob IDs in two separate arrays. */ + getJobIds(): any; + /** Retrieves a list of localized life cycle status strings from the Reviewer workspace. */ + getLifecycleStatusStrings(): any; + /** Extracts the MapServer url from the full ArcGIS Data Reviewer for Server SOE url. */ + getReviewerMapServerUrl(): string; + /** Returns an array of sessions in a Reviewer workspace. */ + getReviewerSessions(): any; + /** Retrieves all scheduled jobs from the server and returns an array of BatchValidationJob with the information. */ + getScheduledJobsList(): any; + /** + * Schedules a new Batch Validation. + * @param parameters Parameters for scheduling a batch job. + */ + scheduleJob(parameters: BatchValidationParameters): any; + /** Fires when the cancelJobExecution method is complete. */ + on(type: "cancel-job-execution", listener: (event: { canceled: boolean; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the createReviewerSessions method is complete. */ + on(type: "create-reviewer-sessions", listener: (event: { reviewerSession: ReviewerSession; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the deleteJob method is complete. */ + on(type: "delete-job", listener: (event: { deleted: boolean; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the disableJob method is complete. */ + on(type: "disable-job", listener: (event: { disabled: boolean; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the editJob method is complete. */ + on(type: "edit-job", listener: (event: { edited: boolean; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the enableJob method is complete. */ + on(type: "enable-job", listener: (event: { enabled: boolean; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when an error occurs during a BatchValidationTask method execution. */ + on(type: "error", listener: (event: { error: Error; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the executeJob method is complete. */ + on(type: "execute-job", listener: (event: { jobId: string; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getAdhocJobsList method is complete. */ + on(type: "get-adhoc-jobs-list", listener: (event: { adhocJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getJobDetails method is complete. */ + on(type: "get-job-details", listener: (event: { jobDetails: BatchValidationJob; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getJobExecutionDetails method is complete. */ + on(type: "get-job-execution-details", listener: (event: { jobInfo: BatchValidationJobInfo; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getJobIds method is complete. */ + on(type: "get-job-ids", listener: (event: { adhocJobs: any[]; scheduledJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getLifecycleStatusStrings method is complete. */ + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getReviewerSessions method is complete. */ + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getScheduledJobsList method is complete. */ + on(type: "get-scheduled-jobs-list", listener: (event: { scheduledJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the scheduleJob method is complete. */ + on(type: "schedule-job", listener: (event: { jobId: string; target: BatchValidationTask }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = BatchValidationTask; +} + +declare module "esri/tasks/datareviewer/DashboardResult" { + import ReviewerFilters = require("esri/tasks/datareviewer/ReviewerFilters"); + + /** Encapsulates data describing a Dashboard Result. */ + class DashboardResult { + /** Array of reviewer result field value counts. */ + counts: any[]; + /** Name of the reviewer results field. */ + fieldName: string; + /** Array of reviewer results field values. */ + fieldValues: any[]; + /** An instance of ReviewerFilters class. */ + filters: ReviewerFilters; + /** + * Gets the result count for a field value. + * @param fieldValue Unique field value from the fieldValues array. + */ + getCount(fieldValue: string | number): number; + } + export = DashboardResult; +} + +declare module "esri/tasks/datareviewer/DashboardTask" { + import esri = require("esri"); + import SessionOptions = require("esri/tasks/datareviewer/SessionOptions"); + import ReviewerFilters = require("esri/tasks/datareviewer/ReviewerFilters"); + import ReviewerSession = require("esri/tasks/datareviewer/ReviewerSession"); + import DashboardResult = require("esri/tasks/datareviewer/DashboardResult"); + + /** Provides functionality to retrieve dashboard results from an ArcGIS Data Reviewer for Server Dashboard REST resource. */ + class DashboardTask { + /** + * Creates a new DashboardTask object. + * @param url The DataReviewerServer Server Object Extension (SOE) URL. + */ + constructor(url: string); + /** + * Creates a new Reviewer session. + * @param sessionName Name of the session to be created. + * @param sessionOptions Session properties to be used to create the session. + */ + createReviewerSession(sessionName: string, sessionOptions: SessionOptions): any; + /** Requests Dashboard results field names. */ + getDashboardFieldNames(): any; + /** + * Requests dashboard results by fieldName. + * @param fieldName Field name for dashboard results. + * @param filters Instance of ReviewerFilters containing one or more filters used to narrow down dashboard results. + */ + getDashboardResults(fieldName: string, filters?: ReviewerFilters): any; + /** Retrieves a list of localized life cycle status strings from the Reviewer workspace. */ + getLifecycleStatusStrings(): any; + /** Extracts the MapServer url from the full ArcGIS Data Reviewer for Server SOE url. */ + getReviewerMapServerUrl(): string; + /** Returns an array of sessions in a Reviewer workspace. */ + getReviewerSessions(): any; + /** Fires when the createReviewerSessions method is complete. */ + on(type: "create-reviewer-sessions", listener: (event: { reviewerSession: ReviewerSession; target: DashboardTask }) => void): esri.Handle; + /** Fires when an error occurs during a DashboardTask method execution. */ + on(type: "error", listener: (event: { error: Error; target: DashboardTask }) => void): esri.Handle; + /** Fires when the getDashboardFieldNames method is complete. */ + on(type: "get-dashboard-field-names", listener: (event: { fieldNames: any[]; target: DashboardTask }) => void): esri.Handle; + /** Fires when the getDashboardResults method is complete. */ + on(type: "get-dashboard-results", listener: (event: { dashboardResult: DashboardResult; target: DashboardTask }) => void): esri.Handle; + /** Fires when the getLifecycleStatusStrings method is complete. */ + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: DashboardTask }) => void): esri.Handle; + /** Fires when the getReviewerSessions method is complete. */ + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: DashboardTask }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = DashboardTask; +} + +declare module "esri/tasks/datareviewer/GetResultsQueryParameters" { + /** Encapsulates data used for retrieving results from the reviewer workspace. */ + class GetResultsQueryParameters { + /** The page number, zero based index, of the results to return. */ + pageNumber: number; + /** The number of items to list on a page. */ + pageSize: number; + /** Array of field names. */ + returnFields: any[]; + /** Indicates a field name by which to sort. */ + sortBy: string; + /** Controls sort order. */ + sortDescending: boolean; + /** Returns a JSON representation of an instance of GetResultsQueryParameters. */ + toJSON(): any; + } + export = GetResultsQueryParameters; +} + +declare module "esri/tasks/datareviewer/ReviewerAttributes" { + /** Encapsulates data used by the writeFeatureAsResult and writeResult methods of the ReviewerResults class. */ + class ReviewerAttributes { + /** Represents the state of a reviewer result. */ + lifecycleStatus: number; + /** Extra information describing a result or feature. */ + notes: string; + /** Represents an ArcGIS Data Reviewer resource name. */ + resourceName: string; + /** A status value (any string) to write to the ReviewStatus field for the result or feature written to the reviewer workspace. */ + reviewStatus: string; + /** The user name under which results or features are written to the reviewer workspace. */ + reviewTechnician: string; + /** Represents an ArcGIS Data Reviewer session ID, the numeric identifier of the session. */ + sessionId: number; + /** Represents an ArcGIS Data Reviewer severity value. */ + severity: number; + /** Subtype from the original feature that was checked and caused an error. */ + subtype: string; + /** Returns a JSON representation of an instance of ReviewerAttributes. */ + toJSON(): any; + } + export = ReviewerAttributes; +} + +declare module "esri/tasks/datareviewer/ReviewerFilters" { + import Polygon = require("esri/geometry/Polygon"); + + /** ReviewerFilters limit or precisely define which results to generate by applying conditions to a query for dashboard results. */ + class ReviewerFilters { + /** + * Queries an attribute by a value. + * @param fieldName The field used to perform the filter. + * @param fieldValues A value or an Array of values in fieldName to filter. + */ + addAttributeFilter(fieldName: string, fieldValues: string | number | any[]): void; + /** + * Queries an attribute by a range of values. + * @param fieldName The field used to perform the filter. + * @param min Minimum value range. + * @param max Maximum value range. + */ + addRangeFilter(fieldName: string, min: string | number, max: string | number): void; + /** + * Queries by a polygon. + * @param geometry The geometry used to perform the filter. + */ + addSpatialFilter(geometry: Polygon): void; + /** Returns the count of ReviewerFilters added. */ + getCount(): number; + /** Returns a JSON representation of a filter object. */ + toJSON(): any; + } + export = ReviewerFilters; +} + +declare module "esri/tasks/datareviewer/ReviewerLifecycle" { + /** The ReviewerLifecycle class specifies constant values for all lifecycle status and lifecycle phase strings within the Reviewer quality control workflow. */ + class ReviewerLifecycle { + /** Acceptable lifecycleStatus code = 4 belongs to Verification Phase. */ + ACCEPTABLE: number; + /** Code for Correction Phase. */ + CORRECTION: number; + /** Exception lifecycleStatus code = 9 belongs to Verification Phase. */ + EXCEPTION: number; + /** Failed lifecycleStatus code = 12 belongs to Verification Phase. */ + FAILED: number; + /** Object containing lifecycle phase codes and their associated descriptions. */ + LIFECYCLEPHASE_DESCRIPTIONS: any; + /** Object containing lifecycle status codes and their associated descriptions. */ + LIFECYCLESTATUS_DESCRIPTIONS: any; + /** Mark As Exception lifecycleStatus code = 3 belongs to Correction Phase. */ + MARK_AS_EXCEPTION: number; + /** New lifecycleStatus code = 10 belongs to Review Phase. */ + NEW: number; + /** Passed lifecycleStatus code = 11 belongs to Verification Phase. */ + PASSED: number; + /** Resolved lifecycleStatus code = 2 belongs to Correction Phase. */ + RESOLVED: number; + /** Code for Review Phase. */ + REVIEW: number; + /** Reviewed lifecycleStatus code = 1 belongs to Review Phase. */ + REVIEWED: number; + /** Unacceptable lifecycleStatus code = 6 belongs to Review Phase. */ + UNACCEPTABLE: number; + /** Unknown lifecycleStatus code = 0 belongs to Review Phase. */ + UNKNOWN: number; + /** Unresolved Acceptable lifecycleStatus code = 8 belongs to Verification Phase. */ + UNRESOLVED_ACCEPTABLE: number; + /** Unresolved Exception lifecycleStatus code = 5 belongs to Verification Phase. */ + UNRESOLVED_EXCEPTION: number; + /** Unresolved Unacceptable lifecycleStatus code = 7 belongs to Review Phase. */ + UNRESOLVED_UNACCEPTABLE: number; + /** Code for Verififcation Phase. */ + VERIFICATION: number; + /** + * This function returns the the associated lifecycle phase of the input lifecycle status. + * @param lifecycleStatus The lifecycle status code. + */ + getCurrentLifecyclePhase(lifecycleStatus: number): string; + /** + * This function accepts an array of lifecycle statuses and returns an object containing the next appropriate lifecycle status and phase that the record will advance to. + * @param lifecycleStatus An Array of lifecycle statuses. + */ + getLifecycleInfo(lifecycleStatus: any[]): any; + /** + * This function returns lifecycle phase string associated with the input lifecycle phase code. + * @param lifecyclePhase The lifecycle phase code. + */ + toLifecyclePhaseString(lifecyclePhase: number): string; + /** + * This function returns lifecycle status string associated with the input lifecycle status code. + * @param lifecycleStatus The lifecycle status code. + */ + toLifecycleStatusString(lifecycleStatus: number): string; + } + export = ReviewerLifecycle; +} + +declare module "esri/tasks/datareviewer/ReviewerResultsTask" { + import esri = require("esri"); + import SessionOptions = require("esri/tasks/datareviewer/SessionOptions"); + import ReviewerFilters = require("esri/tasks/datareviewer/ReviewerFilters"); + import GetResultsQueryParameters = require("esri/tasks/datareviewer/GetResultsQueryParameters"); + import ReviewerAttributes = require("esri/tasks/datareviewer/ReviewerAttributes"); + import Graphic = require("esri/graphic"); + import Geometry = require("esri/geometry/Geometry"); + import ReviewerSession = require("esri/tasks/datareviewer/ReviewerSession"); + import FeatureSet = require("esri/tasks/FeatureSet"); + + /** ReviewerResults allows access to the reviewer workspace. */ + class ReviewerResultsTask { + /** + * Creates a new ReviewerResultsTask object. + * @param url The DataReviewerServer Server Object Extension (SOE) URL. + */ + constructor(url: string); + /** + * Creates a new Reviewer session. + * @param sessionName Name of the session to be created. + * @param sessionOptions Session properties to be used to create the session. + */ + createReviewerSession(sessionName: string, sessionOptions: SessionOptions): any; + /** + * Fetches batch run information from REVBATCHRUNTABLE and REVCHECKRUNTABLE. + * @param batchRunIds Array of batchRunIds used to get batch run details. + */ + getBatchRunDetails(batchRunIds: any[]): any; + /** + * Utility operation that returns a where clause given a set of input filters. + * @param filters An instance of ReviewerFilters used to create a layer definition. + */ + getLayerDefinition(filters: ReviewerFilters): any; + /** Retrieves a list of localized life cycle status strings from the Reviewer workspace. */ + getLifecycleStatusStrings(): any; + /** + * Queries records from REVTABLEMAIN, REVBATCHRUNTABLE and REVCHECKRUNTABLE. + * @param getResultsQueryParameters Defines the size and scope of the FeatureSet returned to the callback function. + * @param filters Instance of ReviewerFilters used to query reviewer results. + */ + getResults(getResultsQueryParameters: GetResultsQueryParameters, filters?: ReviewerFilters): any; + /** Extracts the MapServer url from the full ArcGIS Data Reviewer for Server SOE url. */ + getReviewerMapServerUrl(): any; + /** Returns an array of sessions in a Reviewer workspace. */ + getReviewerSessions(): any; + /** + * Updates lifecycle status of the Reviewer results. + * @param sessionId Session that contains results to update. + * @param lifecycleStatus Lifecycle status to which the Reviewer results will get updated. + * @param technicianName Name of the technician performing the update. + * @param filters Instance of ReviewerFilters used to query Reviewer results. + */ + updateLifecycleStatus(sessionId: number, lifecycleStatus: number, technicianName: string, filters: ReviewerFilters): any; + /** + * Writes a feature to the reviewer workspace. + * @param reviewerAttributes Class used to encapsulate all fields to be written to the reviewer workspace. + * @param feature Graphic to write to the reviewer workspace. + */ + writeFeatureAsResult(reviewerAttributes: ReviewerAttributes, feature: Graphic): any; + /** + * Writes a geometry and associated reviewer attributes to the reviewer workspace. + * @param reviewerAttributes Class used to encapsulate all fields to be written to the reviewer workspace. + * @param geometry A Geometry (point, polyline or polygon) to write to the reviewer workspace. + */ + writeResult(reviewerAttributes: ReviewerAttributes, geometry: Geometry): any; + /** Fires when the createReviewerSession method is complete. */ + on(type: "create-reviewer-sessions", listener: (event: { reviewerSession: ReviewerSession; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when an error occurs during a ReviewerResultsTask method execution. */ + on(type: "error", listener: (event: { error: Error; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getBatchRunDetails method is complete. */ + on(type: "get-batch-run-details", listener: (event: { featureSet: FeatureSet; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getLayerDefinition method is complete. */ + on(type: "get-layer-definition", listener: (event: { whereClause: string; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getLifecycleStatusStrings method is complete. */ + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getResults method is complete. */ + on(type: "get-results", listener: (event: { featureSet: FeatureSet; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getReviewerSessions method is complete. */ + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the updateLifecycleStatus method is complete. */ + on(type: "update-lifecycle-status", listener: (event: { featureEditResults: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the writeFeatureAsResult method is complete. */ + on(type: "write-feature-as-result", listener: (event: { success: boolean; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the writeResult method is complete. */ + on(type: "write-result", listener: (event: { success: boolean; target: ReviewerResultsTask }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ReviewerResultsTask; +} + +declare module "esri/tasks/datareviewer/ReviewerSession" { + /** Represents an ArcGIS Data Reviewer session in which validation and manual quality control results are written to the reviewer workspace. */ + class ReviewerSession { + /** Numeric identifier of the session. */ + sessionId: number; + /** Session name. */ + sessionName: string; + /** Name under which records are written to the reviewer workspace. */ + userName: string; + /** Enterprise geodatabase version in which records are validated. */ + versionName: string; + /** + * Creates a new ReviewerSession object. + * @param sessionId Numeric identifier of the session. + * @param sessionName Name of the session. + * @param userName User name under which records are written to the reviewer workspace. + * @param versionName The enterprise geodatabase version in which records are validated. + */ + constructor(sessionId: string, sessionName: string, userName: string, versionName: string); + /** The Session ID and name in format Session 10 : Parcels. */ + toString(): string; + } + export = ReviewerSession; +} + +declare module "esri/tasks/datareviewer/SessionOptions" { + /** Represents an ArcGIS Data Reviewer session properties in which validation and manual quality control results are written to the reviewer workspace. */ + class SessionOptions { + /** Indicates how to handle duplicate results when writing the results to the Reviewer workspace. */ + duplicateFilter: string; + /** Indicates if validation result geometries are stored in the Reviewer workspace. */ + storeGeometry: boolean; + /** The user account to associate with a session. */ + userName: string; + /** Indicates an enterprise geodatabase version to associate with the session. */ + versionName: string; + /** + * Creates a new SessionOptions object. + * @param userName The username under which records are written to the reviewer workspace. + * @param versionName The enterprise geodatabase version under which records are written to the reviewer workspace. + * @param duplicateFilter Handle duplicate results when writing the results to the Reviewer workspace. + * @param storeGeometry Controls if validation result geometries are stored in the Reviewer workspace. + */ + constructor(userName: string, versionName: string, duplicateFilter: string, storeGeometry: boolean); + } + export = SessionOptions; +} + declare module "esri/tasks/geoenrichment/AddressStudyArea" { import StudyArea = require("esri/tasks/geoenrichment/StudyArea"); @@ -15019,7 +15854,7 @@ declare module "esri/tasks/geoenrichment/GeographyLevel" { declare module "esri/tasks/geoenrichment/GeographyQuery" { import GeographyQueryBase = require("esri/tasks/geoenrichment/GeographyQueryBase"); - /** (Beta at v3.12) Represents StandardGeographyQuery parameters to search for geographies by ID or Name. */ + /** (Currently in beta) Represents StandardGeographyQuery parameters to search for geographies by ID or Name. */ class GeographyQuery extends GeographyQueryBase { /** Array of geography IDs. */ geographyIDs: string[]; @@ -15036,7 +15871,7 @@ declare module "esri/tasks/geoenrichment/GeographyQuery" { declare module "esri/tasks/geoenrichment/GeographyQueryBase" { import SpatialReference = require("esri/SpatialReference"); - /** (Beta at v3.12) Base class for all GeographyQuery objects. */ + /** (Currently in beta) Base class for all GeographyQuery objects. */ class GeographyQueryBase { /** Two-digit country code. */ countryID: string; @@ -15113,7 +15948,7 @@ declare module "esri/tasks/geoenrichment/StandardGeographyQueryTask" { import GeographyQueryBase = require("esri/tasks/geoenrichment/GeographyQueryBase"); import FeatureSet = require("esri/tasks/FeatureSet"); - /** (Beta at v3.12) Geoenrichment helper task that returns standard geography IDs and features for the supported geographic levels in Canada, the United States and a number of European countries. */ + /** (Currently in beta) Geoenrichment helper task that returns standard geography IDs and features for the supported geographic levels in Canada, the United States and a number of European countries. */ class StandardGeographyQueryTask { /** * Creates a new instance of the StandardGeographyQueryTask class. @@ -15151,6 +15986,9 @@ declare module "esri/tasks/geoenrichment/StandardGeographyStudyArea" { declare module "esri/tasks/geoenrichment/StudyArea" { import GeographyLevel = require("esri/tasks/geoenrichment/GeographyLevel"); + import RingBuffer = require("esri/tasks/geoenrichment/RingBuffer"); + import DriveBuffer = require("esri/tasks/geoenrichment/DriveBuffer"); + import IntersectingGeographies = require("esri/tasks/geoenrichment/IntersectingGeographies"); /** The study area that is used for enrichment or for display in an Infographic widget. */ class StudyArea { @@ -15159,7 +15997,7 @@ declare module "esri/tasks/geoenrichment/StudyArea" { /** The identifiers for layers used to find comparison geographies. */ comparisonGeographyLevels: GeographyLevel[]; /** The options to apply to the study area. */ - options: any; + options: RingBuffer | DriveBuffer | IntersectingGeographies; /** If true, geometry will be returned. */ returnGeometry: boolean; /** Converts object to its JSON representation. */ @@ -15171,7 +16009,7 @@ declare module "esri/tasks/geoenrichment/StudyArea" { declare module "esri/tasks/geoenrichment/SubGeographyQuery" { import GeographyQueryBase = require("esri/tasks/geoenrichment/GeographyQueryBase"); - /** (Beta at v3.12) Represents StandardGeographyQuery parameters to search subgeographic areas that are within a parent geography. */ + /** (Currently in beta) Represents StandardGeographyQuery parameters to search subgeographic areas that are within a parent geography. */ class SubGeographyQuery extends GeographyQueryBase { /** Parent layer geography IDs. */ filterGeographyIDs: string; @@ -15196,7 +16034,7 @@ declare module "esri/tasks/locationproviders/CoordinatesLocationProvider" { import esri = require("esri"); import LocationProviderClientBase = require("esri/tasks/locationproviders/LocationProviderClientBase"); - /** (Beta at v3.12) The CoordinatesLocationProvider class uses the fields that contain Latitude and Longitude values to generate or locate geometries. */ + /** (Currently in beta) The CoordinatesLocationProvider class uses the fields that contain Latitude and Longitude values to generate or locate geometries. */ class CoordinatesLocationProvider extends LocationProviderClientBase { /** The attribute field in the graphic object that has the longitude (X) values. */ xField: string; @@ -15215,7 +16053,7 @@ declare module "esri/tasks/locationproviders/GeometryLocationProvider" { import esri = require("esri"); import LocationProviderClientBase = require("esri/tasks/locationproviders/LocationProviderClientBase"); - /** (Beta at v3.12) The GeometryLocationProvider class uses the field in the data that has geometry as a JSON to generate the corresponding geometry. */ + /** (Currently in beta) The GeometryLocationProvider class uses the field in the data that has geometry as a JSON to generate the corresponding geometry. */ class GeometryLocationProvider extends LocationProviderClientBase { /** The attribute field in the graphic object that contains the JSON string representing the geometry. */ geometryField: string; @@ -15232,7 +16070,7 @@ declare module "esri/tasks/locationproviders/LocationProviderBase" { import esri = require("esri"); import Graphic = require("esri/graphic"); - /** (Beta at v3.12) The base class for all LocationProviders. */ + /** (Currently in beta) The base class for all LocationProviders. */ class LocationProviderBase { /** The geometry type of the returned features. */ geometryType: string; @@ -15261,7 +16099,7 @@ declare module "esri/tasks/locationproviders/LocationProviderClientBase" { import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); import SpatialReference = require("esri/SpatialReference"); - /** (Beta at v3.12) The base class for CoordinatesLocationProvider and GeometryLocationProvider. */ + /** (Currently in beta) The base class for CoordinatesLocationProvider and GeometryLocationProvider. */ class LocationProviderClientBase extends LocationProviderBase { /** The Spatial Reference of the input geometries. */ inSpatialReference: SpatialReference; @@ -15272,7 +16110,7 @@ declare module "esri/tasks/locationproviders/LocationProviderClientBase" { declare module "esri/tasks/locationproviders/LocationProviderRemoteBase" { import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); - /** (Beta at v3.12) The base class for Location Providers that use a remote service to locate geometries. */ + /** (Currently in beta) The base class for Location Providers that use a remote service to locate geometries. */ class LocationProviderRemoteBase extends LocationProviderBase { } export = LocationProviderRemoteBase; @@ -15283,7 +16121,7 @@ declare module "esri/tasks/locationproviders/LocatorLocationProvider" { import LocationProviderRemoteBase = require("esri/tasks/locationproviders/LocationProviderRemoteBase"); import Locator = require("esri/tasks/locator"); - /** (Beta at v3.12) The LocatorLocationProvider class uses a geocode service through the Locator object to generate or locate geometries using fields in the graphics that contain Street address information */ + /** (Currently in beta) The LocatorLocationProvider class uses a geocode service through the Locator object to generate or locate geometries using fields in the graphics that contain Street address information */ class LocatorLocationProvider extends LocationProviderRemoteBase { /** Object that matches the Locator address fields to corresponding attribute names in the Graphic object. */ addressFields: any; @@ -15303,7 +16141,7 @@ declare module "esri/tasks/locationproviders/QueryTaskLocationProvider" { import LocationProviderRemoteBase = require("esri/tasks/locationproviders/LocationProviderRemoteBase"); import QueryTask = require("esri/tasks/QueryTask"); - /** (Beta at v3.12) The QueryTaskLocationProvider performs a query against a ArcGIS Feature service or Map service layer based on common fields that are present in both the data and the ArcGIS layer. */ + /** (Currently in beta) The QueryTaskLocationProvider performs a query against a ArcGIS Feature service or Map service layer based on common fields that are present in both the data and the ArcGIS layer. */ class QueryTaskLocationProvider extends LocationProviderRemoteBase { /** A query parameter object that will be used to query the ArcGIS layer. */ queryParameters: any; @@ -15327,7 +16165,7 @@ declare module "esri/tasks/locationproviders/StandardGeographyQueryLocationProvi import LocationProviderRemoteBase = require("esri/tasks/locationproviders/LocationProviderRemoteBase"); import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask"); - /** (Beta at v3.12) The StandardGeographyQueryLocationProvider class uses the Geoenrichment service to generate geometries by querying the standard geography layers. */ + /** (Currently in beta) The StandardGeographyQueryLocationProvider class uses the Geoenrichment service to generate geometries by querying the standard geography layers. */ class StandardGeographyQueryLocationProvider extends LocationProviderRemoteBase { /** A template to be used to build the query for Standard Geography query. */ geographyQueryTemplate: string; @@ -15491,6 +16329,90 @@ declare module "esri/tasks/query" { export = Query; } +declare module "esri/toolbars/ImageServiceMeasureTool" { + import esri = require("esri"); + import SimpleFillSymbol = require("esri/symbols/SimpleFillSymbol"); + import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); + import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); + import Geometry = require("esri/geometry/Geometry"); + + /** A toolbar that provides support for measuring image services. */ + class ImageServiceMeasureTool { + /** The angular unit in which directions of line segments will be calculated. */ + angularUnit: string; + /** The area unit in which areas of polygons will be calculated. */ + areaUnit: string; + /** Symbol to be used when drawing a polygon or extent. */ + fillSymbol: SimpleFillSymbol; + /** The linear unit in which height, length, or perimeters will be calculated. */ + linearUnit: string; + /** Symbol to be used when drawing a line. */ + lineSymbol: SimpleLineSymbol; + /** Symbol to be used when drawing a point. */ + markerSymbol: SimpleMarkerSymbol; + /** + * Creates a new instance of ImageServiceMeasureTool. + * @param params Constructor options. + */ + constructor(params: esri.ImageServiceMeasureToolOptions); + /** + * Activates the toolbar for performing the measure operation. + * @param operation The mensuration rule to apply to the measure operation. + */ + activate(operation: string): void; + /** Deactivates the toolbar. */ + deactivate(): void; + /** Returns a list of measure operations supported by the image service. */ + getSupportedMeasureOperations(): string[]; + /** Returns a list of supported linear, angular and area units. */ + getSupportedUnits(): string[]; + /** Disables the tooltip message for performing a draw. */ + hideDrawTooltip(): void; + /** + * Sets the angularUnit. + * @param unit The angular unit to set. + */ + setAngularUnit(unit: string): void; + /** + * Sets the areaUnit. + * @param unit Possible Values: esriSquareInches | esriSqudareFeet | esriSquareYards | esriAcres | esriSquareMiles | esriSquareMillimeters | esriSquareCentimeters | esriSquareDecimeters | esriSquareMeters | esriAres | esriHectares | esriSquareKilometers + */ + setAreaUnit(unit: string): void; + /** + * Sets the fillSymbol. + * @param fillSymbol The fill symbol to set. + */ + setFillSymbol(fillSymbol: SimpleFillSymbol): void; + /** + * Sets the linearUnit. + * @param unit The linear unit to set. + */ + setLinearUnit(unit: string): void; + /** + * Sets the lineSymbol. + * @param lineSymbol The line symbol to set. + */ + setLineSymbol(lineSymbol: SimpleLineSymbol): void; + /** + * Sets the markerSymbol. + * @param markerSymbol The marker symbol to set. + */ + setMarkerSymbol(markerSymbol: SimpleMarkerSymbol): void; + /** Enables the tooltip message for performing a draw. */ + showDrawTooltip(): void; + /** Fires when the drawing is complete. */ + on(type: "draw-end", listener: (event: { geometry: Geometry; target: ImageServiceMeasureTool }) => void): esri.Handle; + /** Fires when the user starts drawing. */ + on(type: "draw-start", listener: (event: { target: ImageServiceMeasureTool }) => void): esri.Handle; + /** Fires when the measure operation has been performed. */ + on(type: "measure-end", listener: (event: { measureResult: any; target: ImageServiceMeasureTool }) => void): esri.Handle; + /** Fires when the unit has been changed. */ + on(type: "unit-change", listener: (event: { measureResult: any; target: ImageServiceMeasureTool }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = ImageServiceMeasureTool; +} + declare module "esri/toolbars/draw" { import esri = require("esri"); import SimpleFillSymbol = require("esri/symbols/SimpleFillSymbol"); @@ -15823,7 +16745,7 @@ declare module "esri/units" { static POINTS: any; /** Units are square centimeters. */ static SQUARE_CENTIMETERS: any; - /** Units are square deciemeters. */ + /** Units are square decimeters. */ static SQUARE_DECIMETERS: any; /** Units are square feet. */ static SQUARE_FEET: any; @@ -16013,34 +16935,18 @@ declare module "esri/workers/WorkerClient" { * Import any script or function into the worker. * @param paths An AMD require path to a script file to import. */ - importScripts(paths: string): any; - /** - * Import any script or function into the worker. - * @param paths An AMD require path to a script file to import. - */ - importScripts(paths: string[]): any; + importScripts(paths: string | string[]): any; /** * Posts a message to the worker. * @param msg The data to post to the worker. * @param transfers An optional array of transferable objects. */ - postMessage(msg: any, transfers?: any[]): any; - /** - * Posts a message to the worker. - * @param msg The data to post to the worker. - * @param transfers An optional array of transferable objects. - */ - postMessage(msg: any[], transfers?: any[]): any; + postMessage(msg: any | any[], transfers?: any[]): any; /** * Sets the worker that is used in the Worker Client. * @param paths An AMD require path to a script file to import. */ - setWorker(paths: string): void; - /** - * Sets the worker that is used in the Worker Client. - * @param paths An AMD require path to a script file to import. - */ - setWorker(paths: string[]): void; + setWorker(paths: string | string[]): void; /** Terminates the worker and cancels all unresolved messages. */ terminate(): void; } From aaa447bd7e4b4dbfc75e6ea6c393a86c6d567bdc Mon Sep 17 00:00:00 2001 From: "Watal M. Iwasaki" Date: Fri, 17 Jul 2015 00:51:16 +0900 Subject: [PATCH 127/416] i18next: Add init() and setLng() with a two-arg callback --- i18next/i18next.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 3d24c9b96..e20cb4c93 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -87,6 +87,7 @@ interface I18nextStatic { }; init(callback?: (t: (key: string, options?: any) => string) => void ): JQueryDeferred; init(options?: I18nextOptions, callback?: (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; @@ -104,6 +105,7 @@ interface I18nextStatic { preload(languages: string[], callback?: (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; From 7706ea89164d07e8aca9d6de46111d1f488b17c7 Mon Sep 17 00:00:00 2001 From: Scott Date: Thu, 16 Jul 2015 08:56:54 -0700 Subject: [PATCH 128/416] Rename angular-formly-test.ts to angular-formly-tests.ts Renamed according to comply with repo standards. --- .../{angular-formly-test.ts => angular-formly-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename angular-formly/{angular-formly-test.ts => angular-formly-tests.ts} (100%) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-tests.ts similarity index 100% rename from angular-formly/angular-formly-test.ts rename to angular-formly/angular-formly-tests.ts From 3aae128161027bfb8dced69bc95d9c85929c09fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 19:33:38 +0300 Subject: [PATCH 129/416] easy-xapi --- easy-xapi/easy-xapi-tests.ts | 32 ++++++++++++++++++++++++++ easy-xapi/easy-xapi.d.ts | 44 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 easy-xapi/easy-xapi-tests.ts create mode 100644 easy-xapi/easy-xapi.d.ts diff --git a/easy-xapi/easy-xapi-tests.ts b/easy-xapi/easy-xapi-tests.ts new file mode 100644 index 000000000..70c5351d4 --- /dev/null +++ b/easy-xapi/easy-xapi-tests.ts @@ -0,0 +1,32 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// + +import express = require('express'); +import eXapi = require('easy-xapi'); + +eXapi.init({ + jSend: { + partial: true + } +}); + +var xApi = eXapi.create({ + root: __dirname, + log: { + name: 'Log', + level: 'info' + }, + port: 3000, + name: 'test', + mount: function (app) { + app.get('/', function (req, res) { + res.send('ok'); + }); + } +}); + +xApi.listen(); diff --git a/easy-xapi/easy-xapi.d.ts b/easy-xapi/easy-xapi.d.ts new file mode 100644 index 000000000..612dd51d5 --- /dev/null +++ b/easy-xapi/easy-xapi.d.ts @@ -0,0 +1,44 @@ +// Type definitions for easy-xapi +// Project: https://github.com/DeadAlready/easy-xapi +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module Express { + export interface Request { + log: any; + info: any; + } +} + +declare module "easy-xapi" { + import express = require('express'); + import http = require('http'); + + interface InitConfig { + jSend?: {partial: boolean}; + } + + interface Config { + root: string; + port: number; + name: string; + log: { + name: string; + level: string + } + mount: (app: express.Application) => void + } + + interface Result { + express: any; + app: express.Application; + server: http.Server; + listen: () => void; + } + + export function init(conf: InitConfig): void; + export function create(conf: Config): Result; +} From e6b1d5f73b03df88acabef15a393e4a52e19e681 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Thu, 16 Jul 2015 09:49:34 -0700 Subject: [PATCH 130/416] Formatted bardjs tests. --- bardjs/bardjs-tests.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index 3eedd970b..3aba6cade 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -128,11 +128,11 @@ module bardTests { */ function test_debugging() { console.log( - bard.debugging(true), // should be true - bard.debugging(false), // should be false - bard.debugging(42), // should be true - bard.debugging(''), // should be false - bard.debugging() // should be false + bard.debugging(true), // should return true + bard.debugging(false), // should return false + bard.debugging(42), // should return true + bard.debugging(''), // should return false + bard.debugging() // should return false ); } @@ -280,4 +280,4 @@ module bardTests { function done() { console.log('...Done'); } bard.wrapWithDone(callback, done); } -} \ No newline at end of file +} From 7fcdbd1a9b5ebdf39b5ac8e51ce72adfde685d74 Mon Sep 17 00:00:00 2001 From: Andrew Archibald Date: Thu, 16 Jul 2015 10:14:38 -0700 Subject: [PATCH 131/416] Made myService in bard tests minification safe --- bardjs/bardjs-tests.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index 3aba6cade..b033ffe3c 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -9,8 +9,6 @@ module bardTests { assert = chai.assert; class MyService { - static $inject = ['$q']; - constructor(private $q: angular.IQService) {} remoteCall(): angular.IPromise { @@ -20,6 +18,7 @@ module bardTests { } } + myService.$inject = ['$q']; function myService($q: angular.IQService) { return new MyService($q); } From 98440df4412a47e844039acf50025b98709d616d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 20:19:32 +0300 Subject: [PATCH 132/416] Add xHeaderDefaults --- easy-xapi/easy-xapi.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/easy-xapi/easy-xapi.d.ts b/easy-xapi/easy-xapi.d.ts index 612dd51d5..4afe5b44c 100644 --- a/easy-xapi/easy-xapi.d.ts +++ b/easy-xapi/easy-xapi.d.ts @@ -25,6 +25,7 @@ declare module "easy-xapi" { root: string; port: number; name: string; + xHeaderDefaults: Object; log: { name: string; level: string From 09e37c0f4069b986237c4fa8506d28b243e88aeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 20:19:53 +0300 Subject: [PATCH 133/416] Fix typo --- easy-xapi/easy-xapi.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/easy-xapi/easy-xapi.d.ts b/easy-xapi/easy-xapi.d.ts index 4afe5b44c..7e59a14b5 100644 --- a/easy-xapi/easy-xapi.d.ts +++ b/easy-xapi/easy-xapi.d.ts @@ -25,7 +25,7 @@ declare module "easy-xapi" { root: string; port: number; name: string; - xHeaderDefaults: Object; + xHeaderDefaults?: Object; log: { name: string; level: string From 4b055bdf5ab9c2cbd6bd3721460b53ba38ff01ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 20:58:44 +0300 Subject: [PATCH 134/416] Updates for easy- definitions --- easy-jsend/easy-jsend.d.ts | 4 ++-- easy-x-headers/easy-x-headers.d.ts | 2 +- easy-xapi/easy-xapi.d.ts | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/easy-jsend/easy-jsend.d.ts b/easy-jsend/easy-jsend.d.ts index 21a9bc11e..b45fbdac7 100644 --- a/easy-jsend/easy-jsend.d.ts +++ b/easy-jsend/easy-jsend.d.ts @@ -27,7 +27,7 @@ declare module Express { export interface Response { success (data?: any, status?: number): void; fail (data: any, status?: number): void; - error (err: any): void; + error (err: any, status?: number): void; partial? (data: PartialInput, status?: number): void; makePartial? (data: MakePartialInput): void; } @@ -35,4 +35,4 @@ declare module Express { declare module "easy-jsend" { export function init(conf?:{partial:boolean}): void; -} \ No newline at end of file +} diff --git a/easy-x-headers/easy-x-headers.d.ts b/easy-x-headers/easy-x-headers.d.ts index c0a13d1a8..4158654ed 100644 --- a/easy-x-headers/easy-x-headers.d.ts +++ b/easy-x-headers/easy-x-headers.d.ts @@ -14,5 +14,5 @@ declare module Express { declare module "easy-x-headers" { import express = require('express'); - export function getMiddleware(): express.RequestHandler; + export function getMiddleware(defaults?: Object): express.RequestHandler; } diff --git a/easy-xapi/easy-xapi.d.ts b/easy-xapi/easy-xapi.d.ts index 7e59a14b5..2468cb8b6 100644 --- a/easy-xapi/easy-xapi.d.ts +++ b/easy-xapi/easy-xapi.d.ts @@ -9,7 +9,6 @@ declare module Express { export interface Request { log: any; - info: any; } } From ac1ca868dd29ec8a4e76926692cfbc180fcba4a3 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Thu, 16 Jul 2015 11:52:50 -0700 Subject: [PATCH 135/416] Expanded tests, defined formlyConfig, and defined formlyValidationMessages. --- angular-formly/angular-formly-tests.ts | 30 ++++++++- angular-formly/angular-formly.d.ts | 90 ++++++++++++++++++++++++-- 2 files changed, 114 insertions(+), 6 deletions(-) diff --git a/angular-formly/angular-formly-tests.ts b/angular-formly/angular-formly-tests.ts index 603840208..ef6a38463 100644 --- a/angular-formly/angular-formly-tests.ts +++ b/angular-formly/angular-formly-tests.ts @@ -6,11 +6,37 @@ interface IScope extends ng.IScope { to: { label: string; } } +class FormConfig { + constructor(formlyConfig: AngularFormly.IFormlyConfig, formlyValidationMessages: AngularFormly.IValidationMessages) { + formlyConfig.setWrapper({ + name: 'validation', + types: ['input', 'customInput'], + templateUrl: 'my-messages.html' + }); + + formlyValidationMessages.addStringMessage('required', 'This field is required'); + + formlyConfig.setType({ + name: 'customInput', + extends: 'input' + }); + } +} + class AppController { fields: AngularFormly.IFieldConfigurationObject[]; - constructor($scope: ng.IScope) { + constructor() { var vm = this; vm.fields = [ + { + key: 'firstName', + type: 'customInput', + templateOptions: { + required: true, + label: 'First Name', + foo: 'hi' + } + }, { key: 'email', type: 'input', @@ -43,7 +69,7 @@ class AppController { }, validation: { messages: { - required: function($viewValue: any, $modelValue: any, scope: IScope) { + required: function($viewValue: any, $modelValue: any, scope: AngularFormly.ITemplateScope) { return scope.to.label + ' is required' } } diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 8ce552c52..8f76b3ccf 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -42,7 +42,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue: any, $modelValue: any, scope: Object): any; + ($viewValue: any, $modelValue: any, scope: ITemplateScope): any; } @@ -56,7 +56,7 @@ declare module AngularFormly { interface ITemplateManipulator { - (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; + (template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement; } @@ -121,8 +121,8 @@ declare module AngularFormly { */ interface IWatcher { deep?: boolean; //Defaults to false - expression?: string | { (field: string, scope: Object): boolean }; - listener: (field: string, newValue: any, oldValue: any, scope: Object, stopWatching: Function) => void; + expression?: string | { (field: string, scope: ITemplateScope): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -489,4 +489,86 @@ declare module AngularFormly { } + /** + * + * + * see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options + */ + interface ITypeOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + defaultOptions?: IFieldConfigurationObject | Function; + controller?: Function | string | any[]; + data?: Object; + extends?: string; + link?: ng.IDirectiveLinkFn; + overwriteOk?: boolean; + name: string; + template?: Function | string; + templateUrl?: Function | string; + validateOptions?: Function; + wrapper?: string | string[]; + } + + interface IWrapperOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + overwriteOk?: boolean; + name?: string; + template?: string; + templateUrl?: string; + types?: string[]; + validateOptions?: Function; + } + + interface IFormlyConfig { + setType(typeOptions: ITypeOptions): void; + setWrapper(wrapperOptions: IWrapperOptions): void; + + } + + interface ITemplateScopeOptions { + formControl: ng.IFormController | ng.IFormController[]; + templateOptions: ITemplateOptions; + validation: Object; + } + + /** + * see http://docs.angular-formly.com/docs/custom-templates#templates-scope + */ + interface ITemplateScope { + options: ITemplateScopeOptions; + //Shortcut to options.formControl + fc: ng.IFormController | ng.IFormController[]; + //all the fields for the form + fields: IFieldConfigurationObject[]; + //the form controller the field is in + form: any; + //The object passed as options.formState to the formly-form directive. Use this to share state between fields. + formState: Object; + //The id of the field. You shouldn't have to use this. + id: string; + //The index of the field the form is on (in ng-repeat) + index: number; + //the model of the form (or the model specified by the field if it was specified). + model: Object | string; + //Shortcut to options.validation.errorExistsAndShouldBeVisible + showError: boolean; + //Shortcut to options.templateOptions + to: ITemplateOptions; + } + + /** + * see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage + */ + interface IValidationMessages { + addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void; + addStringMessage(name: string, string: string): void; + messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string }; + } + } \ No newline at end of file From 91df93db208c4b3cf79fd49f6e8b3d72413f4305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Thu, 16 Jul 2015 22:45:02 +0300 Subject: [PATCH 136/416] Update easy-xapi output --- easy-xapi/easy-xapi.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/easy-xapi/easy-xapi.d.ts b/easy-xapi/easy-xapi.d.ts index 2468cb8b6..25d95b432 100644 --- a/easy-xapi/easy-xapi.d.ts +++ b/easy-xapi/easy-xapi.d.ts @@ -5,6 +5,7 @@ /// /// +/// declare module Express { export interface Request { @@ -15,6 +16,7 @@ declare module Express { declare module "easy-xapi" { import express = require('express'); import http = require('http'); + import bunyan = require('bunyan'); interface InitConfig { jSend?: {partial: boolean}; @@ -36,6 +38,7 @@ declare module "easy-xapi" { express: any; app: express.Application; server: http.Server; + log: bunyan.Logger; listen: () => void; } From 563cc35a17808ace7d527f1af829e74a2431290b Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 16 Jul 2015 22:25:10 +0100 Subject: [PATCH 137/416] Type definitions and tests for node title-case module --- title-case/title-case-tests.ts | 7 +++++++ title-case/title-case.d.ts | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 title-case/title-case-tests.ts create mode 100644 title-case/title-case.d.ts diff --git a/title-case/title-case-tests.ts b/title-case/title-case-tests.ts new file mode 100644 index 000000000..d1183db8f --- /dev/null +++ b/title-case/title-case-tests.ts @@ -0,0 +1,7 @@ +/// + +import titleCase = require('title-case'); + +console.log(titleCase('string')); // => "String" +console.log(titleCase('PascalCase')); // => "Pascal Case" +console.log(titleCase('STRING', 'tr')); // => "Strıng" diff --git a/title-case/title-case.d.ts b/title-case/title-case.d.ts new file mode 100644 index 000000000..c8e4dee30 --- /dev/null +++ b/title-case/title-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for title-case +// Project: https://github.com/blakeembrey/title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "title-case" { + function titleCase(string1: string, string2?: string): string; + export = titleCase; +} \ No newline at end of file From 212793c4be051977f73675fa9bb125d891df037a Mon Sep 17 00:00:00 2001 From: Jeff Cross Date: Thu, 16 Jul 2015 15:59:19 -0700 Subject: [PATCH 138/416] angular2: add typings for angular2 and angular2 router --- angular2/angular2-2.0.0-alpha.31.d.ts | 6137 ++++++++++++++++++++++++ angular2/angular2.d.ts | 6218 +++++++++++-------------- angular2/router-2.0.0-alpha.31.d.ts | 459 ++ angular2/router.d.ts | 325 +- 4 files changed, 9552 insertions(+), 3587 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.31.d.ts create mode 100644 angular2/router-2.0.0-alpha.31.d.ts diff --git a/angular2/angular2-2.0.0-alpha.31.d.ts b/angular2/angular2-2.0.0-alpha.31.d.ts new file mode 100644 index 000000000..dfad7d349 --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.31.d.ts @@ -0,0 +1,6137 @@ +// Type definitions for Angular v2.0.0-alpha.31 +// Project: http://angular.io/ +// Definitions by: angular team +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// *********************************************************** +// This file is generated by the Angular build process. +// Please do not create manual edits or send pull requests +// modifying this file. +// *********************************************************** + +// Angular depends transitively on these libraries. +// If you don't have them installed you can run +// $ tsd query es6-promise rx rx-lite --action install --save +/// +/// + +interface List extends Array {} +interface Map {} +interface StringMap extends Map {} + +declare module ng { + type SetterFn = typeof Function; + type int = number; + interface Type extends Function { + new (...args:any[]):any; + } + + // See https://github.com/Microsoft/TypeScript/issues/1168 + class BaseException /* extends Error */ { + message: string; + stack: string; + toString(): string; + } + interface InjectableReference {} +} + + + + +/** + * The `angular2` is the single place to import all of the individual types. + */ +declare module ng { + class DehydratedException extends BaseException { + } + + class ExpressionChangedAfterItHasBeenChecked extends BaseException { + } + + class ChangeDetectionError extends BaseException { + + location: string; + } + + + /** + * ON_PUSH means that the change detector's mode will be set to CHECK_ONCE during hydration. + */ + var ON_PUSH:any; + + + /** + * DEFAULT means that the change detector's mode will be set to CHECK_ALWAYS during hydration. + */ + var DEFAULT:any; + + + /** + * Controls change detection. + * + * {@link ChangeDetectorRef} allows requesting checks for detectors that rely on observables. It + * also allows detaching and + * attaching change detector subtrees. + */ + class ChangeDetectorRef { + + + /** + * Request to check all ON_PUSH ancestors. + */ + requestCheck(): void; + + + /** + * Detaches the change detector from the change detector tree. + * + * The detached change detector will not be checked until it is reattached. + */ + detach(): void; + + + /** + * Reattach the change detector to the change detector tree. + * + * This also requests a check of this change detector. This reattached change detector will be + * checked during the + * next change detection run. + */ + reattach(): void; + } + + class Pipes { + + + /** + * Map of {@link Pipe} names to {@link PipeFactory} lists used to configure the + * {@link Pipes} registry. + * + * #Example + * + * ``` + * var pipesConfig = { + * 'json': [jsonPipeFactory] + * } + * @Component({ + * viewInjector: [ + * bind(Pipes).toValue(new Pipes(pipesConfig)) + * ] + * }) + * ``` + */ + config: StringMap; + + get(type: string, obj: any, cdRef?: ChangeDetectorRef, existingPipe?: Pipe): Pipe; + } + + + /** + * Indicates that the result of a {@link Pipe} transformation has changed even though the reference + * has not changed. + * + * The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored. + */ + class WrappedValue { + + wrapped: any; + } + + + /** + * An interface for extending the list of pipes known to Angular. + * + * If you are writing a custom {@link Pipe}, you must extend this interface. + * + * #Example + * + * ``` + * class DoublePipe implements Pipe { + * supports(obj) { + * return true; + * } + * + * onDestroy() {} + * + * transform(value, args = []) { + * return `${value}${value}`; + * } + * } + * ``` + */ + interface Pipe { + + supports(obj: any): boolean; + + onDestroy(): void; + + transform(value: any, args: List): any; + } + + interface PipeFactory { + + supports(obs: any): boolean; + + create(cdRef: ChangeDetectorRef): Pipe; + } + + class NullPipe extends BasePipe { + + called: boolean; + + supports(obj: any): boolean; + + transform(value: any, args?: List): WrappedValue; + } + + class NullPipeFactory implements PipeFactory { + + supports(obj: any): boolean; + + create(cdRef: ChangeDetectorRef): Pipe; + } + + var defaultPipes : Pipes ; + + + /** + * Provides default implementation of supports and onDestroy. + * + * #Example + * + * ``` + * class DoublePipe extends BasePipe {* + * transform(value) { + * return `${value}${value}`; + * } + * } + * ``` + */ + class BasePipe implements Pipe { + + supports(obj: any): boolean; + + onDestroy(): void; + + transform(value: any, args: List): any; + } + + class Locals { + + parent: Locals; + + current: Map; + + contains(name: string): boolean; + + get(name: string): any; + + set(name: string, value: any): void; + + clearValues(): void; + } + + + interface AbstractControl_onlySelfArgs { + onlySelf?: boolean; + } + + interface AbstractControl_updateValueAndValidityArgs { + onlySelf?: boolean; + emitEvent?: boolean; + } + + /** + * Omitting from external API doc as this is really an abstract internal concept. + */ + class AbstractControl { + + validator: Function; + + value: any; + + status: string; + + valid: boolean; + + errors: StringMap; + + pristine: boolean; + + dirty: boolean; + + touched: boolean; + + untouched: boolean; + + valueChanges: Observable; + + markAsTouched(): void; + + markAsDirty(args?:AbstractControl_onlySelfArgs): void; + + setParent(parent: any): void; + + updateValidity(args?:AbstractControl_onlySelfArgs): void; + + updateValueAndValidity(args?:AbstractControl_updateValueAndValidityArgs): void; + + find(path: List| string): AbstractControl; + + getError(errorCode: string, path?: List): any; + + hasError(errorCode: string, path?: List): boolean; + } + + class AbstractControlDirective { + + control: AbstractControl; + + value: any; + + valid: boolean; + + errors: StringMap; + + pristine: boolean; + + dirty: boolean; + + touched: boolean; + + untouched: boolean; + } + + + interface Control_updateValueOptions { + onlySelf?: boolean; + emitEvent?: boolean; + } + /** + * Defines a part of a form that cannot be divided into other controls. + * + * `Control` is one of the three fundamental building blocks used to define forms in Angular, along + * with + * {@link ControlGroup} and {@link ControlArray}. + */ + class Control extends AbstractControl { + + updateValue(value: any, options?: Control_updateValueOptions): void; + + registerOnChange(fn: Function): void; + } + + + /** + * Defines a part of a form, of fixed length, that can contain other controls. + * + * A ControlGroup aggregates the values and errors of each {@link Control} in the group. Thus, if + * one of the controls + * in a group is invalid, the entire group is invalid. Similarly, if a control changes its value, + * the entire group + * changes as well. + * + * `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular, + * along with + * {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other controls, + * but is of variable + * length. + */ + class ControlGroup extends AbstractControl { + + controls: StringMap; + + addControl(name: string, c: AbstractControl): void; + + removeControl(name: string): void; + + include(controlName: string): void; + + exclude(controlName: string): void; + + contains(controlName: string): boolean; + } + + + /** + * Defines a part of a form, of variable length, that can contain other controls. + * + * A `ControlArray` aggregates the values and errors of each {@link Control} in the group. Thus, if + * one of the controls + * in a group is invalid, the entire group is invalid. Similarly, if a control changes its value, + * the entire group + * changes as well. + * + * `ControlArray` is one of the three fundamental building blocks used to define forms in Angular, + * along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain + * other controls, but is of fixed length. + */ + class ControlArray extends AbstractControl { + + controls: List; + + at(index: number): AbstractControl; + + push(control: AbstractControl): void; + + insert(index: number, control: AbstractControl): void; + + removeAt(index: number): void; + + length: number; + } + + + /** + * Creates and binds a control with a specified name to a DOM element. + * + * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}. + * + * # Example + * + * In this example, we create the login and password controls. + * We can work with each control separately: check its validity, get its value, listen to its + * changes. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: ` + *
    + * Login + *
    Login is invalid
    + * + * Password + * + * + *
    + * `}) + * class LoginComp { + * onLogIn(value) { + * // value === {login: 'some login', password: 'some password'} + * } + * } + * ``` + * + * We can also use ng-model to bind a domain model to the form. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: ` + *
    + * Login + * Password + * + *
    + * `}) + * class LoginComp { + * credentials: {login:string, password:string}; + * + * onLogIn() { + * // this.credentials.login === "some login" + * // this.credentials.password === "some password" + * } + * } + * ``` + */ + class NgControlName extends NgControl { + + update: void; + + model: any; + + ngValidators: QueryList; + + onChange(c: StringMap): void; + + onDestroy(): void; + + viewToModelUpdate(newValue: any): void; + + path: List; + + formDirective: any; + + control: Control; + + validator: Function; + } + + + /** + * Binds an existing control to a DOM element. + * + * # Example + * + * In this example, we bind the control to an input element. When the value of the input element + * changes, the value of + * the control will reflect that change. Likewise, if the value of the control changes, the input + * element reflects that + * change. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: "" + * }) + * class LoginComp { + * loginControl:Control; + * + * constructor() { + * this.loginControl = new Control(''); + * } + * } + * + * ``` + * + * We can also use ng-model to bind a domain model to the form. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: "" + * }) + * class LoginComp { + * loginControl:Control; + * login:string; + * + * constructor() { + * this.loginControl = new Control(''); + * } + * } + * ``` + */ + class NgFormControl extends NgControl { + + form: Control; + + update: void; + + model: any; + + ngValidators: QueryList; + + onChange(c: any): void; + + path: List; + + control: Control; + + validator: Function; + + viewToModelUpdate(newValue: any): void; + } + + + /** + * Binds a domain model to the form. + * + * # Example + * ``` + * @Component({selector: "search-comp"}) + * @View({ + * directives: [formDirectives], + * template: ` + * + * `}) + * class SearchComp { + * searchQuery: string; + * } + * ``` + */ + class NgModel extends NgControl { + + update: void; + + model: any; + + ngValidators: QueryList; + + onChange(c: any): void; + + control: Control; + + path: List; + + validator: Function; + + viewToModelUpdate(newValue: any): void; + } + + + /** + * An abstract class that all control directive extend. + * + * It binds a {@link Control} object to a DOM element. + */ + class NgControl extends AbstractControlDirective { + + name: string; + + valueAccessor: ControlValueAccessor; + + validator: Function; + + path: List; + + viewToModelUpdate(newValue: any): void; + } + + + /** + * Creates and binds a control group to a DOM element. + * + * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}. + * + * # Example + * + * In this example, we create the credentials and personal control groups. + * We can work with each group separately: check its validity, get its value, listen to its changes. + * + * ``` + * @Component({selector: "signup-comp"}) + * @View({ + * directives: [formDirectives], + * template: ` + *
    + *
    + * Login + * Password + *
    + *
    Credentials are invalid
    + * + *
    + * Name + *
    + * + *
    + * `}) + * class SignupComp { + * onSignUp(value) { + * // value === {personal: {name: 'some name'}, + * // credentials: {login: 'some login', password: 'some password'}} + * } + * } + * + * ``` + */ + class NgControlGroup extends ControlContainer { + + onInit(): void; + + onDestroy(): void; + + control: ControlGroup; + + path: List; + + formDirective: Form; + } + + + /** + * Binds an existing control group to a DOM element. + * + * # Example + * + * In this example, we bind the control group to the form element, and we bind the login and + * password controls to the + * login and password elements. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: "
    " + + * "Login " + + * "Password " + + * "" + + * "
    " + * }) + * class LoginComp { + * loginForm:ControlGroup; + * + * constructor() { + * this.loginForm = new ControlGroup({ + * login: new Control(""), + * password: new Control("") + * }); + * } + * + * onLogin() { + * // this.loginForm.value + * } + * } + * + * ``` + * + * We can also use ng-model to bind a domain model to the form. + * + * ``` + * @Component({selector: "login-comp"}) + * @View({ + * directives: [formDirectives], + * template: "
    " + + * "Login " + + * "Password " + + * "" + + * "
    " + * }) + * class LoginComp { + * credentials:{login:string, password:string} + * loginForm:ControlGroup; + * + * constructor() { + * this.loginForm = new ControlGroup({ + * login: new Control(""), + * password: new Control("") + * }); + * } + * + * onLogin() { + * // this.credentials.login === 'some login' + * // this.credentials.password === 'some password' + * } + * } + * ``` + */ + class NgFormModel extends ControlContainer implements Form { + + form: ControlGroup; + + directives: List; + + ngSubmit: void; + + onChange(_: any): void; + + formDirective: Form; + + control: ControlGroup; + + path: List; + + addControl(dir: NgControl): void; + + getControl(dir: NgControl): Control; + + removeControl(dir: NgControl): void; + + addControlGroup(dir: NgControlGroup): void; + + removeControlGroup(dir: NgControlGroup): void; + + getControlGroup(dir: NgControlGroup): ControlGroup; + + updateModel(dir: NgControl, value: any): void; + + onSubmit(): boolean; + } + + + /** + * Creates and binds a form object to a DOM element. + * + * # Example + * + * ``` + * @Component({selector: "signup-comp"}) + * @View({ + * directives: [formDirectives], + * template: ` + *
    + *
    + * Login + * Password + *
    + *
    Credentials are invalid
    + * + *
    + * Name + *
    + * + *
    + * `}) + * class SignupComp { + * onSignUp(value) { + * // value === {personal: {name: 'some name'}, + * // credentials: {login: 'some login', password: 'some password'}} + * } + * } + * + * ``` + */ + class NgForm extends ControlContainer implements Form { + + form: ControlGroup; + + ngSubmit: void; + + formDirective: Form; + + control: ControlGroup; + + path: List; + + controls: StringMap; + + addControl(dir: NgControl): void; + + getControl(dir: NgControl): Control; + + removeControl(dir: NgControl): void; + + addControlGroup(dir: NgControlGroup): void; + + removeControlGroup(dir: NgControlGroup): void; + + getControlGroup(dir: NgControlGroup): ControlGroup; + + updateModel(dir: NgControl, value: any): void; + + onSubmit(): boolean; + } + + + /** + * A bridge between a control and a native element. + * + * Please see {@link DefaultValueAccessor} for more information. + */ + interface ControlValueAccessor { + + writeValue(obj: any): void; + + registerOnChange(fn: any): void; + + registerOnTouched(fn: any): void; + } + + + /** + * The default accessor for writing a value and listening to changes that is used by the + * {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives. + * + * # Example + * ``` + * + * ``` + */ + class DefaultValueAccessor implements ControlValueAccessor { + + value: string; + + onChange: void; + + onTouched: void; + + cd: NgControl; + + renderer: Renderer; + + elementRef: ElementRef; + + writeValue(value: any): void; + + ngClassUntouched: boolean; + + ngClassTouched: boolean; + + ngClassPristine: boolean; + + ngClassDirty: boolean; + + ngClassValid: boolean; + + ngClassInvalid: boolean; + + registerOnChange(fn: any): void; + + registerOnTouched(fn: any): void; + } + + + /** + * The accessor for writing a value and listening to changes on a checkbox input element. + * + * # Example + * ``` + * + * ``` + */ + class CheckboxControlValueAccessor implements ControlValueAccessor { + + checked: boolean; + + onChange: void; + + onTouched: void; + + cd: NgControl; + + renderer: Renderer; + + elementRef: ElementRef; + + writeValue(value: any): void; + + ngClassUntouched: boolean; + + ngClassTouched: boolean; + + ngClassPristine: boolean; + + ngClassDirty: boolean; + + ngClassValid: boolean; + + ngClassInvalid: boolean; + + registerOnChange(fn: any): void; + + registerOnTouched(fn: any): void; + } + + + /** + * The accessor for writing a value and listening to changes on a select element. + */ + class SelectControlValueAccessor implements ControlValueAccessor { + + value: void; + + onChange: void; + + onTouched: void; + + cd: NgControl; + + renderer: Renderer; + + elementRef: ElementRef; + + writeValue(value: any): void; + + ngClassUntouched: boolean; + + ngClassTouched: boolean; + + ngClassPristine: boolean; + + ngClassDirty: boolean; + + ngClassValid: boolean; + + ngClassInvalid: boolean; + + registerOnChange(fn: any): void; + + registerOnTouched(fn: any): void; + } + + + /** + * A list of all the form directives used as part of a `@View` annotation. + * + * This is a shorthand for importing them each individually. + */ + var formDirectives : List ; + + + /** + * Provides a set of validators used by form controls. + * + * # Example + * + * ``` + * var loginControl = new Control("", Validators.required) + * ``` + */ + class Validators { + } + + class NgValidator { + + validator: Function; + } + + class NgRequiredValidator extends NgValidator { + + validator: Function; + } + + + /** + * Creates a form object from a user-specified configuration. + * + * # Example + * + * ``` + * import {Component, View, bootstrap} from 'angular2/angular2'; + * import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms'; + * + * @Component({ + * selector: 'login-comp', + * viewInjector: [ + * FormBuilder + * ] + * }) + * @View({ + * template: ` + *
    + * Login + * + *
    + * Password + * Confirm password + *
    + *
    + * `, + * directives: [ + * formDirectives + * ] + * }) + * class LoginComp { + * loginForm: ControlGroup; + * + * constructor(builder: FormBuilder) { + * this.loginForm = builder.group({ + * login: ["", Validators.required], + * + * passwordRetry: builder.group({ + * password: ["", Validators.required], + * passwordConfirmation: ["", Validators.required] + * }) + * }); + * } + * } + * + * bootstrap(LoginComp) + * ``` + * + * This example creates a {@link ControlGroup} that consists of a `login` {@link Control}, and a + * nested + * {@link ControlGroup} that defines a `password` and a `passwordConfirmation` {@link Control}: + * + * ``` + * var loginForm = builder.group({ + * login: ["", Validators.required], + * + * passwordRetry: builder.group({ + * password: ["", Validators.required], + * passwordConfirmation: ["", Validators.required] + * }) + * }); + * + * ``` + */ + class FormBuilder { + + group(controlsConfig: StringMap, extra?: StringMap): ControlGroup; + + control(value: Object, validator?: Function): Control; + + array(controlsConfig: List, validator?: Function): ControlArray; + } + + var formInjectables : List ; + + + /** + * A dispatcher for all events happening in a view. + */ + interface EventDispatcher { + + + /** + * Called when an event was triggered for a on-* attribute on an element. + * @param {Map} locals Locals to be used to evaluate the + * event expressions + */ + dispatchEvent(elementIndex: number, eventName: string, locals: Map): void; + } + + class Renderer { + + + /** + * Creates a root host view that includes the given element. + * @param {RenderProtoViewRef} hostProtoViewRef a RenderProtoViewRef of type + * ProtoViewDto.HOST_VIEW_TYPE + * @param {any} hostElementSelector css selector for the host element (will be queried against the + * main document) + * @return {RenderViewRef} the created view + */ + createRootHostView(hostProtoViewRef: RenderProtoViewRef, hostElementSelector: string): RenderViewRef; + + + /** + * Creates a regular view out of the given ProtoView + */ + createView(protoViewRef: RenderProtoViewRef): RenderViewRef; + + + /** + * Destroys the given view after it has been dehydrated and detached + */ + destroyView(viewRef: RenderViewRef): void; + + + /** + * Attaches a componentView into the given hostView at the given element + */ + attachComponentView(location: RenderElementRef, componentViewRef: RenderViewRef): void; + + + /** + * Detaches a componentView into the given hostView at the given element + */ + detachComponentView(location: RenderElementRef, componentViewRef: RenderViewRef): void; + + + /** + * Attaches a view into a ViewContainer (in the given parentView at the given element) at the + * given index. + */ + attachViewInContainer(location: RenderElementRef, atIndex: number, viewRef: RenderViewRef): void; + + + /** + * Detaches a view into a ViewContainer (in the given parentView at the given element) at the + * given index. + */ + detachViewInContainer(location: RenderElementRef, atIndex: number, viewRef: RenderViewRef): void; + + + /** + * Hydrates a view after it has been attached. Hydration/dehydration is used for reusing views + * inside of the view pool. + */ + hydrateView(viewRef: RenderViewRef): void; + + + /** + * Dehydrates a view after it has been attached. Hydration/dehydration is used for reusing views + * inside of the view pool. + */ + dehydrateView(viewRef: RenderViewRef): void; + + + /** + * Returns the native element at the given location. + * Attention: In a WebWorker scenario, this should always return null! + */ + getNativeElementSync(location: RenderElementRef): any; + + + /** + * Sets a property on an element. + */ + setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void; + + + /** + * Sets an attribute on an element. + */ + setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void; + + + /** + * Sets a class on an element. + */ + setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void; + + + /** + * Sets a style on an element. + */ + setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void; + + + /** + * Calls a method on an element. + */ + invokeElementMethod(location: RenderElementRef, methodName: string, args: List): void; + + + /** + * Sets the value of a text node. + */ + setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void; + + + /** + * Sets the dispatcher for all events of the given view + */ + setEventDispatcher(viewRef: RenderViewRef, dispatcher: EventDispatcher): void; + } + + + /** + * Abstract reference to the element which can be marshaled across web-worker boundry. + * + * This interface is used by the {@link Renderer} api. + */ + interface RenderElementRef { + + + /** + * Reference to the {@link RenderViewRef} where the `RenderElementRef` is inside of. + */ + renderView: RenderViewRef; + + + /** + * Index of the element inside the {@link ViewRef}. + * + * This is used internally by the Angular framework to locate elements. + */ + boundElementIndex: number; + } + + class RenderViewRef { + } + + class RenderProtoViewRef { + } + + class DomRenderer extends Renderer { + + createRootHostView(hostProtoViewRef: RenderProtoViewRef, hostElementSelector: string): RenderViewRef; + + createView(protoViewRef: RenderProtoViewRef): RenderViewRef; + + destroyView(view: RenderViewRef): void; + + getNativeElementSync(location: RenderElementRef): any; + + attachComponentView(location: RenderElementRef, componentViewRef: RenderViewRef): void; + + setComponentViewRootNodes(componentViewRef: RenderViewRef, rootNodes: List): void; + + getRootNodes(viewRef: RenderViewRef): List; + + detachComponentView(location: RenderElementRef, componentViewRef: RenderViewRef): void; + + attachViewInContainer(location: RenderElementRef, atIndex: number, viewRef: RenderViewRef): void; + + detachViewInContainer(location: RenderElementRef, atIndex: number, viewRef: RenderViewRef): void; + + hydrateView(viewRef: RenderViewRef): void; + + dehydrateView(viewRef: RenderViewRef): void; + + setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void; + + setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void; + + setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void; + + setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void; + + invokeElementMethod(location: RenderElementRef, methodName: string, args: List): void; + + setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void; + + setEventDispatcher(viewRef: RenderViewRef, dispatcher: any): void; + } + + var DOCUMENT_TOKEN:any; + + + /** + * Declare reusable UI building blocks for an application. + * + * Each Angular component requires a single `@Component` and at least one `@View` annotation. The + * `@Component` + * annotation specifies when a component is instantiated, and which properties and hostListeners it + * binds to. + * + * When a component is instantiated, Angular + * - creates a shadow DOM for the component. + * - loads the selected template into the shadow DOM. + * - creates all the injectable objects configured with `hostInjector` and `viewInjector`. + * + * All template expressions and statements are then evaluated against the component instance. + * + * For details on the `@View` annotation, see {@link View}. + * + * ## Example + * + * ``` + * @Component({ + * selector: 'greet' + * }) + * @View({ + * template: 'Hello {{name}}!' + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + */ + class ComponentAnnotation extends DirectiveAnnotation { + + + /** + * Defines the used change detection strategy. + * + * When a component is instantiated, Angular creates a change detector, which is responsible for + * propagating + * the component's bindings. + * + * The `changeDetection` property defines, whether the change detection will be checked every time + * or only when the component + * tells it to do so. + */ + changeDetection: string; + + + /** + * Defines the set of injectable objects that are visible to its view dom children. + * + * ## Simple Example + * + * Here is an example of a class that can be injected: + * + * ``` + * class Greeter { + * greet(name:string) { + * return 'Hello ' + name + '!'; + * } + * } + * + * @Directive({ + * selector: 'needs-greeter' + * }) + * class NeedsGreeter { + * greeter:Greeter; + * + * constructor(greeter:Greeter) { + * this.greeter = greeter; + * } + * } + * + * @Component({ + * selector: 'greet', + * viewInjector: [ + * Greeter + * ] + * }) + * @View({ + * template: ``, + * directives: [NeedsGreeter] + * }) + * class HelloWorld { + * } + * + * ``` + */ + viewInjector: List; + } + + + /** + * Directives allow you to attach behavior to elements in the DOM. + * + * {@link Directive}s with an embedded view are called {@link Component}s. + * + * A directive consists of a single directive annotation and a controller class. When the + * directive's `selector` matches + * elements in the DOM, the following steps occur: + * + * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor + * arguments. + * 2. Angular instantiates directives for each matched element using `ElementInjector` in a + * depth-first order, + * as declared in the HTML. + * + * ## Understanding How Injection Works + * + * There are three stages of injection resolution. + * - *Pre-existing Injectors*: + * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if + * the dependency was + * specified as `@Optional`, returns `null`. + * - The platform injector resolves browser singleton resources, such as: cookies, title, + * location, and others. + * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow + * the same parent-child hierarchy + * as the component instances in the DOM. + * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each + * element has an `ElementInjector` + * which follow the same parent-child hierarchy as the DOM elements themselves. + * + * When a template is instantiated, it also must instantiate the corresponding directives in a + * depth-first order. The + * current `ElementInjector` resolves the constructor dependencies for each directive. + * + * Angular then resolves dependencies as follows, according to the order in which they appear in the + * {@link View}: + * + * 1. Dependencies on the current element + * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary + * 3. Dependencies on component injectors and their parents until it encounters the root component + * 4. Dependencies on pre-existing injectors + * + * + * The `ElementInjector` can inject other directives, element-specific special objects, or it can + * delegate to the parent + * injector. + * + * To inject other directives, declare the constructor parameter as: + * - `directive:DirectiveType`: a directive on the current element only + * - `@Ancestor() directive:DirectiveType`: any directive that matches the type between the current + * element and the + * Shadow DOM root. Current element is not included in the resolution, therefore even if it could + * resolve it, it will + * be ignored. + * - `@Parent() directive:DirectiveType`: any directive that matches the type on a direct parent + * element only. + * - `@Query(DirectiveType) query:QueryList`: A live collection of direct child + * directives. + * - `@QueryDescendants(DirectiveType) query:QueryList`: A live collection of any + * child directives. + * + * To inject element-specific special objects, declare the constructor parameter as: + * - `element: ElementRef` to obtain a reference to logical element in the view. + * - `viewContainer: ViewContainerRef` to control child template instantiation, for + * {@link Directive} directives only + * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way. + * + * ## Example + * + * The following example demonstrates how dependency injection resolves constructor arguments in + * practice. + * + * + * Assume this HTML template: + * + * ``` + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + * ``` + * + * With the following `dependency` decorator and `SomeService` injectable class. + * + * ``` + * @Injectable() + * class SomeService { + * } + * + * @Directive({ + * selector: '[dependency]', + * properties: [ + * 'id: dependency' + * ] + * }) + * class Dependency { + * id:string; + * } + * ``` + * + * Let's step through the different ways in which `MyDirective` could be declared... + * + * + * ### No injection + * + * Here the constructor is declared with no arguments, therefore nothing is injected into + * `MyDirective`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor() { + * } + * } + * ``` + * + * This directive would be instantiated with no dependencies. + * + * + * ### Component-level injection + * + * Directives can inject any injectable instance from the closest component injector or any of its + * parents. + * + * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type + * from the parent + * component's injector. + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(someService: SomeService) { + * } + * } + * ``` + * + * This directive would be instantiated with a dependency on `SomeService`. + * + * + * ### Injecting a directive from the current element + * + * Directives can inject other directives declared on the current element. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(dependency: Dependency) { + * expect(dependency.id).toEqual(3); + * } + * } + * ``` + * This directive would be instantiated with `Dependency` declared at the same element, in this case + * `dependency="3"`. + * + * + * ### Injecting a directive from a direct parent element + * + * Directives can inject other directives declared on a direct parent element. By definition, a + * directive with a + * `@Parent` annotation does not attempt to resolve dependencies for the current element, even if + * this would satisfy + * the dependency. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Parent() dependency: Dependency) { + * expect(dependency.id).toEqual(2); + * } + * } + * ``` + * This directive would be instantiated with `Dependency` declared at the parent element, in this + * case `dependency="2"`. + * + * + * ### Injecting a directive from any ancestor elements + * + * Directives can inject other directives declared on any ancestor element (in the current Shadow + * DOM), i.e. on the + * parent element and its parents. By definition, a directive with an `@Ancestor` annotation does + * not attempt to + * resolve dependencies for the current element, even if this would satisfy the dependency. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Ancestor() dependency: Dependency) { + * expect(dependency.id).toEqual(2); + * } + * } + * ``` + * + * Unlike the `@Parent` which only checks the parent, `@Ancestor` checks the parent, as well as its + * parents recursively. If `dependency="2"` didn't exist on the direct parent, this injection would + * have returned + * `dependency="1"`. + * + * + * ### Injecting a live collection of direct child directives + * + * + * A directive can also query for other child directives. Since parent directives are instantiated + * before child directives, a directive can't simply inject the list of child directives. Instead, + * the directive injects a {@link QueryList}, which updates its contents as children are added, + * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ng-for`, an + * `ng-if`, or an `ng-switch`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and + * 6. Here, `Dependency` 5 would not be included, because it is not a direct child. + * + * ### Injecting a live collection of descendant directives + * + * By passing the descendant flag to `@Query` above, we can include the children of the child + * elements. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6. + * + * ### Optional injection + * + * The normal behavior of directives is to return an error when a specified dependency cannot be + * resolved. If you + * would like to inject `null` on unresolved dependency instead, you can annotate that dependency + * with `@Optional()`. + * This explicitly permits the author of a template to treat some of the surrounding directives as + * optional. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Optional() dependency:Dependency) { + * } + * } + * ``` + * + * This directive would be instantiated with a `Dependency` directive found on the current element. + * If none can be + * found, the injector supplies `null` instead of throwing an error. + * + * ## Example + * + * Here we use a decorator directive to simply define basic tool-tip behavior. + * + * ``` + * @Directive({ + * selector: '[tooltip]', + * properties: [ + * 'text: tooltip' + * ], + * hostListeners: { + * 'onmouseenter': 'onMouseEnter()', + * 'onmouseleave': 'onMouseLeave()' + * } + * }) + * class Tooltip{ + * text:string; + * overlay:Overlay; // NOT YET IMPLEMENTED + * overlayManager:OverlayManager; // NOT YET IMPLEMENTED + * + * constructor(overlayManager:OverlayManager) { + * this.overlay = overlay; + * } + * + * onMouseEnter() { + * // exact signature to be determined + * this.overlay = this.overlayManager.open(text, ...); + * } + * + * onMouseLeave() { + * this.overlay.close(); + * this.overlay = null; + * } + * } + * ``` + * In our HTML template, we can then add this behavior to a `
    ` or any other element with the + * `tooltip` selector, + * like so: + * + * ``` + *
    + * ``` + * + * Directives can also control the instantiation, destruction, and positioning of inline template + * elements: + * + * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at + * runtime. + * The {@link ViewContainerRef} is created as a result of `