merge upstream master

This commit is contained in:
Nicolas Laplante
2017-03-30 19:36:21 -04:00
950 changed files with 105406 additions and 11877 deletions

View File

@@ -1,19 +1,17 @@
Please fill in this template.
- [ ] Make your PR against the `master` branch.
- [ ] Use a meaningful title for the pull request. Include the name of the package modified.
- [ ] Test the change in your own code. (Compile and run.)
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes).
- [ ] Run `tsc` without errors.
- [ ] Run `npm run lint package-name` if a `tslint.json` is present.
- [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present).
Select one of these and delete the others:
If adding a new definition:
- [ ] The package does not provide its own types, and you can not add them.
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `npm run new-package package-name`, not by basing it on an existing project.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, and `strictNullChecks` set to `true`.
If changing an existing definition:

View File

@@ -110,15 +110,14 @@ Your package should have this structure:
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |
Generate these by running `npm run new-package -- --name my-package-name --template module`.
(Other templates are `module-class`, `module-function`, `module-plugin`, `global`, `global-plugin`, and `global-modifying-module`.
This just wraps [dts-gen](https://github.com/Microsoft/dts-gen), so it supports all options from that.)
Generate these by running `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module`.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.
DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/base64-js).
For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Common mistakes
@@ -167,9 +166,11 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet.
}
```
(To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.)
(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)
Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).
Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint.
## FAQ
@@ -191,7 +192,7 @@ If you're adding a new major version of a library, you can copy `index.d.ts` to
#### I notice some packages having a `package.json` here.
Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it.
A `package.json` may be included for the sake of specifying dependencies. Here's an [example](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/pikaday/package.json).
A `package.json` may be included for the sake of specifying dependencies. Here's an [example](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
We do not allow other fields, such as `"description"`, to be defined manually.
Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json.
@@ -231,7 +232,7 @@ Before making your change, please create a new subfolder with the current versio
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/history/v2/tsconfig.json) looks like:
For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
```json
{
@@ -250,8 +251,8 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
```
Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react-router-bootstrap/tsconfig.json).
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.

View File

@@ -16,13 +16,12 @@
},
"scripts": {
"compile-scripts": "tsc -p scripts",
"new-package": "dts-gen --dt",
"not-needed": "node scripts/not-needed.js",
"lint": "node scripts/lint.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1"
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1",
"lint": "dtslint --dt types"
},
"devDependencies": {
"types-publisher": "Microsoft/types-publisher#production",
"dts-gen": "latest"
"dtslint": "Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
}

View File

@@ -1,25 +0,0 @@
// Usage: npm run lint -- my-package-name
const pkg = process.argv[2];
const execSync = require("child_process").execSync;
const existsSync = require("fs").existsSync;
const path = require("path");
const pkgPath = path.join("types", pkg);
// Path of tslint when `types-publisher` is symlinked
const symlinkedTslintPath = "../../node_modules/types-publisher/node_modules/tslint"
let tslintPath = existsSync(path.join(pkgPath, symlinkedTslintPath)) ? symlinkedTslintPath : "../node_modules/tslint";
// An older version (e.g. abs/v0) is in a nested directory, so needs to look one more level up for tslint.
if (pkg.includes("/") && pkg[pkg.length - 1] !== "/") {
tslintPath = path.join("..", tslintPath);
}
const cmd = `node ${tslintPath}/lib/tslint-cli --format stylish "**/*.ts"`;
console.log(cmd);
try {
// Child process writes directly to our own stdout
execSync(cmd, { cwd: pkgPath, stdio: "inherit" });
} catch (_) {
// Process should have printed out error info
}

View File

@@ -1,6 +1,6 @@
import * as Ably from 'ably';
declare var console: { log(message: any): void };
declare const console: { log(message: any): void };
const ApiKey = 'appId.keyId:secret';
const client = new Ably.Realtime(ApiKey);
@@ -19,10 +19,9 @@ client.connection.on('failed', () => {
// failed connection
});
// Subscribing to a channel
var channel = client.channels.get('test');
const channel = client.channels.get('test');
channel.subscribe(message => {
message.name; // 'greeting'
message.data; // 'Hello World!'
@@ -68,7 +67,6 @@ channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direct
console.log(messagesPage.items.length);
});
// Presence on a channel
// Getting presence:
@@ -118,7 +116,7 @@ channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direct
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
Ably.Realtime.Crypto.generateRandomKey((err, key) => {
var channel = client.channels.get('channelName', { cipher: { key } });
const channel = client.channels.get('channelName', { cipher: { key } });
channel.subscribe(message => {
message.name; // 'name is not encrypted'
@@ -136,7 +134,7 @@ channel.setOptions({cipher: {key: '<KEY>'}}, () => {
// Using the REST API
var restChannel = restClient.channels.get('test');
const restChannel = restClient.channels.get('test');
// Publishing to a channel
@@ -195,7 +193,6 @@ restChannel.presence.history((err, messagesPage) => { // PaginatedResult
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Generate Token and Token Request
// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism.
@@ -206,7 +203,7 @@ client.auth.requestToken((err, tokenDetails) => {
// see https://www.ably.io/documentation/rest/authentication/#token-details for its properties
// Now we have the token, we can send it to someone who can instantiate a client with it:
var clientUsingToken = new Ably.Realtime(tokenDetails.token);
const clientUsingToken = new Ably.Realtime(tokenDetails.token);
});
// requestToken can take two optional params
@@ -242,15 +239,15 @@ client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as Paginat
client.time({}, (err, time) => {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
console.log(messages[0].id);
var message = Ably.Rest.Message.fromEncoded({ id: 'foo' });
const message = Ably.Rest.Message.fromEncoded({ id: 'foo' });
console.log(message.id);
// Getting decoded PresenceMessage objects from JSON
var presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]);
const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]);
console.log(presenceMessages[0].action);
var presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
console.log(presenceMessage.action);

16
types/ably/index.d.ts vendored
View File

@@ -3,7 +3,7 @@
// Definitions by: Ably <https://github.com/ably/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ablyLib {
export namespace ablyLib {
namespace ChannelState {
type INITIALIZED = 'initialized';
type ATTACHING = 'attaching';
@@ -130,15 +130,15 @@ declare namespace ablyLib {
* A function which is called when a new token is required.
* The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically
* by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object.
**/
authCallback?: (data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void) => void;
*/
authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void;
authHeaders?: { [index: string]: string };
authMethod?: HTTPMethods;
authParams?: { [index: string]: string };
/**
* A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format).
**/
*/
authUrl?: string;
key?: string;
queryTime?: boolean;
@@ -259,13 +259,13 @@ declare namespace ablyLib {
/**
* A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only),
* 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
**/
*/
level?: number;
/**
* A function to handle each line of log output. If handler is not specified, console.log is used.
**/
handler?: (...args: any[]) => void;
*/
handler?(...args: any[]): void;
}
interface ChannelEvent {
@@ -398,7 +398,7 @@ declare namespace ablyLib {
}
interface Crypto {
generateRandomKey: (callback: (error: ErrorInfo, key: string) => void) => void;
generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void;
}
class Connection extends EventEmitter<connectionEventCallback> {

View File

@@ -27,8 +27,6 @@ accounting.formatMoney(5318008, {
// Will recursively format an array of values:
accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]
// formatColumn
// Format list of numbers for display:
@@ -40,8 +38,6 @@ accounting.formatColumn([123, 12345], "$ ", 0); // ["$ 123", "$ 12,345"]
// List of numbers can be a multi-dimensional array (formatColumn is applied recursively):
accounting.formatColumn([[1, 100], [900, 9]]); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]]
// formatNumber
// Example usage:
@@ -58,16 +54,11 @@ accounting.formatNumber(5318008, {
// Will recursively format an array of values:
accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]]
// toFixed
(0.615).toFixed(2); // "0.61"
accounting.toFixed(0.615, 2); // "0.62"
// unformat
// Example usage:

View File

@@ -1,4 +1,4 @@
// Type definitions for ADAL.JS 1.0.13
// Type definitions for ADAL.JS 1.0.14
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js
// Definitions by: mmaitre314 <https://github.com/mmaitre314>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -29,6 +29,7 @@ declare namespace adal {
loginResource?: string;
resource?: string;
extraQueryParameter?: string;
navigateToLoginRequestUrl?: boolean;
}
interface User {

View File

@@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -16,7 +16,6 @@ amplify.subscribe("dataexample", data => {
alert(data.foo); // bar
});
amplify.publish("dataexample", { foo: "bar" });
amplify.subscribe("dataexample2", (param1, param2) => {
@@ -47,7 +46,6 @@ amplify.subscribe("priorityexample", data => {
}
}, 1);
// Store data with amplify storage picking the default storage technology:
amplify.publish("priorityexample", { foo: "bar" });
@@ -56,9 +54,9 @@ amplify.publish("priorityexample", { foo: "oops" });
amplify.store("storeExample1", { foo: "bar" });
amplify.store("storeExample2", "baz");
// retrieve the data later via the key
var myStoredValue = amplify.store("storeExample1"),
myStoredValue2 = amplify.store("storeExample2"),
myStoredValues = amplify.store();
const myStoredValue = amplify.store("storeExample1");
let myStoredValue2 = amplify.store("storeExample2");
const myStoredValues = amplify.store();
myStoredValue.foo; // bar
myStoredValue2; // baz
myStoredValues.storeExample1.foo; // bar
@@ -68,15 +66,13 @@ myStoredValues.storeExample2; // baz
amplify.store.sessionStorage("explicitExample", { foo2: "baz" });
// retrieve the data later via the key
var myStoredValue2 = amplify.store.sessionStorage("explicitExample");
myStoredValue2 = amplify.store.sessionStorage("explicitExample");
myStoredValue2.foo2; // baz
// REQUEST
// Set up and use a request utilizing Ajax
amplify.request.define("ajaxExample1", "ajax", {
url: "/myApiUrl",
dataType: "json",
@@ -159,15 +155,11 @@ amplify.request("twitter-search", { term: "amplifyjs" } );
// Similarly, we can create a request that searches for mentions, by accepting a username:
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: data => {
return {
q: "@" + data.user
};
}
});
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: data => ({ q: "@" + data.user }),
});
amplify.request("twitter-mentions", { user: "amplifyjs" });
@@ -175,7 +167,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" });
// Example:
var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => {
const appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
@@ -197,7 +189,6 @@ amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
// but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
@@ -246,11 +237,11 @@ amplify.request({
// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition.
amplify.request.define("statusExample1", "ajax", {
// ...
});
amplify.request.define("statusExample1", "ajax", {
// ...
});
amplify.request({
amplify.request({
resourceId: "statusExample1",
success: (data, status) => {
},

View File

@@ -9,8 +9,8 @@ declare namespace amplify {
interface RequestSettings {
resourceId: string;
data?: any;
success?: (...args: any[]) => void;
error?: (...args: any[]) => void;
success?(...args: any[]): void;
error?(...args: any[]): void;
}
type Decoder =

View File

@@ -1,7 +1,7 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false,
"ban-types": false,
"unified-signatures": false
}
}

View File

@@ -1,7 +1,7 @@
// promise api tests
import amqp = require('amqplib');
var msg = 'Hello World';
const msg = 'Hello World';
// test promise api
amqp.connect('amqp://localhost')
@@ -21,11 +21,10 @@ amqp.connect('amqp://localhost')
});
// test promise api properties
var amqpMessage: amqp.Message;
let amqpMessage: amqp.Message;
amqpMessage.properties.contentType = 'application/json';
var amqpAssertExchangeOptions: amqp.Options.AssertExchange;
var anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
let amqpAssertExchangeOptions: amqp.Options.AssertExchange;
let anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
// callback api tests
import amqpcb = require('amqplib/callback_api');
@@ -59,7 +58,7 @@ amqpcb.connect('amqp://localhost', (err, connection) => {
});
// test callback api properties
var amqpcbMessage: amqpcb.Message;
let amqpcbMessage: amqpcb.Message;
amqpcbMessage.properties.contentType = 'application/json';
var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange;
var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;
let amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange;
let anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;

View File

@@ -30,6 +30,7 @@ class FormConfig {
formlyConfig.extras.errorExistsAndShouldBeVisibleExpression = angular.noop;
formlyConfig.extras.explicitAsync = true;
formlyConfig.extras.fieldTransform = angular.noop;
formlyConfig.extras.fieldTransform = [angular.noop];
formlyConfig.extras.getFieldId = angular.noop;
formlyConfig.extras.ngModelAttrsManipulatorPreferUnbound = true;
}

View File

@@ -1,4 +1,4 @@
// Type definitions for angular-formly 7.2.3
// Type definitions for angular-formly 7.2.4
// Project: https://github.com/formly-js/angular-formly
// Definitions by: Scott Hatcher <https://github.com/scatcher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -44,7 +44,7 @@ declare namespace AngularFormly {
data?: {
[key: string]: any;
};
fieldTransform?: Function;
fieldTransform?: Function | Array<Function>;
formState?: Object;
removeChromeAutoComplete?: boolean;
resetModel?: Function;
@@ -580,7 +580,7 @@ declare namespace AngularFormly {
defaultHideDirective: string;
errorExistsAndShouldBeVisibleExpression: any;
getFieldId: Function;
fieldTransform: Function;
fieldTransform: Function | Array<Function>;
explicitAsync: boolean;
}

View File

@@ -3,11 +3,10 @@ import * as angular from "angular";
import gridster from "angular-gridster";
var myApp = angular.module("testModule", ["gridster"]);
const myApp = angular.module("testModule", ["gridster"]);
// configure gridster's global options
myApp.run(["gridsterConfig", (gridsterConfig: angular.gridster.GridsterConfig) => {
gridsterConfig.mobileBreakPoint = 697;
gridsterConfig.colWidth = "100";
gridsterConfig.rowHeight = "100";
@@ -24,4 +23,4 @@ myApp.run(["gridsterConfig", (gridsterConfig: angular.gridster.GridsterConfig) =
gridsterConfig.resizable = { enabled: true,
handles: ["n", "s", "e", "w", "ne", "se", "sw", "nw"]};
}
]);
]);

View File

@@ -7,4 +7,4 @@ angular.module('angular-oauth2-test', ['angular-oauth2'])
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET' // optional
});
}]);
}]);

View File

@@ -62,7 +62,6 @@ angular.module('http-auth-interceptor', [])
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
*/
.config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => {
$httpProvider.defaults.headers.common = {Authorization: 'Bearer token'};
$httpProvider.defaults.headers.get['Authorization'] = 'Bearer token';
$httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token';
@@ -108,7 +107,7 @@ namespace HttpAndRegularPromiseTests {
$http.get<ExpectedResponse>('http://somewhere/some/resource')
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
// const i: number = response.data
// would type check
$scope.person = response.data;
});
@@ -116,7 +115,7 @@ namespace HttpAndRegularPromiseTests {
$http.get<ExpectedResponse>('http://somewhere/some/resource')
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
// const i: number = response.data
// would NOT type check
$scope.person = response.data;
});
@@ -153,7 +152,13 @@ namespace HttpAndRegularPromiseTests {
// Test for AngularJS Syntax
namespace My.Namespace {
export var x: any; // need to export something for module to kick in
export const x: any = null; // need to export something for module to kick in
}
class TestProvider implements ng.IServiceProvider {
constructor(private $scope: ng.IScope) {}
$get() {}
}
// IModule Registering Test
@@ -229,14 +234,6 @@ mod.value(My.Namespace);
mod.decorator('name', ($scope: ng.IScope) => {});
mod.decorator('name', ['$scope', ($scope: ng.IScope) => {}]);
class TestProvider implements ng.IServiceProvider {
constructor(private $scope: ng.IScope) {
}
$get() {
}
}
// QProvider tests
angular.module('qprovider-test', [])
.config(['$qProvider', ($qProvider: ng.IQProvider) => {
@@ -276,8 +273,8 @@ foo.then((x) => {
// Object is inferred here
x.a = 123;
// Try a promise
var y: ng.IPromise<number>;
var condition: boolean;
const y: ng.IPromise<number> = null;
const condition: boolean = null;
return condition ? y : x.a; // IPromise<T> | T, both are good for the 1st arg of .then()
}).then((x) => {
// x is infered to be a number, which is the resolved value of a promise
@@ -299,15 +296,15 @@ namespace TestQ {
g: string;
h: number;
}
var tResult: TResult;
var promiseTResult: angular.IPromise<TResult>;
var tValue: TValue;
var promiseTValue: angular.IPromise<TValue>;
var tOther: TOther;
var promiseTOther: angular.IPromise<TOther>;
const tResult: TResult = null;
const promiseTResult: angular.IPromise<TResult> = null;
const tValue: TValue = null;
const promiseTValue: angular.IPromise<TValue> = null;
const tOther: TOther = null;
const promiseTOther: angular.IPromise<TOther> = null;
var $q: angular.IQService;
var promiseAny: angular.IPromise<any>;
const $q: angular.IQService = null;
const promiseAny: angular.IPromise<any> = null;
const assertPromiseType = <T>(arg: angular.IPromise<T>) => arg;
@@ -346,7 +343,7 @@ namespace TestQ {
let result: angular.IDeferred<TResult>;
result = $q.defer<TResult>();
result.resolve(tResult);
var anyValue: any;
const anyValue: any = null;
result.reject(anyValue);
result.promise.then(result => {
return $q.resolve<TResult>(result);
@@ -411,7 +408,7 @@ namespace TestQ {
let httpFoo: ng.IHttpPromise<number>;
httpFoo.then((x) => {
// When returning a promise the generic type must be inferred.
var innerPromise: ng.IPromise<number>;
const innerPromise: ng.IPromise<number> = null;
return innerPromise;
}).then((x) => {
// must still be number.
@@ -427,16 +424,16 @@ httpFoo.then((response: ng.IHttpPromiseCallbackArg<any>) => {
// Deferred signature tests
namespace TestDeferred {
var any: any;
const any: any = null;
interface TResult {
a: number;
b: string;
c: boolean;
}
var tResult: TResult;
const tResult: TResult = null;
var deferred: angular.IDeferred<TResult>;
const deferred: angular.IDeferred<TResult> = null;
// deferred.resolve
{
@@ -467,7 +464,7 @@ namespace TestDeferred {
}
namespace TestInjector {
var $injector: angular.auto.IInjectorService;
const $injector: angular.auto.IInjectorService = null;
$injector.strictDi = true;
@@ -477,7 +474,7 @@ namespace TestInjector {
// Promise signature tests
namespace TestPromise {
var any: any;
const any: any = null;
interface TResult {
kind: 'result';
@@ -497,16 +494,16 @@ namespace TestPromise {
return x.kind === 'result';
}
var tresult: TResult;
var tresultPromise: ng.IPromise<TResult>;
var tresultHttpPromise: ng.IHttpPromise<TResult>;
const tresult: TResult = null;
const tresultPromise: ng.IPromise<TResult> = null;
const tresultHttpPromise: ng.IHttpPromise<TResult> = null;
var tother: TOther;
var totherPromise: ng.IPromise<TOther>;
var totherHttpPromise: ng.IHttpPromise<TOther>;
const tother: TOther = null;
const totherPromise: ng.IPromise<TOther> = null;
const totherHttpPromise: ng.IHttpPromise<TOther> = null;
var promise: angular.IPromise<TResult>;
var $q: angular.IQService;
const promise: angular.IPromise<TResult> = null;
const $q: angular.IQService = null;
const assertPromiseType = <T>(arg: angular.IPromise<T>) => arg;
const reject = $q.reject();
@@ -608,9 +605,9 @@ namespace TestTimeout {
b: string;
c: boolean;
}
var fnTResult: (...args: any[]) => TResult;
var promiseAny: angular.IPromise<any>;
var $timeout: angular.ITimeoutService;
const fnTResult: (...args: any[]) => TResult = null;
const promiseAny: angular.IPromise<any> = null;
const $timeout: angular.ITimeoutService = null;
// $timeout
{
@@ -670,9 +667,7 @@ class SampleDirective implements ng.IDirective {
return new SampleDirective();
}
link(scope: ng.IScope) {
}
link(scope: ng.IScope) {}
}
class SampleDirective2 implements ng.IDirective {
@@ -688,9 +683,7 @@ class SampleDirective2 implements ng.IDirective {
return new SampleDirective2();
}
link(scope: ng.IScope) {
}
link(scope: ng.IScope) {}
}
angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance);
@@ -825,11 +818,10 @@ angular.module('docsTimeDirective', [])
$scope.format = 'M/d/yy h:mm:ss a';
}])
.directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => {
return {
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
let format: any,
timeoutId: any;
let format: any;
let timeoutId: any;
function updateTime() {
element.text(dateFilter(new Date(), format));
@@ -904,7 +896,10 @@ angular.module('docsIsoFnBindExample', [])
angular.module('dragModule', [])
.directive('myDraggable', ['$document', ($document: any) => {
return (scope: any, element: any, attr: any) => {
let startX = 0, startY = 0, x = 0, y = 0;
let startX = 0;
let startY = 0;
let x = 0;
let y = 0;
element.css({
position: 'relative',
@@ -1030,11 +1025,10 @@ interface ICopyExampleUser {
}
interface ICopyExampleScope {
user: ICopyExampleUser;
master: ICopyExampleUser;
update: (copyExampleUser: ICopyExampleUser) => any;
reset: () => any;
update(copyExampleUser: ICopyExampleUser): any;
reset(): any;
}
angular.module('copyExample', [])
@@ -1055,8 +1049,7 @@ angular.module('copyExample', [])
}]);
namespace locationTests {
var $location: ng.ILocationService;
const $location: ng.ILocationService = null;
/*
* From https://docs.angularjs.org/api/ng/service/$location
@@ -1114,9 +1107,9 @@ namespace locationTests {
// NgModelController
function NgModelControllerTyping() {
var ngModel: angular.INgModelController;
var $http: angular.IHttpService;
var $q: angular.IQService;
const ngModel: angular.INgModelController = null;
const $http: angular.IHttpService = null;
const $q: angular.IQService = null;
// See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators
ngModel.$validators['validCharacters'] = (modelValue, viewValue) => {
@@ -1141,8 +1134,7 @@ function NgModelControllerTyping() {
let $filter: angular.IFilterService;
function testFilter() {
var items: string[];
const items: string[] = null;
$filter('filter')(items, 'test');
$filter('filter')(items, {name: 'test'});
$filter('filter')(items, (val, index, array) => {
@@ -1224,7 +1216,7 @@ function testCustomFilter() {
}
function parseTyping() {
var $parse: angular.IParseService;
const $parse: angular.IParseService = null;
const compiledExp = $parse('a.b.c');
if (compiledExp.constant) {
return compiledExp({});
@@ -1234,7 +1226,7 @@ function parseTyping() {
}
function parseWithParams() {
var $parse: angular.IParseService;
const $parse: angular.IParseService = null;
const compiledExp1 = $parse('a.b.c', () => null);
const compiledExp2 = $parse('a.b.c', null, false);
}
@@ -1255,7 +1247,7 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector
}
function testIHttpParamSerializerJQLikeProvider() {
var serializer: angular.IHttpParamSerializer;
const serializer: angular.IHttpParamSerializer = null;
serializer({
a: 'b'
});
@@ -1271,6 +1263,6 @@ function anyOf3<T1, T2, T3>(v1: T1, v2: T2, v3: T3) {
}
function toPromise<T>(val: T): ng.IPromise<T> {
var p: ng.IPromise<T>;
const p: ng.IPromise<T> = null;
return p;
}

View File

@@ -413,7 +413,7 @@ declare namespace angular {
// https://docs.angularjs.org/api/ng/directive/ngModelOptions
interface INgModelOptions {
updateOn?: string;
debounce?: any;
debounce?: number | { [key: string]: number; };
allowInvalid?: boolean;
getterSetter?: boolean;
timezone?: string;
@@ -602,7 +602,7 @@ declare namespace angular {
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
(delay?: number, invokeApply?: boolean): IPromise<void>;
<T>(fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise<T>;
<T>(fn: (...args: any[]) => T | IPromise<T>, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise<T>;
cancel(promise?: IPromise<any>): boolean;
}
@@ -782,7 +782,7 @@ declare namespace angular {
// Check angular's i18n files for exemples
NUMBER_FORMATS: ILocaleNumberFormatDescriptor;
DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor;
pluralCat: (num: any) => string;
pluralCat(num: any): string;
}
interface ILocaleNumberFormatDescriptor {
@@ -875,7 +875,8 @@ declare namespace angular {
* @param identifierStart The function that will decide whether the given character is a valid identifier start character.
* @param identifierContinue The function that will decide whether the given character is a valid identifier continue character.
**/
setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean,
setIdentifierFns(
identifierStart?: (character: string, codePoint: number) => boolean,
identifierContinue?: (character: string, codePoint: number) => boolean): void;
}
@@ -1591,10 +1592,10 @@ declare namespace angular {
}
interface IHttpInterceptor {
request?: (config: IRequestConfig) => IRequestConfig|IPromise<IRequestConfig>;
requestError?: (rejection: any) => any;
response?: <T>(response: IHttpPromiseCallbackArg<T>) => IPromise<IHttpPromiseCallbackArg<T>>|IHttpPromiseCallbackArg<T>;
responseError?: (rejection: any) => any;
request?(config: IRequestConfig): IRequestConfig|IPromise<IRequestConfig>;
requestError?(rejection: any): any;
response?<T>(response: IHttpPromiseCallbackArg<T>): IPromise<IHttpPromiseCallbackArg<T>>|IHttpPromiseCallbackArg<T>;
responseError?(rejection: any): any;
}
interface IHttpInterceptorFactory {
@@ -2025,7 +2026,6 @@ declare namespace angular {
service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider;
value(name: string, value: any): IServiceProvider;
}
}
/**

View File

@@ -2,32 +2,18 @@
"extends": "../tslint.json",
"rules": {
"class-name": true,
"curly": true,
"max-line-length": false,
"no-consecutive-blank-lines": true,
"no-shadowed-variable": true,
"quotemark": [
true,
"single"
],
"align": true,
"indent": [true, "spaces"],
"quotemark": [true, "single"],
"variable-name": [true, "check-format"],
// Below are all TODOs
"callable-types": false,
"forbidden-types": false,
"indent": [
true,
"spaces"
],
"ban-types": false,
"interface-name": false,
"linebreak-style": [
true,
"LF"
],
"jsdoc-format": false,
"max-line-length": false,
"no-empty-interface": false,
"unified-signatures": false,
"variable-name": [
true,
"check-format"
],
"void-return": false
}
}

View File

@@ -0,0 +1,269 @@
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
declare function describe(desc: string, fn: () => void): void;
declare function it(desc: string, fn: () => void): void;
describe("ApplePaySession", () => {
it("the constants are defined", () => {
let status = 0;
switch (status) {
case ApplePaySession.STATUS_FAILURE:
case ApplePaySession.STATUS_INVALID_BILLING_POSTAL_ADDRESS:
case ApplePaySession.STATUS_INVALID_SHIPPING_CONTACT:
case ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:
case ApplePaySession.STATUS_PIN_INCORRECT:
case ApplePaySession.STATUS_PIN_LOCKOUT:
case ApplePaySession.STATUS_PIN_REQUIRED:
case ApplePaySession.STATUS_SUCCESS:
default:
break;
}
});
it("can create a new instance", () => {
const version = 1;
const paymentRequest = {
countryCode: "US",
currencyCode: "USD",
supportedNetworks: [
"masterCard",
"visa"
],
merchantCapabilities: [
"supports3DS"
],
total: {
label: "My Store",
amount: "9.99"
}
};
const session = new ApplePaySession(version, paymentRequest);
});
it("can call static methods", () => {
const merchantIdentifier = "MyMerchantId";
let canMakePayments: boolean = ApplePaySession.canMakePayments();
let supported: boolean = ApplePaySession.supportsVersion(2);
ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier)
.then((status: boolean) => {
console.log(`Can make payments with active card: ${status}.`);
});
ApplePaySession.openPaymentSetup(merchantIdentifier)
.then((success) => {
console.log(`Apple Pay setup: ${success}.`);
});
});
it("can call instance methods", () => {
const version = 1;
const paymentRequest = {
countryCode: "US",
currencyCode: "USD",
supportedNetworks: [
"masterCard",
"visa"
],
merchantCapabilities: [
"supports3DS"
],
total: {
label: "My Store",
amount: "9.99"
}
};
const session = new ApplePaySession(version, paymentRequest);
session.abort();
session.completeMerchantValidation({
foo: "bar"
});
session.completePayment(ApplePaySession.STATUS_SUCCESS);
const total = {
label: "Subtotal",
type: "final",
amount: "35.00"
};
const lineItems = [
{
label: "Subtotal",
type: "final",
amount: "35.00"
},
{
label: "Free Shipping",
amount: "0.00",
type: "pending"
},
{
label: "Estimated Tax",
amount: "3.06"
}
];
const shippingMethods = [
{
label: "Free Shipping",
detail: "Arrives in 5 to 7 days",
amount: "0.00",
identifier: "FreeShipping"
},
{
label: "2-hour Shipping",
amount: "5.00"
}
];
session.completePaymentMethodSelection(total, lineItems);
session.completeShippingContactSelection(
ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
shippingMethods,
total,
lineItems);
session.completeShippingMethodSelection(
ApplePaySession.STATUS_SUCCESS,
total,
lineItems);
session.oncancel = (event: ApplePayJS.Event): void => {
event.cancelBubble = true;
};
session.onpaymentauthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => {
if (event.payment) {
console.log("Payment data:", JSON.stringify(event.payment));
}
};
session.onpaymentmethodselected = (event: ApplePayJS.ApplePayPaymentMethodSelectedEvent) => {
if (event.paymentMethod) {
console.log("Payment method:", JSON.stringify(event.paymentMethod));
}
};
session.onshippingcontactselected = (event: ApplePayJS.ApplePayShippingContactSelectedEvent) => {
if (event.shippingContact) {
console.log("Shipping contact:", JSON.stringify(event.shippingContact));
}
};
session.onshippingmethodselected = (event: ApplePayJS.ApplePayShippingMethodSelectedEvent) => {
if (event.shippingMethod) {
console.log("Shipping method:", JSON.stringify(event.shippingMethod));
}
};
session.onvalidatemerchant = (event: ApplePayJS.ApplePayValidateMerchantEvent) => {
if (event.validationURL) {
console.log(`The validation URL is '${event.validationURL}'.`);
}
};
});
});
describe("ApplePayPaymentRequest", () => {
it("can create a new instance", () => {
let paymentRequest: ApplePayJS.ApplePayPaymentRequest = {
applicationData: "ApplicationData",
countryCode: "GB",
currencyCode: "GBP",
merchantCapabilities: [
"supports3DS",
"supportsCredit",
"supportsDebit"
],
supportedNetworks: [
"amex",
"discover",
"jcb",
"masterCard",
"privateLabel",
"visa"
],
total: {
label: "Apple",
type: "final",
amount: "9.99"
}
};
paymentRequest.billingContact = {
emailAddress: "ravipatel@example.com",
familyName: "Patel",
givenName: "Ravi",
phoneNumber: "(408) 555-5555",
addressLines: [
"1 Infinite Loop"
],
locality: "Cupertino",
administrativeArea: "CA",
postalCode: "95014",
country: "United States",
countryCode: "US"
};
paymentRequest.lineItems = [
{
label: "Subtotal",
type: "final",
amount: "35.00"
},
{
label: "Free Shipping",
amount: "0.00",
type: "pending"
},
{
label: "Estimated Tax",
amount: "3.06"
}
];
paymentRequest.requiredBillingContactFields = [
"postalAddress",
"name"
];
paymentRequest.requiredShippingContactFields = [
"postalAddress",
"name",
"phone",
"email"
];
paymentRequest.shippingContact = {
emailAddress: "ravipatel@example.com",
familyName: "Patel",
givenName: "Ravi",
phoneNumber: "(408) 555-5555",
addressLines: [
"1 Infinite Loop"
],
locality: "Cupertino",
administrativeArea: "CA",
postalCode: "95014",
country: "United States",
countryCode: "US"
};
paymentRequest.shippingMethods = [
{
label: "Free Shipping",
detail: "Arrives in 5 to 7 days",
amount: "0.00",
identifier: "FreeShipping"
},
{
label: "2-hour Shipping",
amount: "5.00"
}
];
paymentRequest.shippingType = "storePickup";
});
});

560
types/applepayjs/index.d.ts vendored Normal file
View File

@@ -0,0 +1,560 @@
// Type definitions for Apple Pay JS 1.0
// Project: https://developer.apple.com/reference/applepayjs
// Definitions by: Martin Costello <https://martincostello.com/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* A session object for managing the payment process on the web.
*/
declare class ApplePaySession extends EventTarget {
/**
* Creates a new instance of the ApplePaySession class.
* @param version - The version of the ApplePay JS API you are using.
* @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet.
*/
constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest);
/**
* A callback function that is automatically called when the payment UI is dismissed with an error.
*/
oncancel: (event: ApplePayJS.Event) => void;
/**
* A callback function that is automatically called when the user has authorized the Apple Pay payment, typically via TouchID.
*/
onpaymentauthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => void;
/**
* A callback function that is automatically called when a new payment method is selected.
*/
onpaymentmethodselected: (event: ApplePayJS.ApplePayPaymentMethodSelectedEvent) => void;
/**
* A callback function that is called when a shipping contact is selected in the payment sheet.
*/
onshippingcontactselected: (event: ApplePayJS.ApplePayShippingContactSelectedEvent) => void;
/**
* A callback function that is automatically called when a shipping method is selected.
*/
onshippingmethodselected: (event: ApplePayJS.ApplePayShippingMethodSelectedEvent) => void;
/**
* A callback function that is automatically called when the payment sheet is displayed.
*/
onvalidatemerchant: (event: ApplePayJS.ApplePayValidateMerchantEvent) => void;
/**
* Indicates whether or not the device supports Apple Pay.
* @returns true if the device supports making payments with Apple Pay; otherwise, false.
*/
static canMakePayments(): boolean;
/**
* Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false.
*/
static canMakePaymentsWithActiveCard(merchantIdentifier: string): Promise<boolean>;
/**
* Displays the Set up Apple Pay button.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @returns A boolean value indicating whether setup was successful.
*/
static openPaymentSetup(merchantIdentifier: string): Promise<boolean>;
/**
* Verifies if a web browser supports a given Apple Pay JS API version.
* @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1.
* @returns A boolean value indicating whether the web browser supports the given API version. Returns false if the web browser does not support the specified version.
*/
static supportsVersion(version: number): boolean;
/**
* Aborts the current Apple Pay session.
*/
abort(): void;
/**
* Begins the merchant validation process.
*/
begin(): void;
/**
* Call after the merchant has been validated.
* @param merchantSession - An opaque message session object.
*/
completeMerchantValidation(merchantSession: any): void;
/**
* Call when a payment has been authorized.
* @param status - The status of the payment.
*/
completePayment(status: number): void;
/**
* Call after a payment method has been selected.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after a shipping contact has been selected.
* @param status - The status of the shipping contact update.
* @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completeShippingContactSelection(
status: number,
newShippingMethods: ApplePayJS.ApplePayShippingMethod[],
newTotal: ApplePayJS.ApplePayLineItem,
newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after the shipping method has been selected.
* @param status - The status of the shipping method update.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* The requested action succeeded.
*/
static readonly STATUS_SUCCESS: number;
/**
* The requested action failed.
*/
static readonly STATUS_FAILURE: number;
/**
* The billing address is not valid.
*/
static readonly STATUS_INVALID_BILLING_POSTAL_ADDRESS: number;
/**
* The shipping address is not valid.
*/
static readonly STATUS_INVALID_SHIPPING_POSTAL_ADDRESS: number;
/**
* The shipping contact information is not valid.
*/
static readonly STATUS_INVALID_SHIPPING_CONTACT: number;
/**
* The PIN information is not valid. Cards on the China Union Pay network may require a PIN.
*/
static readonly STATUS_PIN_INCORRECT: number;
/**
* The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
*/
static readonly STATUS_PIN_LOCKOUT: number;
/**
* The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
*/
static readonly STATUS_PIN_REQUIRED: number;
}
declare namespace ApplePayJS {
/**
* Defines a line item in a payment request - for example, total, tax, discount, or grand total.
*/
interface ApplePayLineItem {
/**
* A short, localized description of the line item.
*/
label: string;
/**
* The line item's amount.
*/
amount: string;
/**
* A value that indicates if the line item is final or pending.
*/
type?: string;
}
/**
* Represents the result of authorizing a payment request and contains encrypted payment information.
*/
interface ApplePayPayment {
/**
* The encrypted token for an authorized payment.
*/
token: ApplePayPaymentToken;
/**
* The billing contact selected by the user for this transaction.
*/
billingContact?: ApplePayPaymentContact;
/**
* The shipping contact selected by the user for this transaction.
*/
shippingContact?: ApplePayPaymentContact;
}
/**
* The ApplePayPaymentAuthorizedEvent class defines the attributes contained by the ApplePaySession.onpaymentauthorized callback function.
*/
abstract class ApplePayPaymentAuthorizedEvent extends Event {
/**
* The payment token used to authorize a payment.
*/
readonly payment: ApplePayPayment;
}
/**
* Encapsulates contact information needed for billing and shipping.
*/
interface ApplePayPaymentContact {
/**
* An email address for the contact.
*/
emailAddress: string;
/**
* The contact's family name.
*/
familyName: string;
/**
* The contact's given name.
*/
givenName: string;
/**
* A phone number for the contact.
*/
phoneNumber: string;
/**
* The address for the contact.
*/
addressLines: string[];
/**
* The city for the contact.
*/
locality: string;
/**
* The state for the contact.
*/
administrativeArea: string;
/**
* The zip code, where applicable, for the contact.
*/
postalCode: string;
/**
* The colloquial country name for the contact.
*/
country: string;
/**
* The contact's ISO country code.
*/
countryCode: string;
}
/**
* Contains information about an Apple Pay payment card.
*/
interface ApplePayPaymentMethod {
/**
* A string, suitable for display, that describes the card.
*/
displayName: string;
/**
* A string, suitable for display, that is the name of the payment network backing the card.
* The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest.
*/
network: string;
/**
* A value representing the card's type of payment.
*/
type: string;
/**
* The payment pass object associated with the payment.
*/
paymentPass: ApplePayPaymentPass;
}
/**
* The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function.
*/
abstract class ApplePayPaymentMethodSelectedEvent extends Event {
/**
* The card used to complete a payment.
*/
readonly paymentMethod: ApplePayPaymentMethod;
}
/**
* Represents a provisioned payment card for Apple Pay payments.
*/
interface ApplePayPaymentPass {
/**
* The unique identifier for the primary account number for the payment card.
*/
primaryAccountIdentifier: string;
/**
* A version of the primary account number suitable for display in your UI.
*/
primaryAccountNumberSuffix: string;
/**
* The unique identifier for the device-specific account number.
*/
deviceAccountIdentifier?: string;
/**
* A version of the device account number suitable for display in your UI.
*/
deviceAccountNumberSuffix?: string;
/**
* The activation state of the pass.
*/
activationState: string;
}
/**
* Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information.
*/
interface ApplePayPaymentRequest {
/**
* The merchant's two-letter ISO 3166 country code.
*/
countryCode: string;
/**
* The three-letter ISO 4217 currency code for the payment.
*/
currencyCode: string;
/**
* A set of line items that explain recurring payments and/or additional charges.
*/
lineItems?: ApplePayLineItem[];
/**
* The payment capabilities supported by the merchant.
* The value must at least contain ApplePayMerchantCapability.supports3DS.
*/
merchantCapabilities: string[];
/**
* The payment networks supported by the merchant.
*/
supportedNetworks: string[];
/**
* A line item representing the total for the payment.
*/
total: ApplePayLineItem;
/**
* Billing contact information for the user.
*/
billingContact?: ApplePayPaymentContact;
/**
* The billing information that you require from the user in order to process the transaction.
*/
requiredBillingContactFields?: string[];
/**
* The shipping information that you require from the user in order to fulfill the order.
*/
requiredShippingContactFields?: string[];
/**
* Shipping contact information for the user.
*/
shippingContact?: ApplePayPaymentContact;
/**
* A set of shipping method objects that describe the available shipping methods.
*/
shippingMethods?: ApplePayShippingMethod[] | string[];
/**
* How the items are to be shipped.
*/
shippingType?: string;
/**
* Optional user-defined data.
*/
applicationData?: string;
}
/**
* Contains the user's payment credentials.
*/
interface ApplePayPaymentToken {
/**
* An object containing the encrypted payment data.
*/
paymentData: any;
/**
* Information about the card used in the transaction.
*/
paymentMethod: ApplePayPaymentMethod;
/**
* A unique identifier for this payment.
*/
transactionIdentifier: string;
}
/**
* The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function.
*/
abstract class ApplePayShippingContactSelectedEvent extends Event {
/**
* The shipping address selected by the user.
*/
readonly shippingContact: ApplePayPaymentContact;
}
/**
* Defines a shipping method for delivering physical goods.
*/
interface ApplePayShippingMethod {
/**
* A short description of the shipping method.
*/
label: string;
/**
* A further description of the shipping method.
*/
detail?: string;
/**
* The amount associated with this shipping method.
*/
amount: string;
/**
* A client-defined identifier.
*/
identifier?: string;
}
/**
* The ApplePayShippingMethodSelectedEvent class defines the attribute contained by the ApplePaySession.onshippingmethodselected callback function.
*/
abstract class ApplePayShippingMethodSelectedEvent extends Event {
/**
* The shipping method selected by the user.
*/
readonly shippingMethod: ApplePayShippingMethod;
}
/**
* The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function.
*/
abstract class ApplePayValidateMerchantEvent extends Event {
/**
* The URL used to validate the merchant server.
*/
readonly validationURL: string;
}
abstract class Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
readonly composed: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
readonly srcElement: EventTarget;
readonly target: EventTarget;
readonly timeStamp: string;
readonly type: string;
composedPath(): Node[];
initEvent(type?: string, bubbles?: boolean, cancelable?: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
static readonly AT_TARGET: number;
static readonly BLUR: number;
static readonly BUBBLING_PHASE: number;
static readonly CAPTURING_PHASE: number;
static readonly CHANGE: number;
static readonly CLICK: number;
static readonly DBLCLICK: number;
static readonly DRAGDROP: number;
static readonly FOCUS: number;
static readonly KEYDOWN: number;
static readonly KEYPRESS: number;
static readonly KEYUP: number;
static readonly MOUSEDOWN: number;
static readonly MOUSEDRAG: number;
static readonly MOUSEMOVE: number;
static readonly MOUSEOUT: number;
static readonly MOUSEOVER: number;
static readonly MOUSEUP: number;
static readonly NONE: number;
static readonly SELECT: number;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"baseUrl": "../",
"forceConsistentCasingInFileNames": true,
"lib": [
"dom",
"es6"
],
"module": "commonjs",
"noImplicitAny": true,
"noImplicitThis": true,
"noEmit": true,
"strictNullChecks": true,
"typeRoots": [
"../"
],
"types": []
},
"files": [
"index.d.ts",
"applepayjs-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "../tslint.json" }

View File

@@ -1,6 +1,6 @@
// More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md
var config: Microsoft.ApplicationInsights.IConfig = {
const config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: "<your iKey>",
endpointUrl: "endpointUrl",
emitLineDelimitedJson: false,
@@ -30,7 +30,7 @@ var config: Microsoft.ApplicationInsights.IConfig = {
isStorageUseDisabled: true
};
var appInsights: Microsoft.ApplicationInsights.IAppInsights = {
appInsights = {
config,
context: null,
queue: null,
@@ -91,9 +91,8 @@ appInsights.setAuthenticatedUserContext("userId", "accountId");
// set config dynamically
appInsights.config.instrumentationKey = "<new key>";
// TelementryContext
var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
const context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
context.application.ver = "v0.0.0";
context.application.build = "1.1.1";
@@ -113,54 +112,54 @@ context.operation.id = "1";
context.operation.syntheticSource = "testAgent";
// track
var data = new Microsoft.Telemetry.Base();
var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name");
const data = new Microsoft.Telemetry.Base();
const envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name");
context.track(envelope);
context.addTelemetryInitializer((envelope) => false);
context.addTelemetryInitializer(telemetryEnvelope => false);
// track event
var eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj);
var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
const eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
const eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj);
const eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
context.track(eventEnvelope);
// track exception
var exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical);
var exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Exception>(
const exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical);
const exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Exception>(
Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj);
var exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
const exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
context.track(exceptionEnvelope);
// track metric
var metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null);
var metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Metric>(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj);
var metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
const metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null);
const metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Metric>(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj);
const metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
context.track(metricEnvelope);
// track page view
var pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null);
var pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj);
var pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
const pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null);
const pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj);
const pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
context.track(pageViewEnvelope);
// track page view performance
var pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null);
var pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(
const pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null);
const pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(
Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj);
var pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
const pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
context.track(pageViewPerfEnvelope);
// track remote dependency
var remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET");
var remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(
const remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET");
const remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(
Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj);
var remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
const remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
context.track(pageViewPerfEnvelope);
// track trace
var traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null);
var traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
var traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);
const traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null);
const traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
const traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);

View File

@@ -195,8 +195,8 @@ declare module Microsoft.ApplicationInsights.Context {
interface IInternal {
/**
* The SDK version used to create this telemetry item.
*/
* The SDK version used to create this telemetry item.
*/
sdkVersion: string;
/**
* The SDK agent version.
@@ -206,15 +206,15 @@ declare module Microsoft.ApplicationInsights.Context {
interface ISample {
/**
* Sample rate
*/
* Sample rate
*/
sampleRate: number;
}
interface ISession {
/**
* The session ID.
*/
* The session ID.
*/
id: string;
/**
* The true if this is the first session
@@ -258,8 +258,8 @@ declare module Microsoft.ApplicationInsights.Context {
interface IUser {
/**
* The telemetry configuration.
*/
* The telemetry configuration.
*/
config: any;
/**
* The user ID.
@@ -345,12 +345,12 @@ declare module Microsoft.ApplicationInsights.Telemetry {
measurements: Microsoft.ApplicationInsights.FieldType;
};
/**
* Constructs a new isntance of the ExceptionTelemetry object
*/
* Constructs a new isntance of the ExceptionTelemetry object
*/
constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel);
/**
* Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.
*/
* Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.
*/
static CreateSimpleException(message: string, typeName: string, assembly: string, fileName: string, details: string, line: number, handledAt?: string): Telemetry.Exception;
}
@@ -414,8 +414,8 @@ declare module Microsoft.ApplicationInsights.Telemetry {
getIsValid(): boolean;
private durationMs;
/**
* Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method.
*/
* Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method.
*/
getDurationMs(): number;
/**
* Constructs a new instance of the PageEventTelemetry object
@@ -423,8 +423,8 @@ declare module Microsoft.ApplicationInsights.Telemetry {
constructor(name: string, url: string, unused: number, properties?: any, measurements?: any);
static getPerformanceTiming(): PerformanceTiming;
/**
* Returns true is window performance timing API is supported, false otherwise.
*/
* Returns true is window performance timing API is supported, false otherwise.
*/
static isPerformanceTimingSupported(): PerformanceTiming;
/**
* As page loads different parts of performance timing numbers get set. When all of them are set we can report it.
@@ -615,16 +615,16 @@ declare module Microsoft.ApplicationInsights {
interface ITelemetryContext {
/**
* The object describing a component tracked by this object.
*/
* The object describing a component tracked by this object.
*/
application: Context.IApplication;
/**
* The object describing a device tracked by this object.
*/
device: Context.IDevice;
/**
* The object describing internal settings.
*/
* The object describing internal settings.
*/
internal: Context.IInternal;
/**
* The object describing a location tracked by this object.
@@ -635,8 +635,8 @@ declare module Microsoft.ApplicationInsights {
*/
operation: Context.IOperation;
/**
* The object describing sampling settings.
*/
* The object describing sampling settings.
*/
sample: Context.ISample;
/**
* The object describing a user tracked by this object.
@@ -647,13 +647,13 @@ declare module Microsoft.ApplicationInsights {
*/
session: Context.ISession;
/**
* Adds telemetry initializer to the collection. Telemetry initializers will be called one by one
* before telemetry item is pushed for sending and in the order they were added.
*/
* Adds telemetry initializer to the collection. Telemetry initializers will be called one by one
* before telemetry item is pushed for sending and in the order they were added.
*/
addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any;
/**
* Tracks telemetry object.
*/
* Tracks telemetry object.
*/
track(envelope: Microsoft.ApplicationInsights.IEnvelope): any;
}
@@ -662,23 +662,23 @@ declare module Microsoft.ApplicationInsights {
context: ITelemetryContext;
queue: Array<() => void>;
/**
* Starts timing how long the user views a page or other item. Call this when the page opens.
* This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
* Starts timing how long the user views a page or other item. Call this when the page opens.
* This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
startTrackPage(name?: string): any;
/**
* Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackPage(name?: string, url?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
* Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackPage(
name?: string,
url?: string,
properties?: { [name: string]: string },
measurements?: { [name: string]: number }): any;
/**
* Logs that a page or other item was viewed.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
@@ -687,11 +687,11 @@ declare module Microsoft.ApplicationInsights {
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally.
*/
trackPageView(name?: string, url?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}, duration?: number): any;
trackPageView(
name?: string,
url?: string,
properties?: { [name: string]: string },
measurements?: { [name: string]: number }, duration?: number): any;
/**
* Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends.
* @param name A string that identifies this event uniquely within the document.
@@ -703,22 +703,20 @@ declare module Microsoft.ApplicationInsights {
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackEvent(name: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
stopTrackEvent(
name: string,
properties?: { [name: string]: string },
measurements?: { [name: string]: number }): any;
/**
* Log a user action or other occurrence.
* @param name A string to identify this event in the portal.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
trackEvent(name: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}): any;
* Log a user action or other occurrence.
* @param name A string to identify this event in the portal.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
trackEvent(
name: string,
properties?: { [name: string]: string },
measurements?: { [name: string]: number }): any;
/**
* Log a dependency call
* @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id.
@@ -737,11 +735,12 @@ declare module Microsoft.ApplicationInsights {
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param severityLevel AI.SeverityLevel - severity level
*/
trackException(exception: Error, handledAt?: string, properties?: {
[name: string]: string;
}, measurements?: {
[name: string]: number;
}, severityLevel?: AI.SeverityLevel): any;
trackException(
exception: Error,
handledAt?: string,
properties?: { [name: string]: string },
measurements?: { [name: string]: number },
severityLevel?: AI.SeverityLevel): any;
/**
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
@@ -752,28 +751,30 @@ declare module Microsoft.ApplicationInsights {
* @param min The smallest measurement in the sample. Defaults to the average.
* @param max The largest measurement in the sample. Defaults to the average.
*/
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: {
[name: string]: string;
}): any;
trackMetric(
name: string,
average: number,
sampleCount?: number,
min?: number,
max?: number,
properties?: { [name: string]: string }): any;
/**
* Log a diagnostic message.
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
*/
trackTrace(message: string, properties?: {
[name: string]: string;
}): any;
* Log a diagnostic message.
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
*/
trackTrace(message: string, properties?: { [name: string]: string }): any;
/**
* Immediately send all queued telemetry.
*/
flush(): any;
/**
* Sets the autheticated user id and the account id in this session.
* User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars.
*
* @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
* @param accountId {string} - An optional string to represent the account associated with the authenticated user.
*/
* Sets the autheticated user id and the account id in this session.
* User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars.
*
* @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
* @param accountId {string} - An optional string to represent the account associated with the authenticated user.
*/
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any;
/**
* Clears the authenticated user id and the account id from the user context.
@@ -796,4 +797,4 @@ declare module 'applicationinsights-js' {
const AppInsights: Microsoft.ApplicationInsights.IAppInsights;
}
declare var appInsights: Microsoft.ApplicationInsights.IAppInsights;
declare var appInsights: Microsoft.ApplicationInsights.IAppInsights;

View File

@@ -8,4 +8,4 @@ point = {
spatialReference: {
wkid: 4326
}
};
};

View File

@@ -65,7 +65,6 @@ export interface BezierCurve {
export type JsonCurve = CircularArc | Arc | OldCircularArc | BezierCurve;
export interface SpatialReferenceWkid {
wkid?: number;
latestWkid?: number;
@@ -131,7 +130,6 @@ export interface Envelope extends Geometry {
export type esriGeometryType = "esriGeometryPoint" | "esriGeometryMultipoint" | "esriGeometryPolyline" | "esriGeometryPolygon" | "esriGeometryEnvelope";
export type Color = [number, number, number, number];
export type SimpleMarkerSymbolStyle = "esriSMSCircle" | "esriSMSCross" | "esriSMSDiamond" | "esriSMSSquare" | "esriSMSX" | "esriSMSTriangle";
export type SimpleLineSymbolStyle = "esriSLSDash" | "esriSLSDashDot" | "esriSLSDashDotDot" | "esriSLSDot" | "esriSLSNull" | "esriSLSSolid";
@@ -181,7 +179,6 @@ export interface PictureSourced {
"angle"?: number;
"xoffset"?: number;
"yoffset"?: number;
}
export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced {
@@ -217,4 +214,4 @@ export interface TextSymbol extends MarkerSymbol {
"kerning"?: boolean;
"font"?: Font;
"text"?: string; // only applicable when specified as a client-side graphic.
}
}

View File

@@ -14,7 +14,7 @@ const geojsonPoint: GeoJSON.Point = {
};
// parse ArcGIS JSON, convert it to GeoJSON
var geojson = utils.arcgisToGeoJSON(arcgisPoint);
const geojson = utils.arcgisToGeoJSON(arcgisPoint);
// take GeoJSON and convert it to ArcGIS JSON
var arcgis = utils.geojsonToArcGIS(geojsonPoint);
const arcgis = utils.geojsonToArcGIS(geojsonPoint);

View File

@@ -15,4 +15,4 @@ export function arcgisToGeoJSON<T extends ArcGis.Geometry>(arcgis: T): GeoJSON.G
/**
* Converts a GeoJSON geometry into a ArcGIS geometry.
*/
export function geojsonToArcGIS(geojson: GeoJSON.GeometryObject): ArcGis.Geometry;
export function geojsonToArcGIS(geojson: GeoJSON.GeometryObject): ArcGis.Geometry;

View File

@@ -2,4 +2,4 @@ import arrayUniq = require("array-uniq");
arrayUniq([1, 1, 2, 3, 3]);
arrayUniq(["foo", "foo", "bar", "foo"]);
arrayUniq(["foo", "foo", "bar", "foo"]);

View File

@@ -5,4 +5,4 @@
declare function arrayUniq<T>(arr: T[]): T[];
export = arrayUniq;
export = arrayUniq;

View File

@@ -29,4 +29,4 @@ artyom.getVoices();
artyom.getLanguage();
// Get the artyom.js version
artyom.getVersion();
artyom.getVersion();

View File

@@ -22,16 +22,16 @@ interface SpeechRecognition extends EventTarget {
start(): void;
stop(): void;
abort(): void;
onaudiostart: (ev: Event) => any;
onsoundstart: (ev: Event) => any;
onspeechstart: (ev: Event) => any;
onspeechend: (ev: Event) => any;
onsoundend: (ev: Event) => any;
onresult: (ev: SpeechRecognitionEvent) => any;
onnomatch: (ev: SpeechRecognitionEvent) => any;
onerror: (ev: SpeechRecognitionError) => any;
onstart: (ev: Event) => any;
onend: (ev: Event) => any;
onaudiostart(ev: Event): any;
onsoundstart(ev: Event): any;
onspeechstart(ev: Event): any;
onspeechend(ev: Event): any;
onsoundend(ev: Event): any;
onresult(ev: SpeechRecognitionEvent): any;
onnomatch(ev: SpeechRecognitionEvent): any;
onerror(ev: SpeechRecognitionError): any;
onstart(ev: Event): any;
onend(ev: Event): any;
}
interface SpeechRecognitionStatic {
@@ -106,7 +106,7 @@ interface SpeechSynthesis extends EventTarget {
speaking: boolean;
paused: boolean;
onvoiceschanged: (ev: Event) => any;
onvoiceschanged(ev: Event): any;
speak(utterance: SpeechSynthesisUtterance): void;
cancel(): void;
pause(): void;
@@ -128,13 +128,13 @@ interface SpeechSynthesisUtterance extends EventTarget {
rate: number;
pitch: number;
onstart: (ev: SpeechSynthesisEvent) => any;
onend: (ev: SpeechSynthesisEvent) => any;
onerror: (ev: SpeechSynthesisErrorEvent) => any;
onpause: (ev: SpeechSynthesisEvent) => any;
onresume: (ev: SpeechSynthesisEvent) => any;
onmark: (ev: SpeechSynthesisEvent) => any;
onboundary: (ev: SpeechSynthesisEvent) => any;
onstart(ev: SpeechSynthesisEvent): any;
onend(ev: SpeechSynthesisEvent): any;
onerror(ev: SpeechSynthesisErrorEvent): any;
onpause(ev: SpeechSynthesisEvent): any;
onresume(ev: SpeechSynthesisEvent): any;
onmark(ev: SpeechSynthesisEvent): any;
onboundary(ev: SpeechSynthesisEvent): any;
}
interface SpeechSynthesisUtteranceStatic {
@@ -211,7 +211,7 @@ declare namespace Artyom {
/** Triggers of the command */
indexes: string[];
/** Logic to execute when the command is triggered */
action: (i: number, wildcard?: string, full?: string) => void;
action(i: number, wildcard?: string, full?: string): void;
/** Description of the command */
description?: string;
/** Flag to specify is a command is either normal or smart */
@@ -502,7 +502,7 @@ declare namespace Artyom {
/**
* Method to bla, bla, bla...
*/
static getInstance(): ArtyomJS
static getInstance(): ArtyomJS;
}
}

View File

@@ -1,5 +0,0 @@
{
"dependencies": {
"@types/auth0-js": "latest"
}
}

View File

@@ -1,5 +0,0 @@
{
"dependencies": {
"@types/auth0-js": "latest"
}
}

View File

@@ -0,0 +1,22 @@
import context = require("aws-lambda-mock-context");
import * as Alexa from "alexa-sdk";
const launchRequestJson: any = {
request: {
locale: "en-US",
requestId: "amzn1.echo-api.request.[unique-value-here]",
timestamp: "2016-10-27T18:21:44Z",
type: "LaunchRequest",
},
session: {
application: {applicationId: "amzn1.ask.skill.[unique-value-here]"},
attributes: {},
new: false,
sessionId: "amzn1.echo-api.session.[unique-value-here]",
user: {userId: "amzn1.ask.account.[unique-value-here]"},
},
version: "1.0",
};
const ctx = context();
const alexa = Alexa.handler(launchRequestJson, ctx);

View File

@@ -0,0 +1,34 @@
// Type definitions for AWS Lambda Mock Context SDK 1.0
// Project: https://github.com/moskalyk/typed-aws-lambda-mock-context
// Definitions by: Morgan Moskalyk <morgan.moskalyk@gmail.com>, Anand Nimkar <anand.a.nimkar@gmail.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function context(options?: Options): Context;
export = context;
interface Context {
Promise: Promise<any>;
callbackWaitsForEmptyEventLoop: boolean;
functionName: string;
functionVersion: string;
invokedFunctionArn: string;
memoryLimitInMB: string;
awsRequestId: string;
invokeid: string;
logGroupName: string;
logStreamName: string;
getRemainingTimeInMillis: number;
succeed(result: any): Promise<any>;
fail(err: any): Promise<any>;
done(err: any, result: any): Promise<any>;
}
interface Options {
region: string;
account: string;
functionName: string;
functionVersion: string;
memoryLimitInMB: string;
alias?: string;
}

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"aws-lambda-mock-context-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}

View File

@@ -1,5 +1,5 @@
import * as base64js from "base64-js";
const length: number = base64js.byteLength("");
const bytes: Uint8Array = base64js.toByteArray("");
const decoded: string = base64js.fromByteArray(new Uint8Array(0));
base64js.byteLength(""); // $ExpectType number
base64js.toByteArray(""); // $ExpectType Uint8Array
base64js.fromByteArray(new Uint8Array(0)); // $ExpectTpe string

View File

@@ -1,9 +1,9 @@
import BigInteger = require('bigi');
var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012");
var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
const b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012");
const b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
var b3 = b1.multiply(b2);
const b3 = b1.multiply(b2);
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132

View File

@@ -3,9 +3,9 @@
import bigi = require('bigi');
import bitcoin = require('bitcoinjs-lib');
declare var it: any;
declare var describe: any;
declare var assert: any;
declare const it: any;
declare const describe: any;
declare const assert: any;
describe('bitcoinjs-lib (basic)', () => {
it('can generate a random bitcoin address', () => {
@@ -13,18 +13,18 @@ describe('bitcoinjs-lib (basic)', () => {
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); }
// generate random keyPair
var keyPair = bitcoin.ECPair.makeRandom({ rng });
var address = keyPair.getAddress();
const keyPair = bitcoin.ECPair.makeRandom({ rng });
const address = keyPair.getAddress();
assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64');
});
it('can generate an address from a SHA256 hash', () => {
var hash = bitcoin.crypto.sha256('correct horse battery staple');
var d = bigi.fromBuffer(hash);
const hash = bitcoin.crypto.sha256('correct horse battery staple');
const d = bigi.fromBuffer(hash);
var keyPair = new bitcoin.ECPair(d);
var address = keyPair.getAddress();
const keyPair = new bitcoin.ECPair(d);
const address = keyPair.getAddress();
assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8');
});
@@ -33,26 +33,26 @@ describe('bitcoinjs-lib (basic)', () => {
// for testing only
function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); }
var litecoin = bitcoin.networks.litecoin;
const litecoin = bitcoin.networks.litecoin;
var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng });
var wif = keyPair.toWIF();
var address = keyPair.getAddress();
const keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng });
const wif = keyPair.toWIF();
const address = keyPair.getAddress();
assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn');
assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS');
});
it('can import an address via WIF', () => {
var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct');
var address = keyPair.getAddress();
const keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct');
const address = keyPair.getAddress();
assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31');
});
it('can create a Transaction', () => {
var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy');
var tx = new bitcoin.TransactionBuilder();
const keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy');
const tx = new bitcoin.TransactionBuilder();
tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0);
tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000);

View File

@@ -1,4 +1,4 @@
var someInput = { a: 1, b: 2, c: 3 };
const someInput = { a: 1, b: 2, c: 3 };
import blacklist = require('blacklist');
@@ -10,4 +10,4 @@ blacklist(someInput, {
b: false, // b will be in the result
c: 1 > 2 // false, therefore c will be in the result
});
// => { b: 2, c: 3 }
// => { b: 2, c: 3 }

View File

@@ -1,11 +1,11 @@
import { BloomFilter } from './index';
import { BloomFilter } from 'bloomfilter';
function test_bloomfilter() {
const m: number = 10;
const k: number = 2;
let bloomFilter = new BloomFilter(m, k);
let array: Array<Int32Array> = bloomFilter.buckets;
let length: number = bloomFilter.buckets.length;
const bloomFilter = new BloomFilter(m, k);
const array: Int32Array[] = bloomFilter.buckets;
const length: number = bloomFilter.buckets.length;
bloomFilter.add('someString');
let test: boolean = bloomFilter.test('someString');
const test: boolean = bloomFilter.test('someString');
}

View File

@@ -3,8 +3,8 @@
// Definitions by: slawiko <https://github.com/slawiko>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export declare class BloomFilter {
buckets: Array<Int32Array>;
export class BloomFilter {
buckets: Int32Array[];
constructor(m: number, k: number);

View File

@@ -7,7 +7,6 @@ function testSomeStaticMethods() {
function testFunctionReturningPromise() {
function functionReturningPromise(): Promise<string> {
return new Promise<string>((resolve, reject, onCancel) => {
if (onCancel) {
onCancel(() => {
console.log("onCancel cleanup");
@@ -40,5 +39,4 @@ function testPromiseRejection() {
.then((value) => {
return value.toUpperCase();
});
}

View File

@@ -5,6 +5,6 @@
"no-empty-interface": false,
"array-type": false,
"unified-signatures": false,
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -16,7 +16,7 @@ declare namespace bodyParser {
interface Options {
inflate?: boolean;
limit?: number | string;
type?: string | ((req: Request) => any);
type?: string | string[] | ((req: Request) => any);
verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void;
}

View File

@@ -7,7 +7,7 @@
* @module braintree-web/american-express
* @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields.
*/
declare namespace BraintreeWeb {
declare namespace braintree {
export interface AmericanExpress {
/**
* @static
@@ -24,22 +24,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options Options
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.</strong>
* @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
*/
export class AmericanExpress {
/**
* @class
* @param {object} options Options
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.</strong>
* @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
*/
constructor(options: any);
/**
* Gets the rewards balance associated with a Braintree nonce.
@@ -63,7 +47,7 @@ declare namespace BraintreeWeb {
* });
* });
*/
public getRewardsBalance(options: { nonce: string }, callback: callback): void;
getRewardsBalance(options: { nonce: string }, callback: callback): void;
/**
* Gets the Express Checkout nonce profile given a nonce from American Express.
@@ -87,121 +71,123 @@ declare namespace BraintreeWeb {
* });
* });
*/
public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void;
getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void;
}
}
// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest
declare namespace braintree {
// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest
// billingContact
// Billing contact information for the user.
// countryCode
//Required.The merchants two- letter ISO 3166 country code.
// currencyCode
// Required.The three- letter ISO 4217 currency code for the payment.
// lineItems
//A set of line items that explain recurring payments and additional charges.
// merchantCapabilities
// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit.
// requiredBillingContactFields
// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
// requiredShippingContactFields
// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
// shippingContact
// Shipping contact information for the user.
// shippingMethods
//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation.
// shippingType
// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping.
// supportedNetworks
// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa.
// total
// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation.
interface ApplePayPaymentRequest {
total: {
label: string;
amount: string;
};
countryCode: string;
currencyCode: string;
supportedNetworks: string[];
merchantCapabilities: string[];
// billingContact
// Billing contact information for the user.
// countryCode
//Required.The merchants two- letter ISO 3166 country code.
// currencyCode
// Required.The three- letter ISO 4217 currency code for the payment.
// lineItems
//A set of line items that explain recurring payments and additional charges.
// merchantCapabilities
// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit.
// requiredBillingContactFields
// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
// requiredShippingContactFields
// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
// shippingContact
// Shipping contact information for the user.
// shippingMethods
//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation.
// shippingType
// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping.
// supportedNetworks
// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa.
// total
// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation.
interface ApplePayPaymentRequest {
total: {
label: string;
amount: string;
};
countryCode: string;
currencyCode: string;
supportedNetworks: string[];
merchantCapabilities: string[];
billingContact?: any;
shippingContact?: any;
shippingMethods?: any;
shippingType?: any;
requiredBillingContactFields?: any;
requiredShippingContactFields?: any;
}
billingContact?: any;
shippingContact?: any;
shippingMethods?: any;
shippingType?: any;
requiredBillingContactFields?: any;
requiredShippingContactFields?: any;
}
declare enum ApplePayStatusCodes {
// The requested action succeeded.
STATUS_SUCCESS = 1,
// The requested action failed.
STATUS_FAILURE,
// The billing address is not valid.
STATUS_INVALID_BILLING_POSTAL_ADDRESS,
// The shipping address is not valid.
STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
// The shipping contact information is not valid.
STATUS_INVALID_SHIPPING_CONTACT,
// The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
STATUS_PIN_REQUIRED,
// The PIN information is not valid.Cards on the China Union Pay network may require a PIN.
STATUS_PIN_INCORRECT,
// The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
STATUS_PIN_LOCKOUT,
}
export enum ApplePayStatusCodes {
// The requested action succeeded.
STATUS_SUCCESS = 1,
// The requested action failed.
STATUS_FAILURE,
// The billing address is not valid.
STATUS_INVALID_BILLING_POSTAL_ADDRESS,
// The shipping address is not valid.
STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
// The shipping contact information is not valid.
STATUS_INVALID_SHIPPING_CONTACT,
// The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
STATUS_PIN_REQUIRED,
// The PIN information is not valid.Cards on the China Union Pay network may require a PIN.
STATUS_PIN_INCORRECT,
// The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
STATUS_PIN_LOCKOUT,
}
interface ApplePayPayload {
merchantIdentifier: string;
domainName: string;
displayName: string;
}
interface ApplePayPayload {
merchantIdentifier: string;
domainName: string;
displayName: string;
}
declare class ApplePaySession {
constructor(version: number, request: ApplePayPaymentRequest);
export class ApplePaySession {
constructor(version: number, request: ApplePayPaymentRequest);
canMakePayments(): boolean;
canMakePayments(): boolean;
canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean;
canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean;
completeMerchantValidation(merchantSession: any): void;
completeMerchantValidation(merchantSession: any): void;
abort(): void;
abort(): void;
begin(): void;
begin(): void;
completePayment(status: ApplePayStatusCodes): void;
completePayment(status: ApplePayStatusCodes): void;
completePaymentMethodSelection(newTotal: any, newLineItems: any): void;
completePaymentMethodSelection(newTotal: any, newLineItems: any): void;
completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void;
completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void;
completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void;
completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void;
supportsVersion(version: number): boolean;
supportsVersion(version: number): boolean;
oncancel: (event: any) => void;
oncancel: (event: any) => void;
onpaymentauthorized: (event: any) => void;
onpaymentauthorized: (event: any) => void;
onpaymentmethodselected: (event: any) => void;
onpaymentmethodselected: (event: any) => void;
onshippingcontactselected: (event: any) => void;
onshippingcontactselected: (event: any) => void;
onshippingmethodselected: (event: any) => void;
onshippingmethodselected: (event: any) => void;
onvalidatemerchant: (event: any) => void;
onvalidatemerchant: (event: any) => void;
}
}
/**
* @module braintree-web/apple-pay
* @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.*
*/
declare namespace BraintreeWeb {
declare namespace braintree {
export interface ApplePay {
/**
* @static
@@ -218,22 +204,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options Options
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.</strong>
* @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
*/
export class ApplePay {
/**
* @class
* @param {object} options Options
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.</strong>
* @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
*/
constructor(options: any);
/**
* Merges a payment request with Braintree defaults
@@ -260,7 +230,7 @@ declare namespace BraintreeWeb {
* // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
*
*/
public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest
createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest
/**
* Validates the merchant website, as required by ApplePaySession before payment can be authorized.
@@ -302,7 +272,7 @@ declare namespace BraintreeWeb {
* };
* });
*/
public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void;
performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void;
/**
* Tokenizes an Apple Pay payment.
@@ -332,16 +302,14 @@ declare namespace BraintreeWeb {
* };
* });
*/
public tokenize(options: { token: any }, callback: callback): void;
tokenize(options: { token: any }, callback: callback): void;
}
}
/** @module braintree-web/client */
declare namespace BraintreeWeb {
declare namespace braintree {
/**
* This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves.
* @typedef {object} Client~configuration
* @property {object} client The braintree-web/client parameters.
* @property {string} client.authorization A tokenizationKey or clientToken.
* @property {object} gatewayConfiguration Gateway-supplied configuration.
@@ -398,30 +366,13 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {Client~configuration} configuration Options
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.</strong>
* @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
*/
export class Client {
/**
* @class
* @param {Client~configuration} configuration Options
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.</strong>
* @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
*/
constructor(configuration: Configuration);
/**
* Returns a copy of the configuration values.
* @public
* @returns {Client~configuration} configuration
*/
public getConfiguration(): Configuration;
getConfiguration(): Configuration;
/**
* Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization.
@@ -470,13 +421,12 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void;
request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void;
}
}
/** @module braintree-web/data-collector */
declare namespace BraintreeWeb {
declare namespace braintree {
export interface DataCollector {
/**
* @static
@@ -496,24 +446,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @global
* @name DataCollector
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.</strong>
* @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. Before using DataCollector, make sure you have enabled advanced fraud protection in the Braintree gateway. To use your own Kount ID, contact our support team ([support@braintreepayments.com](mailto:support@braintreepayments.com) or [877.434.2894](tel:877.434.2894)).
*/
export class DataCollector {
/**
* @class
* @global
* @name DataCollector
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.</strong>
* @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions.
*/
constructor();
/**
* @memberof DataCollector
@@ -534,12 +466,11 @@ declare namespace BraintreeWeb {
* @returns {void}
*/
teardown(callback?: callback): void;
}
}
/** @module braintree-web/hosted-fields */
declare namespace BraintreeWeb {
declare namespace braintree {
/**
* Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options}
* @typedef {object} field
@@ -578,7 +509,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} HostedFields~hostedFieldsCard
* @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}.
* @property {string} type The code-friendly representation of the card type. It will be one of the following strings:
* - `american-express`
@@ -618,7 +548,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} HostedFields~hostedFieldsFieldData
* @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}.
* @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event.
* @property {boolean} isFocused Whether or not the input is currently focused.
@@ -641,7 +570,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} HostedFields~stateObject
* @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}.
* @property {HostedFields~hostedFieldsCard[]} cards
* This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card.
@@ -679,7 +607,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} HostedFields~tokenizePayload
* @property {string} nonce The payment method nonce.
* @property {object} details Additional account details.
* @property {string} details.cardType Type of card, ex: Visa, MasterCard.
@@ -781,22 +708,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class HostedFields
* @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.</strong>
* @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
*/
export class HostedFields {
/**
* @class HostedFields
* @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.</strong>
* @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
*/
constructor(options: any);
/**
* @name HostedFields#on
@@ -829,7 +740,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public teardown(callback?: callback): void;
teardown(callback?: callback): void;
/**
* Tokenizes fields and returns a nonce payload.
@@ -872,7 +783,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public tokenize(options?: { vault: boolean }, callback?: callback): void;
tokenize(options?: { vault: boolean }, callback?: callback): void;
/**
* Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
@@ -889,7 +800,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public addClass(field: string, classname: string, callback?: callback): void;
addClass(field: string, classname: string, callback?: callback): void;
/**
* Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
@@ -910,7 +821,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public removeClass(field: string, classname: string, callback?: callback): void;
removeClass(field: string, classname: string, callback?: callback): void;
/**
* Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}.
@@ -940,7 +851,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public setPlaceholder(field: string, placeholder: string, callback?: callback): void;
setPlaceholder(field: string, placeholder: string, callback?: callback): void;
/**
* Clear the value of a {@link module:braintree-web/hosted-fields~field field}.
@@ -960,7 +871,7 @@ declare namespace BraintreeWeb {
* hostedFieldsInstance.clear('cvv');
* hostedFieldsInstance.clear('expirationDate');
*/
public clear(field: string, callback?: callback): void;
clear(field: string, callback?: callback): void;
/**
* Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types.
@@ -973,14 +884,13 @@ declare namespace BraintreeWeb {
* return state.fields[key].isValid;
* });
*/
public getState(): any;
getState(): any;
}
}
/** @module braintree-web/paypal */
declare namespace BraintreeWeb {
declare namespace braintree {
/**
* @typedef {object} PayPal~tokenizeReturn
* @property {Function} close A handle to close the PayPal checkout flow.
*/
interface PayPalTokenizeReturn {
@@ -988,7 +898,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} PayPal~tokenizePayload
* @property {string} nonce The payment method nonce.
* @property {string} type The payment method type, always `PayPalAccount`.
* @property {object} details Additional PayPal account details.
@@ -1082,20 +991,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
* @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
*/
export class PayPal {
/**
* @class
* @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
* @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
*/
constructor(options: any);
/**
* Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open.
@@ -1192,7 +1087,7 @@ declare namespace BraintreeWeb {
* });
* @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame.
*/
public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn;
tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}.
@@ -1200,15 +1095,13 @@ declare namespace BraintreeWeb {
* @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
* @returns {void}
*/
public teardown(callback?: () => void): void;
teardown(callback?: () => void): void;
}
}
/** @module braintree-web/three-d-secure */
declare namespace BraintreeWeb {
declare namespace braintree {
/**
* @typedef {object} ThreeDSecure~verifyPayload
* @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server.
* @property {object} details Additional account details.
* @property {string} details.cardType Type of card, ex: Visa, MasterCard.
@@ -1250,23 +1143,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.</strong>
* @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
*/
export class ThreeDSecure {
/**
* @class
* @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
* @description <strong>Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.</strong>
* @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
*/
constructor(options: any);
/**
* @callback ThreeDSecure~addFrameCallback
@@ -1329,7 +1205,7 @@ declare namespace BraintreeWeb {
* }
* });
*/
public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void;
verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void;
/**
* Cancel the 3DS flow and return the verification payload if available.
@@ -1349,7 +1225,7 @@ declare namespace BraintreeWeb {
* verifyPayload.liabilityShiftPossible; // boolean
* });
*/
public cancelVerifyCard(callback: callback): void;
cancelVerifyCard(callback: callback): void;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create}
@@ -1357,7 +1233,7 @@ declare namespace BraintreeWeb {
* @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
* @returns {void}
*/
public teardown(callback?: callback): void;
teardown(callback?: callback): void;
}
}
@@ -1365,9 +1241,8 @@ declare namespace BraintreeWeb {
* @module braintree-web/unionpay
* @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.*
*/
declare namespace BraintreeWeb {
declare namespace braintree {
/**
* @typedef {object} UnionPay~tokenizePayload
* @property {string} nonce The payment method nonce.
* @property {string} type Always <code>CreditCard</code>.
* @property {object} details Additional account details:
@@ -1388,7 +1263,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} UnionPay~enrollPayload
* @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`.
* @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag.
* </p><b>true</b> - the user will receive an SMS code that needs to be supplied for tokenization.
@@ -1400,7 +1274,6 @@ declare namespace BraintreeWeb {
}
/**
* @typedef {object} UnionPay~fetchCapabilitiesPayload
* @property {boolean} isUnionPay Determines if this card is a UnionPay card.
* @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`.
* @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`.
@@ -1443,22 +1316,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.</strong>
* @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
*/
export class UnionPay {
/**
* @class
* @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
* @description <strong>You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.</strong>
* @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
*/
constructor(options: any);
/**
* Fetches the capabilities of a card, including whether or not the SMS enrollment process is required.
@@ -1531,7 +1388,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void;
fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void;
/**
* Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required.
@@ -1594,7 +1451,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void;
enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void;
/**
* Tokenizes a UnionPay card and returns a nonce payload.
@@ -1643,7 +1500,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void;
tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields.
@@ -1659,8 +1516,7 @@ declare namespace BraintreeWeb {
* });
* @returns {void}
*/
public teardown(callback?: callback): void;
teardown(callback?: callback): void;
}
/**
@@ -1683,21 +1539,6 @@ declare namespace BraintreeWeb {
* @type {string}
*/
VERSION: string;
}
/**
* @class
* @param {object} options See {@link module:braintree-web/us-bank-account.create|us-bank-account.create}.
* @classdesc This class represents a US Bank Account component. Instances of this class can tokenize raw bank details or present a bank login. <strong>You cannot use this constructor directly. Use {@link module:braintree-web/us-bank-account.create|braintree.us-bank-account.create} instead.</strong>
*/
export class USBankAccount {
/**
* @class
* @param {object} options See {@link module:braintree-web/us-bank-account.create|us-bank-account.create}.
* @classdesc This class represents a US Bank Account component. Instances of this class can tokenize raw bank details or present a bank login. <strong>You cannot use this constructor directly. Use {@link module:braintree-web/us-bank-account.create|braintree.us-bank-account.create} instead.</strong>
*/
constructor(options: any)
/**
* Tokenizes bank information to return a payment method nonce. You can tokenize bank details by providing information like account and routing numbers. You can also tokenize with a bank login UI that prompts the customer to log into their bank account.
@@ -1778,7 +1619,7 @@ declare namespace BraintreeWeb {
* });
* });
*/
public tokenize(options: { mandateText: string, bankDetails: any, bankLogin: any }, callback: callback): void;
tokenize(options: { mandateText: string, bankDetails: any, bankLogin: any }, callback: callback): void;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/us-bank-account.create|create}.
@@ -1786,77 +1627,53 @@ declare namespace BraintreeWeb {
* @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
* @returns {void}
*/
public teardown(callback?: callback): void;
}
}
declare namespace BraintreeError {
/**
* Enum for {@link BraintreeError} types.
* @name BraintreeError.types
* @enum
* @readonly
* @memberof BraintreeError
* @property {string} CUSTOMER An error caused by the customer.
* @property {string} MERCHANT An error that is actionable by the merchant.
* @property {string} NETWORK An error due to a network problem.
* @property {string} INTERNAL An error caused by Braintree code.
* @property {string} UNKNOWN An error where the origin is unknown.
*/
export enum Types {
CUSTOMER,
MERCHANT,
NETWORK,
INTERNAL,
UNKNOWN
teardown(callback?: callback): void;
}
}
/**
* @class
* @global
* @param {object} options Construction options
* @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
* @description <strong>You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.</strong>
*/
declare class BraintreeError {
/**
* @class
* @global
* @param {object} options Construction options
* @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
* @description <strong>You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.</strong>
*/
constructor(options: any);
declare namespace braintree {
export namespace BraintreeError {
/**
* Enum for {@link BraintreeError} types.
* @name BraintreeError.types
* @enum
* @readonly
* @memberof BraintreeError
* @property {string} CUSTOMER An error caused by the customer.
* @property {string} MERCHANT An error that is actionable by the merchant.
* @property {string} NETWORK An error due to a network problem.
* @property {string} INTERNAL An error caused by Braintree code.
* @property {string} UNKNOWN An error where the origin is unknown.
*/
export type Types = "CUSTOMER" | "MERCHANT" | "NETWORK" | "INTERNAL" | "UNKNOWN";
}
/**
* @type {string}
* @description A code that corresponds to specific errors.
*/
code: string;
export interface BraintreeError {
/**
* @type {string}
* @description A code that corresponds to specific errors.
*/
code: string;
/**
* @type {string}
* @description A short description of the error.
*/
message: string;
/**
* @type {string}
* @description A short description of the error.
*/
message: string;
/**
* @type {BraintreeError.types}
* @description The type of error.
*/
type: BraintreeError.Types;
/**
* @type {BraintreeError.types}
* @description The type of error.
*/
type: BraintreeError.Types;
/**
* @type {object=}
* @description Additional information about the error, such as an underlying network error response.
*/
details: any;
}
/**
* @type {object=}
* @description Additional information about the error, such as an underlying network error response.
*/
details: any;
}
declare namespace BraintreeWeb {
/**
* @global
* @callback callback
@@ -1895,39 +1712,40 @@ declare namespace BraintreeWeb {
* braintreeClient.create(...);
* });
*/
interface BraintreeStatic {
declare namespace braintree {
/** @type {module:braintree-web/client} */
client: BraintreeWeb.Client;
export var client: braintree.Client;
/** @type {module:braintree-web/paypal} */
paypal: BraintreeWeb.PayPal;
export var paypal: braintree.PayPal;
/** @type {module:braintree-web/hosted-fields} */
hostedFields: BraintreeWeb.HostedFields;
export var hostedFields: braintree.HostedFields;
/** @type {module:braintree-web/three-d-secure} */
threeDSecure: BraintreeWeb.ThreeDSecure;
export var threeDSecure: braintree.ThreeDSecure;
/** @type {module:braintree-web/data-collector} */
dataCollector: BraintreeWeb.DataCollector;
export var dataCollector: braintree.DataCollector;
/** @type {module:braintree-web/american-express} */
americanExpress: BraintreeWeb.AmericanExpress;
export var americanExpress: braintree.AmericanExpress;
/** @type {module:braintree-web/unionpay} */
unionpay: BraintreeWeb.UnionPay;
export var unionpay: braintree.UnionPay;
/** @type {module:braintree-web/apple-pay} */
applePay: BraintreeWeb.ApplePay;
export var applePay: braintree.ApplePay;
/** @type {module:braintree-web/us-bank-account} */
usBankAccount: BraintreeWeb.USBankAccount;
/** @type {module:braintree-web/us-bank-account} */
export var usBankAccount: braintree.USBankAccount;
/**
* @description The current version of the SDK, i.e. `3.0.2`.
* @type {string}
*/
VERSION: string;
export var VERSION: string;
}
declare var braintree: BraintreeStatic;
export = braintree;
export as namespace braintree;

View File

@@ -0,0 +1,440 @@
import * as braintree from 'braintree-web';
let version: string = braintree.VERSION;
let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
braintree.client.create({
authorization: clientToken
}, function (error: braintree.BraintreeError, clientInstance: any) {
var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
var data: { creditCard: braintree.CreditCardInfo } = {
creditCard: {
number: form['cc-number'].value,
cvv: form['cc-cvv'].value,
expirationDate: form['cc-date'].value,
billingAddress: {
postalCode: form['cc-postal'].value
}
}
};
clientInstance.request({
endpoint: 'payment_methods/credit_cards',
method: 'post',
data: data
}, function (requestErr: braintree.BraintreeError, response: { creditCards: any[]; }) {
if (requestErr) { throw new Error(requestErr.message); }
console.log('Got nonce:', response.creditCards[0].nonce);
});
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16pt',
'color': '#3A3A3A'
},
'.number': {
'font-family': 'monospace'
},
'.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number'
},
cvv: {
selector: '#cvv',
type: 'password'
},
expirationMonth: {
selector: '#expiration-month',
select: {
options: ["01 - Jan", "02 - Feb", "03 - Mar", "04 - Apr", "05 - May", "06 - Jun", "07 - Jul", "08 - Aug", "09 - Sep", "10 - Oct", "11 - Nov", "12 - Dec"]
}
},
expirationYear: {
selector: '#expiration-year',
select: true
}
}
}, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: any) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let form = new HTMLFormElement();
form.addEventListener('submit', function (event: Event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
switch (tokenizeErr.code) {
case 'HOSTED_FIELDS_FIELDS_EMPTY':
console.error('All fields are empty! Please fill out the form.');
break;
case 'HOSTED_FIELDS_FIELDS_INVALID':
console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
break;
case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
console.error('Tokenization failed server side. Is the card valid?');
break;
case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
console.error('Network error occurred when tokenizing.');
break;
default:
console.error('Something bad happened!', tokenizeErr);
}
return;
}
// Put `payload.nonce` into the `payment-method-nonce` input, and then
// submit the form. Alternatively, you could send the nonce to your server
// with AJAX.
(document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce;
form.submit();
});
}, false);
hostedFieldsInstance.on('focus', function (event: braintree.HostedFieldsStateObject) {
console.log(event.emittedBy, 'has been focused');
});
hostedFieldsInstance.teardown(function (teardownErr: braintree.BraintreeError) {
if (teardownErr) {
console.error('Could not tear down Hosted Fields!');
} else {
console.info('Hosted Fields has been torn down!');
}
});
hostedFieldsInstance.tokenize({
vault: true
}, function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
} else {
console.log('Got nonce:', payload.nonce);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
return;
}
// some time later...
hostedFieldsInstance.removeClass('number', 'custom-class');
});
hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: braintree.BraintreeError) {
if (placeholderErr) {
console.error(placeholderErr);
}
});
hostedFieldsInstance.on('cardTypeChange', function (event: braintree.HostedFieldsStateObject) {
// Update the placeholder value if there is only one possible card type
if (event.cards.length === 1) {
braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: braintree.BraintreeError) {
if (placeholderErr) {
// Handle errors, such as invalid field name
console.error(placeholderErr);
}
});
}
});
hostedFieldsInstance.clear('number', function (clearErr: braintree.BraintreeError) {
if (clearErr) {
console.error(clearErr);
}
});
hostedFieldsInstance.clear('number');
hostedFieldsInstance.clear('cvv');
hostedFieldsInstance.clear('expirationDate');
var state = braintree.hostedFields.getState();
var formValid = Object.keys(state.fields).every(function (key) {
return state.fields[key].isValid;
});
});
braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: any) {
if (createErr) {
// Handle error in client creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var paymentRequest = braintree.applePay.createPaymentRequest(request);
console.log(paymentRequest);
// { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new braintree.ApplePaySession(1, request);
session.onvalidatemerchant = function (event: { validationURL: string }) {
braintree.applePay.performValidation({
validationURL: event.validationURL
}, function (err, validationData) {
if (err) {
console.error(err);
session.abort();
return;
}
session.completeMerchantValidation(validationData);
});
};
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new braintree.ApplePaySession(1, request);
session.onpaymentauthorized = function (event) {
braintree.applePay.tokenize({
token: event.payment.token
}, function (err, tokenizedPayload) {
if (err) {
session.completePayment(braintree.ApplePayStatusCodes.STATUS_FAILURE);
return;
}
session.completePayment(braintree.ApplePayStatusCodes.STATUS_SUCCESS);
// Send the tokenizedPayload to your server.
});
};
});
braintree.paypal.create({
client: clientInstance
}, function (createErr, paypalInstance) {
if (createErr) {
if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
console.error('This browser is not supported.');
} else {
console.error('Error!', createErr);
}
}
let button = new HTMLButtonElement();
button.addEventListener('click', function () {
// Disable the button so that we don't attempt to open multiple popups.
button.setAttribute('disabled', 'disabled');
// Because PayPal tokenization opens a popup, this must be called
// as a result of a user action, such as a button click.
paypalInstance.tokenize({
flow: 'vault' // Required
// Any other tokenization options
}, function (tokenizeErr: braintree.BraintreeError, payload: braintree.PayPalTokenizePayload) {
button.removeAttribute('disabled');
if (tokenizeErr) {
// Handle tokenization errors or premature flow closure
switch (tokenizeErr.code) {
case 'PAYPAL_POPUP_CLOSED':
console.error('Customer closed PayPal popup.');
break;
case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
break;
case 'PAYPAL_FLOW_FAILED':
console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
break;
default:
console.error('Error!', tokenizeErr);
}
} else {
// Submit payload.nonce to your server
}
});
});
});
braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
if (createErr) {
console.error(createErr);
return;
}
unionpayInstance.fetchCapabilities({
card: {
number: '4111111111111111'
}
}, function (fetchErr: braintree.BraintreeError, cardCapabilities: braintree.UnionPayFetchCapabilitiesPayload) {
if (fetchErr) {
console.error(fetchErr);
return;
}
if (cardCapabilities.isUnionPay) {
if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
// Braintree cannot process this UnionPay card.
// Ask the user for a different card.
return;
}
if (cardCapabilities.isDebit) {
// CVV and expiration date are not required
} else {
// CVV and expiration date are required
}
// Show mobile phone number field for enrollment
}
});
unionpayInstance.enroll({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038'
},
mobile: {
countryCode: '62',
number: '111111111111'
}
}, function (enrollErr: braintree.BraintreeError, response: braintree.UnionPayEnrollPayload) {
if (enrollErr) {
console.error(enrollErr);
return;
}
if (response.smsCodeRequired) {
// If smsCodeRequired, wait for SMS auth code from customer
// Then use response.enrollmentId during {@link UnionPay#tokenize}
} else {
// SMS code is not required from the user.
// {@link UnionPay#tokenize} can be called immediately
}
});
let enrollResponse: {
enrollmentId: string
};
unionpayInstance.tokenize({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038',
cvv: '123'
},
enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
}, function (tokenizeErr: braintree.BraintreeError, response: braintree.UnionPayTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// Send response.nonce to your server
});
unionpayInstance.teardown(function (teardownErr: braintree.BraintreeError) {
if (teardownErr) {
console.error('Could not tear down UnionPay.');
} else {
console.log('UnionPay has been torn down.');
}
});
});
});
let existingNonce = "fake-valid-nonce";
let submitNonceToServer: (nonce: string) => void;
braintree.threeDSecure.verifyCard({
nonce: existingNonce,
amount: 123.45,
addFrame: function (err, iframe) {
// Set up your UI and add the iframe.
let my3DSContainer = document.createElement('div');
my3DSContainer.appendChild(iframe);
document.body.appendChild(my3DSContainer);
},
removeFrame: function () {
let my3DSContainer = document.createElement('div');
// Remove UI that you added in addFrame.
document.body.removeChild(my3DSContainer);
}
}, function (err: braintree.BraintreeError, payload: braintree.ThreeDSecureVerifyPayload) {
if (err) {
console.error(err);
return;
}
if (payload.liabilityShifted) {
// Liablity has shifted
submitNonceToServer(payload.nonce);
} else if (payload.liabilityShiftPossible) {
// Liablity may still be shifted
// Decide if you want to submit the nonce
} else {
// Liablity has not shifted and will not shift
// Decide if you want to submit the nonce
}
});
braintree.threeDSecure.cancelVerifyCard(function (err: braintree.BraintreeError, verifyPayload: braintree.ThreeDSecureVerifyPayload) {
if (err) {
// Handle error
console.log(err.message); // No verification payload available
return;
}
verifyPayload.nonce; // The nonce returned from the 3ds lookup call
verifyPayload.liabilityShifted; // boolean
verifyPayload.liabilityShiftPossible; // boolean
});

View File

@@ -4,10 +4,10 @@ let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiO
braintree.client.create({
authorization: clientToken
}, function (error: BraintreeError, clientInstance: any) {
}, function (error: braintree.BraintreeError, clientInstance: any) {
var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
var data: { creditCard: BraintreeWeb.CreditCardInfo } = {
var data: { creditCard: braintree.CreditCardInfo } = {
creditCard: {
number: form['cc-number'].value,
cvv: form['cc-cvv'].value,
@@ -22,7 +22,7 @@ braintree.client.create({
endpoint: 'payment_methods/credit_cards',
method: 'post',
data: data
}, function (requestErr: BraintreeError, response: { creditCards: any[]; }) {
}, function (requestErr: braintree.BraintreeError, response: { creditCards: any[]; }) {
if (requestErr) { throw new Error(requestErr.message); }
console.log('Got nonce:', response.creditCards[0].nonce);
@@ -62,7 +62,7 @@ braintree.client.create({
select: true
}
}
}, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) {
}, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: any) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
@@ -75,7 +75,7 @@ braintree.client.create({
form.addEventListener('submit', function (event: Event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
hostedFieldsInstance.tokenize(function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
switch (tokenizeErr.code) {
@@ -105,11 +105,11 @@ braintree.client.create({
});
}, false);
hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) {
hostedFieldsInstance.on('focus', function (event: braintree.HostedFieldsStateObject) {
console.log(event.emittedBy, 'has been focused');
});
hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) {
hostedFieldsInstance.teardown(function (teardownErr: braintree.BraintreeError) {
if (teardownErr) {
console.error('Could not tear down Hosted Fields!');
} else {
@@ -119,7 +119,7 @@ braintree.client.create({
hostedFieldsInstance.tokenize({
vault: true
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
}, function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
} else {
@@ -127,13 +127,13 @@ braintree.client.create({
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
return;
@@ -143,16 +143,16 @@ braintree.client.create({
hostedFieldsInstance.removeClass('number', 'custom-class');
});
hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) {
hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: braintree.BraintreeError) {
if (placeholderErr) {
console.error(placeholderErr);
}
});
hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) {
hostedFieldsInstance.on('cardTypeChange', function (event: braintree.HostedFieldsStateObject) {
// Update the placeholder value if there is only one possible card type
if (event.cards.length === 1) {
braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) {
braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: braintree.BraintreeError) {
if (placeholderErr) {
// Handle errors, such as invalid field name
console.error(placeholderErr);
@@ -161,7 +161,7 @@ braintree.client.create({
}
});
hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) {
hostedFieldsInstance.clear('number', function (clearErr: braintree.BraintreeError) {
if (clearErr) {
console.error(clearErr);
}
@@ -178,7 +178,7 @@ braintree.client.create({
});
});
braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) {
braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: any) {
if (createErr) {
// Handle error in client creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
@@ -209,7 +209,7 @@ braintree.client.create({
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
var session = new braintree.ApplePaySession(1, request);
session.onvalidatemerchant = function (event: { validationURL: string }) {
braintree.applePay.performValidation({
@@ -234,17 +234,17 @@ braintree.client.create({
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
var session = new braintree.ApplePaySession(1, request);
session.onpaymentauthorized = function (event) {
braintree.applePay.tokenize({
token: event.payment.token
}, function (err, tokenizedPayload) {
if (err) {
session.completePayment(ApplePayStatusCodes.STATUS_FAILURE);
session.completePayment(braintree.ApplePayStatusCodes.STATUS_FAILURE);
return;
}
session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS);
session.completePayment(braintree.ApplePayStatusCodes.STATUS_SUCCESS);
// Send the tokenizedPayload to your server.
});
@@ -273,7 +273,7 @@ braintree.client.create({
paypalInstance.tokenize({
flow: 'vault' // Required
// Any other tokenization options
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) {
}, function (tokenizeErr: braintree.BraintreeError, payload: braintree.PayPalTokenizePayload) {
button.removeAttribute('disabled');
if (tokenizeErr) {
@@ -309,7 +309,7 @@ braintree.client.create({
card: {
number: '4111111111111111'
}
}, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) {
}, function (fetchErr: braintree.BraintreeError, cardCapabilities: braintree.UnionPayFetchCapabilitiesPayload) {
if (fetchErr) {
console.error(fetchErr);
return;
@@ -342,7 +342,7 @@ braintree.client.create({
countryCode: '62',
number: '111111111111'
}
}, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) {
}, function (enrollErr: braintree.BraintreeError, response: braintree.UnionPayEnrollPayload) {
if (enrollErr) {
console.error(enrollErr);
return;
@@ -370,7 +370,7 @@ braintree.client.create({
},
enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
}, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) {
}, function (tokenizeErr: braintree.BraintreeError, response: braintree.UnionPayTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
@@ -379,7 +379,7 @@ braintree.client.create({
// Send response.nonce to your server
});
unionpayInstance.teardown(function (teardownErr: BraintreeError) {
unionpayInstance.teardown(function (teardownErr: braintree.BraintreeError) {
if (teardownErr) {
console.error('Could not tear down UnionPay.');
} else {
@@ -407,7 +407,7 @@ braintree.threeDSecure.verifyCard({
// Remove UI that you added in addFrame.
document.body.removeChild(my3DSContainer);
}
}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) {
}, function (err: braintree.BraintreeError, payload: braintree.ThreeDSecureVerifyPayload) {
if (err) {
console.error(err);
return;
@@ -425,7 +425,7 @@ braintree.threeDSecure.verifyCard({
}
});
braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) {
braintree.threeDSecure.cancelVerifyCard(function (err: braintree.BraintreeError, verifyPayload: braintree.ThreeDSecureVerifyPayload) {
if (err) {
// Handle error
console.log(err.message); // No verification payload available
@@ -435,4 +435,4 @@ braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPay
verifyPayload.nonce; // The nonce returned from the 3ds lookup call
verifyPayload.liabilityShifted; // boolean
verifyPayload.liabilityShiftPossible; // boolean
});
});

View File

@@ -18,6 +18,7 @@
},
"files": [
"index.d.ts",
"braintree-web-tests.ts"
"test/web.ts",
"test/node.ts"
]
}
}

View File

@@ -68,6 +68,8 @@ export class ObjectId {
static isValid(id: number | string | ObjectId): boolean;
constructor(id?: number | string | ObjectId);
toHexString(): string;
getTimestamp(): Date;
}
export type ObjectID = ObjectId;
export class BSONRegExp {

View File

@@ -1,8 +1,6 @@
import blackhole = require("bunyan-blackhole");
var logsLaboursLost = blackhole("lost");
const logsLaboursLost = blackhole("lost");
const rotten = new Error("Something is rotten in the state of Denmark");
@@ -20,7 +18,5 @@ logsLaboursLost.info({play: "Much Ado About Nothing"}, "Let me be that I am and
logsLaboursLost.warn({play: "All's Well That Ends Well"}, "Love all, trust a few, do wrong to none");
logsLaboursLost.error({play: "All's Well That Ends Well"}, "Love all, trust a few, do wrong to none");
var hamlet = logsLaboursLost.child({play: "Hamlet"});
const hamlet = logsLaboursLost.child({play: "Hamlet"});
hamlet.info({character: "Polonius"}, "Though this be madness, yet there is method in't");

View File

@@ -1,4 +1,4 @@
// Type definitions for canvas-gauges v2.0.8
// Type definitions for canvas-gauges v2.1.3
// Project: https://github.com/Mikhus/canvas-gauges
// Definitions by: Mikhus <https://github.com/Mikhus>
// Definitions: https://github.com/Mikhus/DefinitelyTyped
@@ -20,6 +20,10 @@ declare namespace CanvasGauges {
color: string
}
export interface EventListeners {
[key: string]: Function|[Function]
}
export type MajorTicks = string[]|number[];
export interface GenericOptions {
@@ -30,6 +34,7 @@ declare namespace CanvasGauges {
maxValue?: number,
value?: number,
units?: string|boolean,
exactTicks?: boolean,
majorTicks?: MajorTicks,
minorTicks?: number,
strokeTicks?: boolean,
@@ -37,6 +42,8 @@ declare namespace CanvasGauges {
animateOnInit?: boolean,
title?: string|boolean,
borders?: boolean,
numbersMargin?: number,
listeners?: EventListeners,
valueInt?: number,
valueDec?: number,
majorTicksInt?: number,
@@ -45,6 +52,7 @@ declare namespace CanvasGauges {
animationDuration?: number,
animationRule?: string|AnimationRule,
colorPlate?: string,
colorPlateEnd?: string,
colorMajorTicks?: string,
colorMinorTicks?: string,
colorTitle?: string,
@@ -67,6 +75,26 @@ declare namespace CanvasGauges {
colorValueBoxShadow?: string,
colorNeedleShadowUp?: string,
colorNeedleShadowDown?: string,
colorBarStroke?: string,
colorBar?: string,
colorBarProgress?: string,
colorBarShadow?: string,
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number,
fontTitleStyle?: FontStyle,
fontValueStyle?: FontStyle,
fontUnitsStyle?: FontStyle,
fontNumbersStyle?: FontStyle,
fontTitleWeight?: FontWeight,
fontValueWeight?: FontWeight,
fontUnitsWeight?: FontWeight,
fontNumbersWeight?: FontWeight,
needle?: boolean,
needleShadow?: boolean,
needleType?: string,
@@ -85,22 +113,10 @@ declare namespace CanvasGauges {
valueBoxBorderRadius?: number,
highlights?: Highlight[],
highlightsWidth?: number,
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number,
fontTitleStyle?: FontStyle,
fontValueStyle?: FontStyle,
fontUnitsStyle?: FontStyle,
fontNumbersStyle?: FontStyle,
fontTitleWeight?: FontWeight,
fontValueWeight?: FontWeight,
fontUnitsWeight?: FontWeight,
fontNumbersWeight?: FontWeight
barWidth?: number,
barStrokeWidth?: number,
barProgress?: boolean,
barShadow?: number
}
export interface RadialGaugeOptions extends GenericOptions {
@@ -113,19 +129,14 @@ declare namespace CanvasGauges {
needleCircleSize?: number,
needleCircleInner?: boolean,
needleCircleOuter?: boolean,
animationTarget?: string
animationTarget?: string,
useMinPath?: boolean
}
export interface LinearGaugeOptions extends GenericOptions {
borderRadius?: number,
barBeginCircle?: number,
barWidth?: number,
barStrokeWidth?: number,
barProgress?: boolean,
colorBar?: string,
colorBarEnd?: string,
colorBarStroke?: string,
colorBarProgress?: string,
colorBarProgressEnd?: string,
tickSide?: string,
needleSide?: string,
@@ -230,6 +241,7 @@ declare namespace CanvasGauges {
public canvas: SmartCanvas;
public animation: Animation;
public value: number;
public static readonly version: number;
constructor(options: GenericOptions);
@@ -238,6 +250,8 @@ declare namespace CanvasGauges {
public abstract draw(): BaseGauge;
public static initialize(type: string, options: GenericOptions): any;
public static fromElement(element: HTMLElement): any;
public static ensureValue(value: number): number;
}
export class RadialGauge extends BaseGauge {

View File

@@ -1,14 +1,11 @@
import chai = require('chai');
import chaiSubset = require('chai-subset');
chai.use(chaiSubset);
var expect = chai.expect;
var assert = chai.assert;
const { assert, expect } = chai;
function test_containSubset() {
var obj = {
const obj = {
a: 'b',
c: 'd',
e: {
@@ -34,7 +31,7 @@ function test_containSubset() {
}
function test_notContainSubset() {
var obj = {
const obj = {
a: 'b',
c: 'd',
e: {
@@ -50,7 +47,7 @@ function test_notContainSubset() {
}
function test_arrayContainSubset() {
var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
const list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).to.containSubset([{a: 'a', b: 'b'}]);
list.should.containSubset([{a: 'a', b: 'b'}]);
@@ -58,7 +55,7 @@ function test_arrayContainSubset() {
}
function test_arrayNotContainSubset() {
var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
const list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).not.to.containSubset([{a: 'a', b: 'bd'}]);
list.should.not.containSubset([{a: 'a', b: 'bd'}]);

View File

@@ -3,15 +3,15 @@ const charm = getCharm();
charm.pipe(process.stdout);
charm.reset();
var colors: getCharm.CharmColor[] = [ 'red', 'cyan', 'yellow', 'green', 'blue' ];
var text = 'Always after me lucky charms.';
const colors: getCharm.CharmColor[] = [ 'red', 'cyan', 'yellow', 'green', 'blue' ];
const text = 'Always after me lucky charms.';
var offset = 0;
var iv = setInterval(() => {
var y = 0, dy = 1;
for (var i = 0; i < 40; i++) {
var color = colors[(i + offset) % colors.length];
var c = text[(i + offset) % text.length];
let offset = 0;
const iv = setInterval(() => {
let y = 0, dy = 1;
for (let i = 0; i < 40; i++) {
const color = colors[(i + offset) % colors.length];
const c = text[(i + offset) % text.length];
charm
.move(1, dy)
.foreground(color)

View File

@@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -250,7 +250,7 @@ interface CheerioElement {
tagName: string;
type: string;
name: string;
attribs: Object;
attribs: {[attr: string]: string};
children: CheerioElement[];
childNodes: CheerioElement[];
lastChild: CheerioElement;
@@ -272,4 +272,4 @@ declare var cheerio:CheerioAPI;
declare module "cheerio" {
export = cheerio;
}
}

View File

@@ -3306,6 +3306,26 @@ declare namespace chrome.history {
* @since Chrome 5.
*/
declare namespace chrome.i18n {
/** Holds detected ISO language code and its percentage in the input string */
interface DetectedLanguage {
/** An ISO language code such as 'en' or 'fr'.
* For a complete list of languages supported by this method, see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}.
* For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */
language: string;
/** The percentage of the detected language */
percentage: number;
}
/** Holds detected language reliability and array of DetectedLanguage */
interface LanguageDetectionResult {
/** CLD detected language reliability */
isReliable: boolean;
/** Array of detectedLanguage */
languages: DetectedLanguage[];
}
/**
* Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage.
* @param callback The callback parameter should be a function that looks like this:
@@ -3324,6 +3344,12 @@ declare namespace chrome.i18n {
* @since Chrome 35.
*/
export function getUILanguage(): string;
/** Detects the language of the provided text using CLD.
* @param text User input string to be translated.
* @param callback The callback parameter should be a function that looks like this: function(object result) {...};
*/
export function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void;
}
////////////////////

View File

@@ -1,16 +1,16 @@
import * as Clipboard from 'clipboard';
var cb1 = new Clipboard('.btn');
var cb2 = new Clipboard(document.getElementById('id'), {
const cb1 = new Clipboard('.btn');
const cb2 = new Clipboard(document.getElementById('id'), {
action: elem => 'copy'
});
var cb3 = new Clipboard(document.querySelectorAll('query'), {
const cb3 = new Clipboard(document.querySelectorAll('query'), {
text: elem => null
});
var cb4 = new Clipboard('.btn', {
const cb4 = new Clipboard('.btn', {
target: elem => null
});
var cb5 = new Clipboard('.btn', {
const cb5 = new Clipboard('.btn', {
action: elem => 'copy',
target: elem => null
});
@@ -25,4 +25,3 @@ cb2.on('success', e => {
e.clearSelection();
});
cb2.on('error', e => { });

View File

@@ -54,4 +54,4 @@ declare namespace Clipboard {
export = Clipboard;
export as namespace Clipboard;
export as namespace Clipboard;

View File

@@ -89,4 +89,4 @@ myCalendar
.setEvents([])
.addEvents([])
.removeEvents(event => event.id === 'idToRemove')
.destroy();
.destroy();

View File

@@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -3,9 +3,9 @@ import * as http from 'http';
const server = http.createServer((req, res) => {
const cookies = new Cookies(req, res);
let unsigned: string,
signed: string,
tampered: string;
let unsigned: string;
let signed: string;
let tampered: string;
if (req.url === "/set") {
cookies

View File

@@ -1,33 +1,21 @@
// examples taken from https://github.com/litehelpers/Cordova-sqlite-storage
function echoTestFunction() {
function successCallback(value: string) {
}
function errorCallback() {
}
function successCallback(value: string) {}
function errorCallback() {}
window.sqlitePlugin.echoTest(successCallback, errorCallback);
}
function selfTestFunction() {
function successCallback() {
}
function errorCallback() {
}
function successCallback() {}
function errorCallback() {}
window.sqlitePlugin.selfTest(successCallback, errorCallback);
}
function openingDatabase() {
function successcb(db: SQLitePlugin.Database) {
function successcb(db: SQLitePlugin.Database) {}
function errorcb(err: Error) {}
}
function errorcb(err: Error) {
}
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);
var db = window.sqlitePlugin.openDatabase({name: 'my.db', iosDatabaseLocation: 'Library'}, successcb, errorcb);
let db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);
db = window.sqlitePlugin.openDatabase({name: 'my.db', iosDatabaseLocation: 'Library'}, successcb, errorcb);
}
function openingDatabase2() {
@@ -104,7 +92,7 @@ function sampleWithPRAGMA() {
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
const db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
db.transaction(tx => {
tx.executeSql('DROP TABLE IF EXISTS test_table');
@@ -134,14 +122,13 @@ function sampleWithPRAGMA() {
}
}
function sampleWithTransactionLevelNesting() {
// Wait for Cordova to load
document.addEventListener('deviceready', onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
const db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
db.transaction(tx => {
tx.executeSql('DROP TABLE IF EXISTS test_table');
@@ -155,7 +142,6 @@ function sampleWithTransactionLevelNesting() {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, (tx, e) => {
console.log("ERROR: " + e.message);
});
@@ -163,18 +149,12 @@ function sampleWithTransactionLevelNesting() {
}
}
function dbClose(db: SQLitePlugin.Database) {
function successcb() {
}
function errorcb(err: Error) {
}
function successcb() {}
function errorcb(err: Error) {}
db.close(successcb, errorcb);
db.transaction(tx => {
tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], (tx, res) => {
console.log('got stringlength: ' + res.rows.item(0).stringlength);
@@ -193,21 +173,16 @@ function dbClose(db: SQLitePlugin.Database) {
}
function deleteDatabase() {
function successcb() {
}
function errorcb(err: Error) {
}
function successcb() {}
function errorcb(err: Error) {}
window.sqlitePlugin.deleteDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);
}
function quickInstallationTest() {
window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, db => {
db.executeSql("select length('tenletters') as stringlength", [], res => {
var stringlength = res.rows.item(0).stringlength;
const stringlength = res.rows.item(0).stringlength;
console.log('got stringlength: ' + stringlength);
// document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength;
});

View File

@@ -65,4 +65,3 @@ declare namespace SQLitePlugin {
echoTest(ok?: (value: string) => void, error?: (msg: string) => void): void;
}
}

View File

@@ -49,87 +49,68 @@ export interface Console {
* Forces invocations of this function to always have this refer to the class instance,
* even if the function is passed around or would otherwise lose its this context. e.g. var fn = context.method;
*/
declare var autobind: Function;
export const autobind: Function;
/**
* Marks a property or method as not being writable.
*/
declare var readonly: PropertyOrMethodDecorator;
export const readonly: PropertyOrMethodDecorator;
/**
* Checks that the marked method indeed overrides a function with the same signature somewhere on the prototype chain.
*/
declare var override: MethodDecorator;
export const override: MethodDecorator;
/**
* Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading.
*/
declare var deprecate: Deprecate;
export const deprecate: Deprecate;
/**
* Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading.
*/
declare var deprecated: Deprecate;
export const deprecated: Deprecate;
/**
* Creates a new debounced function which will be invoked after wait milliseconds since the time it was invoked. Default timeout is 300 ms.
*/
declare var debounce: (wait: number) => MethodDecorator;
export function debounce(wait: number): MethodDecorator;
/**
* Creates a new throttled function which will be invoked in every wait milliseconds. Default timeout is 300 ms.
*/
declare var throttle: (wait: number, options?: ThrottleOptions) => MethodDecorator;
export function throttle(wait: number, options?: ThrottleOptions): MethodDecorator;
/**
* Suppresses any JavaScript console.warn() call while the decorated function is called. (i.e. on the stack)
*/
declare var suppressWarnings: MethodDecorator;
export const suppressWarnings: MethodDecorator;
/**
* Marks a property or method as not being enumerable.
*/
declare var nonenumerable: PropertyOrMethodDecorator;
export const nonenumerable: PropertyOrMethodDecorator;
/**
* Marks a property or method as not being writable.
*/
declare var nonconfigurable: PropertyOrMethodDecorator;
export const nonconfigurable: PropertyOrMethodDecorator;
/**
* Initial implementation included, likely slow. WIP.
*/
declare var memoize: MethodDecorator;
export const memoize: MethodDecorator;
/**
* Immediately applies the provided function and arguments to the method, allowing you to wrap methods with arbitrary helpers like those provided by lodash.
* The first argument is the function to apply, all further arguments will be passed to that decorating function.
*/
declare var decorate: (func: Function, ...args: any[]) => MethodDecorator;
export function decorate(func: Function, ...args: any[]): MethodDecorator;
/**
* Prevents a property initializer from running until the decorated property is actually looked up.
* Useful to prevent excess allocations that might otherwise not be used, but be careful not to over-optimize things.
*/
declare var lazyInitialize: PropertyDecorator;
export const lazyInitialize: PropertyDecorator;
/**
* Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments.
* Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally.
*/
declare var mixin: (...mixins: any[]) => ClassDecorator;
export function mixin(...mixins: any[]): ClassDecorator;
/**
* Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments.
* Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally.
*/
declare var mixins: (...mixins: any[]) => ClassDecorator;
export function mixins(...mixins: any[]): ClassDecorator;
/**
* Uses console.time and console.timeEnd to provide function timings with a unique label whose default prefix is ClassName.method. Supply a first argument to override the prefix:
*/
declare var time: (label: string, console?: Console) => MethodDecorator;
export {
autobind,
readonly,
override,
deprecate,
deprecated,
debounce,
throttle,
suppressWarnings,
nonenumerable,
nonconfigurable,
memoize,
decorate,
lazyInitialize,
mixin,
mixins,
time,
};
export function time(label: string, console?: Console): MethodDecorator;

View File

@@ -2,6 +2,6 @@
"extends": "../tslint.json",
"rules": {
"callable-types": false,
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -927,7 +927,7 @@ declare module "core-js/fn/function" {
export = Function;
}
declare module "core-js/fn/function/has-instance" {
const hasInstance: (value: any) => boolean;
function hasInstance(value: any): boolean;
export = hasInstance;
}
declare module "core-js/fn/function/name" {
@@ -1706,7 +1706,7 @@ declare module "core-js/library/fn/function" {
export = Function;
}
declare module "core-js/library/fn/function/has-instance" {
const hasInstance: (value: any) => boolean;
function hasInstance(value: any): boolean;
export = hasInstance;
}
declare module "core-js/library/fn/function/name" {

View File

@@ -1,6 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
"ban-types": false
}
}

View File

@@ -4,7 +4,6 @@ cpy(['src/*.png', '!src/goat.png'], 'dist').then(() => {
console.log('files copied');
});
cpy('foo.js', 'destination', {
rename: basename => `prefix-${basename}`
});
});

View File

@@ -4,4 +4,7 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = cpy;
declare function cpy(src: string | string[], dest: string, opts?: { cwd?: string, parents?: boolean, rename?: (s: string) => string }): Promise<void>;
declare function cpy(
src: string | string[],
dest: string,
opts?: { cwd?: string, parents?: boolean, rename?(s: string): string }): Promise<void>;

View File

@@ -7,7 +7,6 @@ const c = new Croppie(document.getElementById('item'), {
enableOrientation: false,
});
c.bind({
url: 'demo/demo-2.jpg',
orientation: 4,

View File

@@ -27,7 +27,6 @@ export default class Croppie {
destroy(): void;
}
export type CropType = 'square' | 'circle';
export type Format = 'jpeg' | 'png' | 'webp';

View File

@@ -1,20 +1,21 @@
import parse = require('csv-parse');
function callbackAPITest() {
var input = '#Welcome\n"1","2","3","4"\n"a","b","c","d"';
const input = '#Welcome\n"1","2","3","4"\n"a","b","c","d"';
parse(input, {comment: '#'}, (err, output) => {
output.should.eql([ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]);
});
}
function streamAPITest() {
let output: string[][] = [];
const output: string[][] = [];
// Create the parser
var parser = parse({delimiter: ':'});
let record: string[];
const parser = parse({delimiter: ':'});
// Use the writable stream api
parser.on('readable', () => {
while (record = parser.read()) {
while (true) {
const record = parser.read();
if (!record) break;
output.push(record);
}
});
@@ -35,12 +36,12 @@ function streamAPITest() {
import fs = require('fs');
function pipeFunctionTest() {
var transform = require('stream-transform');
const transform = require('stream-transform');
var output: any = [];
var parser = parse({delimiter: ':'})
var input = fs.createReadStream('/etc/passwd');
var transformer = transform((record: any[], callback: any) => {
const output: any = [];
const parser = parse({delimiter: ':'});
const input = fs.createReadStream('/etc/passwd');
const transformer = transform((record: any[], callback: any) => {
setTimeout(() => {
callback(null, record.join(' ') + '\n');
}, 500);
@@ -51,8 +52,7 @@ function pipeFunctionTest() {
import parseSync = require('csv-parse/lib/sync');
function syncApiTest() {
var input = '"key_1","key_2"\n"value 1","value 2"';
var records = parseSync(input, {columns: true});
const input = '"key_1","key_2"\n"value 1","value 2"';
const records = parseSync(input, {columns: true});
records.should.eql([{ key_1: 'value 1', key_2: 'value 2' }]);
}

View File

@@ -33,16 +33,16 @@ declare namespace parse {
* special constants are 'auto', 'unix', 'mac', 'windows', 'unicode';
* defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
rowDelimiter?: string;
rowDelimiter?: string;
/**
* Optional character surrounding a field, one character only, defaults to double quotes.
*/
quote?: string
quote?: string;
/**
* Set the escape character, one character only, defaults to double quotes.
*/
escape?: string
escape?: string;
/**
* List of fields as an array,
@@ -55,62 +55,62 @@ declare namespace parse {
/**
* Treat all the characters after this one as a comment, default to '' (disabled).
*/
comment?: string
comment?: string;
/**
* Name of header-record title to name objects by.
*/
objname?: string
objname?: string;
/**
* Preserve quotes inside unquoted field.
*/
relax?: boolean
relax?: boolean;
/**
* Discard inconsistent columns count, default to false.
*/
relax_column_count?: boolean
relax_column_count?: boolean;
/**
* Dont generate empty values for empty lines.
*/
skip_empty_lines?: boolean
skip_empty_lines?: boolean;
/**
* Maximum numer of characters to be contained in the field and line buffers before an exception is raised,
* used to guard against a wrong delimiter or rowDelimiter,
* default to 128000 characters.
*/
max_limit_on_data_read?: number
max_limit_on_data_read?: number;
/**
* If true, ignore whitespace immediately around the delimiter, defaults to false.
* Does not remove whitespace in a quoted field.
*/
trim?: boolean
trim?: boolean;
/**
* If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false.
* Does not remove whitespace in a quoted field.
*/
ltrim?: boolean
ltrim?: boolean;
/**
* If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false.
* Does not remove whitespace in a quoted field.
*/
rtrim?: boolean
rtrim?: boolean;
/**
* If true, the parser will attempt to convert read data types to native types.
*/
auto_parse?: boolean
auto_parse?: boolean;
/**
* If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option.
*/
auto_parse_date?: boolean
auto_parse_date?: boolean;
}
// TODO: what is this for?

View File

@@ -1 +1,6 @@
{ "extends": "../tslint.json" }
{
"extends": "../tslint.json",
"rules": {
"no-empty-interface": false
}
}

View File

@@ -183,7 +183,7 @@ declare namespace csvtojson {
* @param {string} str the string to convert
* @return {Converter} returns this object for chaining
*/
fromString(str: string): this
fromString(str: string): this;
/**
* Reads in a CSV from a string.
@@ -197,7 +197,7 @@ declare namespace csvtojson {
* @param {string} filePath the path to the CSV file
* @return {Converter} returns this object for chaining
*/
fromFile(filePath: string): this
fromFile(filePath: string): this;
/**
* Reads in a CSV from a file.
@@ -211,7 +211,7 @@ declare namespace csvtojson {
* @param {Stream} stream the stream
* @return {Converter} returns this object for chaining
*/
fromStream(stream: NodeJS.ReadableStream): this
fromStream(stream: NodeJS.ReadableStream): this;
/**
* Reads in a CSV from a stream.

View File

@@ -1 +1,6 @@
{ "extends": "../tslint.json" }
{
"extends": "../tslint.json",
"rules": {
"ban-types": false
}
}

View File

@@ -153,8 +153,8 @@ export function bisectRight(array: Date[], x: Date, lo?: number, hi?: number): n
export const bisect: typeof bisectRight;
export interface Bisector<T, U> {
left: (array: T[], x: U, lo?: number, hi?: number) => number;
right: (array: T[], x: U, lo?: number, hi?: number) => number;
left(array: T[], x: U, lo?: number, hi?: number): number;
right(array: T[], x: U, lo?: number, hi?: number): number;
}
export function bisector<T, U>(comparator: (a: T, b: U) => number): Bisector<T, U>;

View File

@@ -61,10 +61,10 @@ export interface Axis<Domain> {
(context: Selection<AxisContainerElement, any, any, any>): void;
/**
* Render the axis to the given context.
*
* @param context A transition defined on SVG containers (either SVG or G elements).
*/
* Render the axis to the given context.
*
* @param context A transition defined on SVG containers (either SVG or G elements).
*/
(context: TransitionLike<AxisContainerElement, any>): void;
/**
@@ -142,10 +142,10 @@ export interface Axis<Domain> {
tickArguments(args: [AxisTimeInterval, string]): this;
/**
* Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator.
*
* @param args An array with arguments suitable for the scale to be used for tick generation
*/
* Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator.
*
* @param args An array with arguments suitable for the scale to be used for tick generation
*/
tickArguments(args: any[]): this;
/**

View File

@@ -55,7 +55,6 @@ let circleDrag: d3Drag.DragBehavior<SVGCircleElement, CircleDatum, CircleDatum |
// This drag behavior will use a custom subject accessor to set the subject of the drag event
let circleCustomDrag: d3Drag.DragBehavior<SVGCircleElement, CircleDatum, CustomSubject | d3Drag.SubjectPosition>;
// create new drag behavior ------------------------------------------
circleDrag = d3Drag.drag<SVGCircleElement, CircleDatum>(); // Use short form method
@@ -99,7 +98,6 @@ filterFn = function(d) {
// chainable
circleDrag = circleDrag.filter(function(d, i, group) {
return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum
});
@@ -192,10 +190,8 @@ const wrongSelection: Selection<HTMLDivElement, any, any, any> = select<HTMLDivE
// Test Drag Event Interface
// -----------------------------------------------------------------------------
let e: d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.SubjectPosition> = event;
circleDrag = e.target; // target return drag behavior
const type: string = e.type;
@@ -224,7 +220,6 @@ handler = e.on('dragged');
// fails, handler with wrong datum type
// let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf<SVGCircleElement>)=> void) | undefined = e.on('dragged');
// -----------------------------------------------------------------------------
// Test dragDisable() and dragEnable()
// -----------------------------------------------------------------------------

View File

@@ -7,12 +7,10 @@
import { ArrayLike, Selection, ValueFn } from 'd3-selection';
// --------------------------------------------------------------------------
// Shared Type Definitions and Interfaces
// --------------------------------------------------------------------------
/**
* DraggedElementBaseType serves as an alias for the 'minimal' data type which can be selected
* without 'd3-drag' (and related code in 'd3-selection') trying to use properties internally which would otherwise not
@@ -20,7 +18,6 @@ import { ArrayLike, Selection, ValueFn } from 'd3-selection';
*/
export type DraggedElementBaseType = Element;
/**
* Container element type usable for mouse/touch functions
*/

View File

@@ -12,7 +12,6 @@ import * as d3Dsv from 'd3-dsv';
// Preperatory Steps
// ------------------------------------------------------------------------------------------
const csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38';
const tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38';
const pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38';
@@ -34,7 +33,6 @@ let parseMappedArray: d3Dsv.DSVParsedArray<ParsedTestObject>;
let parseRowsArray: string[][];
let parseRowsMappedArray: ParsedTestObject[];
let columns: string[];
let num: number;
let date: Date;
@@ -77,14 +75,12 @@ str = parseMappedArray[0].make;
str = parseMappedArray[0].model;
num = parseMappedArray[0].length;
// csvParseRows(...) ============================================================================
// without row mapper -----------------------------------------------------------------------
parseRowsArray = d3Dsv.csvParseRows(csvTestString);
str = parseRowsArray[0][0]; // 'Year' of first row
// date = parseRowsArray[0][0]; // fails, return value is string
@@ -158,14 +154,12 @@ str = parseMappedArray[0].make;
str = parseMappedArray[0].model;
num = parseMappedArray[0].length;
// tsvParseRows(...) ============================================================================
// without row mapper -----------------------------------------------------------------------
parseRowsArray = d3Dsv.tsvParseRows(tsvTestString);
str = parseRowsArray[0][0]; // 'Year' of first row
// date = parseRowsArray[0][0]; // fails, return value is string
@@ -244,14 +238,12 @@ str = parseMappedArray[0].make;
str = parseMappedArray[0].model;
num = parseMappedArray[0].length;
// parseRows(...) ============================================================================
// without row mapper -----------------------------------------------------------------------
parseRowsArray = dsv.parseRows(pipedTestString);
str = parseRowsArray[0][0]; // 'Year' of first row
// date = parseRowsArray[0][0]; // fails, return value is string

1
types/d3-dsv/tslint.json Normal file
View File

@@ -0,0 +1 @@
{ "extends": "../tslint.json" }

View File

@@ -1,8 +1,5 @@
import d3dsv = require("d3-dsv");
var csv = d3dsv(",");
var rows = csv.parse("a,b,c\n1,2,3\n4,5,6");
const csv = d3dsv(",");
const rows = csv.parse("a,b,c\n1,2,3\n4,5,6");

View File

@@ -4,11 +4,11 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */
declare var loader: (
/** the symbol used to seperate cells in the row.*/
declare function loader(
/** the symbol used to seperate cells in the row. */
delimiter: string,
/** example: "text/plain" */
encoding?: string) => D3Dsv;
encoding?: string): D3Dsv;
export = loader;
export as namespace d3_dsv;
@@ -16,21 +16,21 @@ export as namespace d3_dsv;
/** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */
interface D3Dsv {
/**
Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows.
The string is assumed to be RFC4180-compliant.
Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names;
these column names become the attributes on the returned objects.
For example, consider the following CSV file:
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
The resulting JavaScript array is:
[ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ]
*/
* Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows.
* The string is assumed to be RFC4180-compliant.
* Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names;
* these column names become the attributes on the returned objects.
* For example, consider the following CSV file:
*
* Year,Make,Model,Length
* 1997,Ford,E350,2.34
* 2000,Mercury,Cougar,2.38
*
* The resulting JavaScript array is:
*
* [ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},
* {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ]
*/
parse<TRow>(
table: string,
/** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */
@@ -38,42 +38,42 @@ interface D3Dsv {
): TRow[];
/**
Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows.
The string is assumed to be RFC4180-compliant.
Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header.
Each row is represented as an array rather than an object.
Rows may have variable length.
For example, consider the following CSV file:
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
The resulting JavaScript array is:
[ ["1997", "Ford", "E350", "2.34"],
["2000", "Mercury", "Cougar", "2.38"] ]
Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details.
*/
* Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows.
* The string is assumed to be RFC4180-compliant.
* Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header.
* Each row is represented as an array rather than an object.
* Rows may have variable length.
* For example, consider the following CSV file:
*
* 1997,Ford,E350,2.34
* 2000,Mercury,Cougar,2.38
* The resulting JavaScript array is:
*
* [ ["1997", "Ford", "E350", "2.34"],
* ["2000", "Mercury", "Cougar", "2.38"] ]
* Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details.
*/
parseRows<TRow>(
table: string,
/** coerce cells (strings) into different types or modify them. return null to strip this row from the output results.*/
/** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */
accessor?: (row: string[]) => TRow
): TRow[];
/**
Converts the specified array of rows into comma-separated values format, returning a string.
This operation is the reverse of parse.
Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,).
Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes.
Each row should be an object, and all object properties will be converted into fields.
For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows.
*/
* Converts the specified array of rows into comma-separated values format, returning a string.
* This operation is the reverse of parse.
* Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,).
* Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes.
*
* Each row should be an object, and all object properties will be converted into fields.
* For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows.
*/
format(rows: any[]): string;
/**
Converts the specified array of rows into comma-separated values format, returning a string.
This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,).
Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes.
*/
* Converts the specified array of rows into comma-separated values format, returning a string.
* This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,).
* Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes.
*/
formatRows(rows: any[]): string;
}

View File

@@ -23,7 +23,6 @@ t_out = d3Ease.easeCubicIn(t_in);
t_out = d3Ease.easeCubicOut(t_in);
t_out = d3Ease.easeCubicInOut(t_in);
let easePolyFactory: d3Ease.PolynomialEasingFactory;
easePolyFactory = d3Ease.easePoly;

View File

@@ -94,25 +94,24 @@ export interface PolynomialEasingFactory {
* Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1].
* If the exponent is not specified, it defaults to 3, equivalent to cubic.
*/
export var easePoly: PolynomialEasingFactory;
export const easePoly: PolynomialEasingFactory;
/**
* Polynomial easing/easing factory; raises t to the specified exponent.
* If the exponent is not specified, it defaults to 3, equivalent to cubicIn.
*/
export var easePolyIn: PolynomialEasingFactory;
export const easePolyIn: PolynomialEasingFactory;
/**
* Reverse polynomial easing/easing factory; equivalent to 1 - polyIn(1 - t).
* If the exponent is not specified, it defaults to 3, equivalent to cubicOut.
*/
export var easePolyOut: PolynomialEasingFactory;
export const easePolyOut: PolynomialEasingFactory;
/**
* Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1].
* If the exponent is not specified, it defaults to 3, equivalent to cubic.
*/
export var easePolyInOut: PolynomialEasingFactory;
export const easePolyInOut: PolynomialEasingFactory;
/**
* Symmetric sinusoidal easing; scales sinIn for t in [0, 0.5] and sinOut for t in [0.5, 1].
@@ -226,7 +225,6 @@ export function easeBounceOut(normalizedTime: number): number;
*/
export function easeBounceInOut(normalizedTime: number): number;
/**
* Anticipatory easing function factory
*/
@@ -249,26 +247,25 @@ export interface BackEasingFactory {
* Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1].
* The degree of overshoot is configurable; it not specified, it defaults to 1.70158.
*/
export var easeBack: BackEasingFactory;
export const easeBack: BackEasingFactory;
/**
* Anticipatory easing, like a dancer bending his knees before jumping off the floor.
* The degree of overshoot is configurable; it not specified, it defaults to 1.70158.
*/
export var easeBackIn: BackEasingFactory;
export const easeBackIn: BackEasingFactory;
/**
* Reverse anticipatory easing; equivalent to 1 - backIn(1 - t).
* The degree of overshoot is configurable; it not specified, it defaults to 1.70158.
*/
export var easeBackOut: BackEasingFactory;
export const easeBackOut: BackEasingFactory;
/**
* Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1].
* The degree of overshoot is configurable; it not specified, it defaults to 1.70158.
*/
export var easeBackInOut: BackEasingFactory;
export const easeBackInOut: BackEasingFactory;
/**
* Elastic easing function factory
@@ -287,11 +284,11 @@ export interface ElasticEasingFactory {
*/
amplitude(a: number): ElasticEasingFactory;
/**
* Returns a new elastic easing with the specified amplitude a.
* Defaults to 0.3,if not specified.
*
* @param p Period for elastic easing.
*/
* Returns a new elastic easing with the specified amplitude a.
* Defaults to 0.3,if not specified.
*
* @param p Period for elastic easing.
*/
period(p: number): ElasticEasingFactory;
}
@@ -300,25 +297,25 @@ export interface ElasticEasingFactory {
* The amplitude and period of the oscillation are configurable;
* if not specified, they default to 1 and 0.3, respectively.
*/
export var easeElastic: ElasticEasingFactory;
export const easeElastic: ElasticEasingFactory;
/**
* Elastic easing, like a rubber band.
* The amplitude and period of the oscillation are configurable;
* if not specified, they default to 1 and 0.3, respectively.
*/
export var easeElasticIn: ElasticEasingFactory;
export const easeElasticIn: ElasticEasingFactory;
/**
* Reverse elastic easing; equivalent to 1 - elasticIn(1 - t).
* The amplitude and period of the oscillation are configurable;
* if not specified, they default to 1 and 0.3, respectively.
*/
export var easeElasticOut: ElasticEasingFactory;
export const easeElasticOut: ElasticEasingFactory;
/**
* Symmetric elastic easing; scales elasticIn for t in [0, 0.5] and elasticOut for t in [0.5, 1].
* The amplitude and period of the oscillation are configurable;
* if not specified, they default to 1 and 0.3, respectively.
*/
export var easeElasticInOut: ElasticEasingFactory;
export const easeElasticInOut: ElasticEasingFactory;

View File

@@ -6,7 +6,6 @@
* are not intended as functional tests.
*/
import * as d3Force from 'd3-force';
// -------------------------------------------------------------------------------------
@@ -30,7 +29,6 @@ interface Graph {
links: SimLink[];
}
const graph: Graph = {
nodes: [
{ id: 'Myriel', group: 1, r: 5 },
@@ -112,7 +110,6 @@ forceCollide = d3Force.forceCollide<SimNode>((node, index, nodes) => {
return n.r;
});
// Configure Collision force -----------------------------------------------------------
let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number;
@@ -139,7 +136,6 @@ num = forceCollide.strength();
forceCollide = forceCollide.iterations(10);
num = forceCollide.iterations();
// Use Collision force -----------------------------------------------------------------
forceCollide.initialize(graph.nodes);
@@ -157,7 +153,6 @@ forceLink = d3Force.forceLink<SimNode, SimLink>();
// with link data
forceLink = d3Force.forceLink<SimNode, SimLink>(graph.links);
// Configure Link force -----------------------------------------------------------
let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number;
@@ -181,7 +176,6 @@ num = simLink.value;
num = simLink.d;
num = simLink.s;
// id (node id accessor)
forceLink = forceLink.id((node, index, nodes) => {
@@ -220,13 +214,11 @@ linkNumberAccessor = forceLink.strength();
forceLink = forceLink.iterations(10);
num = forceLink.iterations();
// Use Link force -----------------------------------------------------------------
forceLink.initialize(graph.nodes);
forceLink(0.1); // alpha
// ManyBody ============================================================================
// create ManyBody force --------------------------------------------------------------
@@ -255,7 +247,6 @@ simNodeNumberAccessor = forceCharge.strength();
forceCharge = forceCharge.theta(0.8);
num = forceCharge.theta();
// distanceMin
forceCharge = forceCharge.distanceMin(1);
@@ -266,13 +257,11 @@ num = forceCharge.distanceMin();
forceCharge = forceCharge.distanceMax(1000);
num = forceCharge.distanceMax();
// Use ManyBody force -----------------------------------------------------------------
forceCharge.initialize(graph.nodes);
forceCharge(0.1); // alpha
// ForceX ==============================================================================
// create ForceX force --------------------------------------------------------------
@@ -327,7 +316,6 @@ simNodeNumberAccessor = forcePosX.x();
forcePosX.initialize(graph.nodes);
forcePosX(0.1); // alpha
// ForceY ==============================================================================
// create ForceY force --------------------------------------------------------------
@@ -388,7 +376,6 @@ forcePosY(0.1); // alpha
// Create Force Simulation =============================================================
let nodeSimulation: d3Force.Simulation<SimNode, undefined>;
let nodeLinkSimulation: d3Force.Simulation<SimNode, SimLink>;
@@ -435,7 +422,6 @@ num = nodeLinkSimulation.alphaTarget();
nodeLinkSimulation = nodeLinkSimulation.velocityDecay(0.4);
num = nodeLinkSimulation.velocityDecay();
// force() -----------------------------------------------------------------------------
nodeSimulation = nodeSimulation.force('posx', forcePosX);
@@ -444,7 +430,6 @@ nodeSimulation.force('posy', forcePosY);
// Remove force
nodeSimulation = nodeSimulation.force('posx', null);
nodeLinkSimulation = nodeLinkSimulation.force('link', forceLink);
nodeLinkSimulation
@@ -480,7 +465,6 @@ simLinks = nodeLinkSimulation.force<d3Force.ForceLink<SimNode, SimLink>>('link')
// fLink = nodeLinkSimulation.force('link')!; // fails, as ForceLink specific properties are missing from 'generic' force
// on() --------------------------------------------------------------------------------
function drawLink(d: SimLink) {
@@ -502,7 +486,6 @@ function drawNode(d: SimNode) {
}
nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() {
const that: d3Force.Simulation<SimNode, SimLink> = this;
if (context) {

View File

@@ -3,7 +3,6 @@
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.0.4
// -----------------------------------------------------------------------
@@ -356,7 +355,6 @@ export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends
initialize?(nodes: NodeDatum[]): void;
}
// Centering ------------------------------------------------------------
/**
@@ -668,7 +666,6 @@ export interface ForceLink<NodeDatum extends SimulationNodeDatum, LinkDatum exte
* @param iterations Number of iterations.
*/
iterations(iterations: number): this;
}
/**

View File

@@ -597,7 +597,7 @@ const context: d3Geo.GeoContext = {
// geoTransform(...) ====================================================
const transformFunction: { stream: (s: d3Geo.GeoStream) => {} } = d3Geo.geoTransform({});
const transformFunction: { stream(s: d3Geo.GeoStream): {} } = d3Geo.geoTransform({});
interface CustomTranformProto extends d3Geo.GeoTransformPrototype {
a: number;
@@ -612,7 +612,7 @@ customTransformProto = {
a: 10
};
const t: { stream: (s: d3Geo.GeoStream) => (CustomTranformProto & d3Geo.GeoStream) } = d3Geo.geoTransform(customTransformProto);
const t: { stream(s: d3Geo.GeoStream): CustomTranformProto & d3Geo.GeoStream } = d3Geo.geoTransform(customTransformProto);
// geoIdentity() ========================================================

View File

@@ -699,14 +699,14 @@ export interface GeoProjection extends GeoStreamWrapper {
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature<GeoGeometryObjects, any>): this;
/**
* Sets the projections scale and translate to fit the specified geographic feature collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection).
*/
* Sets the projections scale and translate to fit the specified geographic feature collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection).
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): this;
/**
* Sets the projections scale and translate to fit the specified geographic geometry object in the center of the given extent.
@@ -719,14 +719,14 @@ export interface GeoProjection extends GeoStreamWrapper {
*/
fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this;
/**
* Sets the projections scale and translate to fit the specified geographic geometry collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection).
*/
* Sets the projections scale and translate to fit the specified geographic geometry collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection).
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection<GeoGeometryObjects>): this;
/**
@@ -1340,7 +1340,7 @@ export interface GeoTransformPrototype {
*
* @param methods An object with custom method implementations, which are used to create a transform projection.
*/
export function geoTransform<T extends GeoTransformPrototype>(methods: T): { stream: (s: GeoStream) => (T & GeoStream) };
export function geoTransform<T extends GeoTransformPrototype>(methods: T): { stream(s: GeoStream): T & GeoStream };
// geoIdentity() =================================================================
@@ -1382,14 +1382,14 @@ export interface GeoIdentityTranform extends GeoStreamWrapper {
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature<GeoGeometryObjects, any>): this;
/**
* Sets the projections scale and translate to fit the specified geographic feature collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection).
*/
* Sets the projections scale and translate to fit the specified geographic feature collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection).
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): this;
/**
* Sets the projections scale and translate to fit the specified geographic geometry object in the center of the given extent.
@@ -1402,14 +1402,14 @@ export interface GeoIdentityTranform extends GeoStreamWrapper {
*/
fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this;
/**
* Sets the projections scale and translate to fit the specified geographic geometry collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection).
*/
* Sets the projections scale and translate to fit the specified geographic geometry collection in the center of the given extent.
* Returns the projection.
*
* Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150.
*
* @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom.
* @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection).
*/
fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection<GeoGeometryObjects>): this;
/**

View File

@@ -92,7 +92,6 @@ linearScaleNumString = linearScaleNumString.domain(domainNumeric);
linearScaleNumString = linearScaleNumString.domain(domainNumbers);
domainNumbers = linearScaleNumString.domain();
// range(...) -----------------------------------------------------------------
linearScaleNumber = linearScaleNumber.range(rangeNumbers);
@@ -138,7 +137,6 @@ linearScaleNumString = linearScaleNumber.interpolate((a, b) => {
// nice(...) -----------------------------------------------------------------------
// chainable
linearScaleNumber = linearScaleNumber.nice();
linearScaleNumber = linearScaleNumber.nice(5);
@@ -180,7 +178,6 @@ powerScaleNumber = d3Scale.scalePow();
powerScaleString = d3Scale.scalePow<string>();
powerScaleNumString = d3Scale.scalePow<number, string>();
let squarerootScaleNumber: d3Scale.ScalePower<number, number>;
let squarerootScaleString: d3Scale.ScalePower<string, string>;
let squarerootScaleNumString: d3Scale.ScalePower<number, string>;
@@ -211,7 +208,6 @@ powerScaleNumString = powerScaleNumString.domain(domainNumeric);
powerScaleNumString = powerScaleNumString.domain(domainNumbers);
domainNumbers = powerScaleNumString.domain();
// range(...) -----------------------------------------------------------------
powerScaleNumber = powerScaleNumber.range(rangeNumbers);
@@ -282,7 +278,6 @@ const copiedPowerScale: d3Scale.ScalePower<number, string> = powerScaleNumString
// Logarithmic Scale Factory
// -------------------------------------------------------------------------------
// scaleLog() ---------------------------------------------------------------------
let logScaleNumber: d3Scale.ScaleLogarithmic<number, number>;
@@ -293,7 +288,6 @@ logScaleNumber = d3Scale.scaleLog();
logScaleString = d3Scale.scaleLog<string>();
logScaleNumString = d3Scale.scaleLog<number, string>();
// ScaleLogarithmic Interface ========================================================
// base --------------------------------------------------------------------
@@ -316,7 +310,6 @@ logScaleNumString = logScaleNumString.domain(domainNumeric);
logScaleNumString = logScaleNumString.domain(domainNumbers);
domainNumbers = logScaleNumString.domain();
// range(...) -----------------------------------------------------------------
logScaleNumber = logScaleNumber.range(rangeNumbers);
@@ -393,10 +386,8 @@ let identityScale: d3Scale.ScaleIdentity;
identityScale = d3Scale.scaleIdentity();
// ScaleIdentity Interface ========================================================
// domain(...) -----------------------------------------------------------------
identityScale = identityScale.domain(domainNumeric);
@@ -434,12 +425,10 @@ tickFormatNumberFn = identityScale.tickFormat(5, '+%');
outputNumber = identityScale(10);
// copy(...) -----------------------------------------------------------------
const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy();
// -------------------------------------------------------------------------------
// Time Scale Factories
// -------------------------------------------------------------------------------
@@ -454,7 +443,6 @@ localTimeScaleNumber = d3Scale.scaleTime();
localTimeScaleString = d3Scale.scaleTime<string>();
localTimeScaleNumString = d3Scale.scaleTime<number, string>();
let utcScaleNumber: d3Scale.ScaleTime<number, number>;
let utcScaleString: d3Scale.ScaleTime<string, string>;
let utcScaleNumString: d3Scale.ScaleTime<number, string>;
@@ -475,7 +463,6 @@ domainDates = localTimeScaleString.domain();
localTimeScaleNumString = localTimeScaleNumString.domain(domainDates);
domainDates = localTimeScaleNumString.domain();
// range(...) -----------------------------------------------------------------
localTimeScaleNumber = localTimeScaleNumber.range(rangeNumbers);
@@ -534,7 +521,6 @@ if (timeInterval !== null) {
ticksDates = localTimeScaleNumString.ticks(timeInterval);
}
// tickFormat(...) -----------------------------------------------------------------
tickFormatDateFn = localTimeScaleNumber.tickFormat();
@@ -543,7 +529,6 @@ if (timeInterval !== null) {
tickFormatDateFn = localTimeScaleNumber.tickFormat(timeInterval, '%I %p');
}
// (...) value mapping from domain to output -----------------------------------
outputNumber = localTimeScaleNumber(new Date(2016, 6, 4));
@@ -595,8 +580,6 @@ outputString = sequentialScaleColorString(10);
const copiedSequentialScale: d3Scale.ScaleSequential<string> = sequentialScaleColorString.copy();
// -------------------------------------------------------------------------------
// Color Interpolators for Sequential Scale Factory
// -------------------------------------------------------------------------------
@@ -619,7 +602,6 @@ colorInterpolator = d3Scale.interpolateCool;
colorInterpolator = d3Scale.interpolateCubehelixDefault;
// -------------------------------------------------------------------------------
// Quantize Scale Factory
// -------------------------------------------------------------------------------
@@ -632,7 +614,6 @@ let quantizeScaleString: d3Scale.ScaleQuantize<string>;
quantizeScaleNumber = d3Scale.scaleQuantize();
quantizeScaleString = d3Scale.scaleQuantize<string>();
// ScaleQuantize Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -649,7 +630,6 @@ rangeNumbers = quantizeScaleNumber.range();
quantizeScaleString = quantizeScaleString.range(['steelblue', 'brown']);
rangeStrings = quantizeScaleString.range();
// invertExtent(...) -----------------------------------------------------------------
numExtent = quantizeScaleNumber.invertExtent(500);
@@ -681,12 +661,10 @@ outputNumber = quantizeScaleNumber(0.51);
const copiedQuantizeScale: d3Scale.ScaleQuantize<number> = quantizeScaleNumber.copy();
// -------------------------------------------------------------------------------
// Quantile Scale Factory
// -------------------------------------------------------------------------------
// scaleQuantile() -----------------------------------------------------------------
let quantileScaleNumber: d3Scale.ScaleQuantile<number>;
@@ -695,7 +673,6 @@ let quantileScaleString: d3Scale.ScaleQuantile<string>;
quantileScaleNumber = d3Scale.scaleQuantile();
quantileScaleString = d3Scale.scaleQuantile<string>();
// ScaleQuantile Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -714,7 +691,6 @@ rangeNumbers = quantileScaleNumber.range();
quantileScaleString = quantileScaleString.range(['q25', 'q50', 'q75']);
rangeStrings = quantileScaleString.range();
// invertExtent(...) -----------------------------------------------------------------
numExtent = quantileScaleNumber.invertExtent(2);
@@ -733,7 +709,6 @@ outputNumber = quantileScaleNumber(0.51);
const copiedQuantileScale: d3Scale.ScaleQuantile<number> = quantileScaleNumber.copy();
// -------------------------------------------------------------------------------
// Threshold Scale Factory
// -------------------------------------------------------------------------------
@@ -746,7 +721,6 @@ let thresholdScaleNumberString: d3Scale.ScaleThreshold<number, string>;
thresholdScaleNumberNumber = d3Scale.scaleThreshold();
thresholdScaleNumberString = d3Scale.scaleThreshold<number, string>();
// ScaleThreshold Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -764,7 +738,6 @@ rangeNumbers = thresholdScaleNumberNumber.range();
thresholdScaleNumberString = thresholdScaleNumberString.range(['steelblue', 'seagreen', 'brown']);
rangeStrings = thresholdScaleNumberString.range();
// invertExtent(...) -----------------------------------------------------------------
numOrUndefinedExtent = thresholdScaleNumberNumber.invertExtent(100);
@@ -781,7 +754,6 @@ outputString = thresholdScaleNumberString(0.9);
const copiedThresholdScale: d3Scale.ScaleThreshold<number, string> = thresholdScaleNumberString.copy();
// -------------------------------------------------------------------------------
// Ordinal Scale Factory
// -------------------------------------------------------------------------------
@@ -794,7 +766,6 @@ let ordinalScaleStringNumber: d3Scale.ScaleOrdinal<string, number>;
ordinalScaleStringString = d3Scale.scaleOrdinal<string>();
ordinalScaleStringNumber = d3Scale.scaleOrdinal<string, number>();
// ScaleOrdinal Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -812,7 +783,6 @@ rangeStrings = ordinalScaleStringString.range();
ordinalScaleStringNumber = ordinalScaleStringNumber.range([-1, 0, 1]);
rangeNumbers = ordinalScaleStringNumber.range();
// unknown(...) and d3Scale.scaleImplicit --------------------------------------
const implicit: { name: 'implicit' } = d3Scale.scaleImplicit;
@@ -839,7 +809,6 @@ outputNumber = ordinalScaleStringNumber('negative');
const copiedOrdinalScale: d3Scale.ScaleOrdinal<string, number> = ordinalScaleStringNumber.copy();
// -------------------------------------------------------------------------------
// Band Scale Factory
// -------------------------------------------------------------------------------
@@ -852,7 +821,6 @@ let bandScaleCoercible: d3Scale.ScaleBand<StringCoercible>;
bandScaleString = d3Scale.scaleBand();
bandScaleCoercible = d3Scale.scaleBand<StringCoercible>();
// ScaleBand Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -870,12 +838,10 @@ let rangeExtent: [number, number] = bandScaleString.range();
bandScaleCoercible = bandScaleCoercible.range([0, 300]);
rangeExtent = bandScaleCoercible.range();
// rangeRound(...) -----------------------------------------------------------------
bandScaleString = bandScaleString.rangeRound([0, 300]);
// round(...) -----------------------------------------------------------------
bandScaleCoercible = bandScaleCoercible.round(true);
@@ -891,7 +857,6 @@ num = bandScaleString.paddingInner();
bandScaleString = bandScaleString.paddingOuter(0.1);
num = bandScaleString.paddingOuter();
// padding(...) -----------------------------------------------------------------
bandScaleString = bandScaleString.padding(0.1);
@@ -910,7 +875,6 @@ num = bandScaleString.bandwidth();
num = bandScaleString.step();
// (...) value mapping from domain to output -----------------------------------
outputNumberMaybe = bandScaleString('neutral');
@@ -921,7 +885,6 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative'));
const copiedBandScale: d3Scale.ScaleBand<StringCoercible> = bandScaleCoercible.copy();
// -------------------------------------------------------------------------------
// Point Scale Factory
// -------------------------------------------------------------------------------
@@ -934,7 +897,6 @@ let pointScaleCoercible: d3Scale.ScalePoint<StringCoercible>;
pointScaleString = d3Scale.scalePoint();
pointScaleCoercible = d3Scale.scalePoint<StringCoercible>();
// ScalePoint Interface ========================================================
// domain(...) -----------------------------------------------------------------
@@ -952,18 +914,15 @@ rangeExtent = pointScaleString.range();
pointScaleCoercible = pointScaleCoercible.range([0, 300]);
rangeExtent = pointScaleCoercible.range();
// rangeRound(...) -----------------------------------------------------------------
pointScaleString = pointScaleString.rangeRound([0, 300]);
// round(...) -----------------------------------------------------------------
pointScaleCoercible = pointScaleCoercible.round(true);
roundingFlag = pointScaleCoercible.round();
// padding(...) -----------------------------------------------------------------
pointScaleString = pointScaleString.padding(0.1);

View File

@@ -33,16 +33,15 @@ export interface InterpolatorFactory<T, U> {
* A helper interface for a continuous scale defined over a numeric domain.
*/
export interface ScaleContinuousNumeric<Range, Output> {
/**
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A numeric value from the domain.
*/
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A numeric value from the domain.
*/
(value: number | { valueOf(): number }): Output;
/**
@@ -163,7 +162,6 @@ export interface ScaleContinuousNumeric<Range, Output> {
* Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.
*/
copy(): this;
}
// -------------------------------------------------------------------------------
@@ -188,7 +186,6 @@ export interface ScaleContinuousNumeric<Range, Output> {
* convert the interpolated range element to a corresponding output element.
*/
export interface ScaleLinear<Range, Output> extends ScaleContinuousNumeric<Range, Output> {
/**
* Returns the scales current interpolator factory, which defaults to interpolate.
*/
@@ -222,7 +219,6 @@ export interface ScaleLinear<Range, Output> extends ScaleContinuousNumeric<Range
* @param interpolate An interpolation factory. The generics for Range and Output of the scale must correpond to the interpolation factory applied to the scale.
*/
interpolate<NewOutput>(interpolate: InterpolatorFactory<Range, NewOutput>): ScaleLinear<Range, NewOutput>;
}
/**
@@ -281,7 +277,6 @@ export function scaleLinear<Range, Output>(): ScaleLinear<Range, Output>;
* convert the interpolated range element to a corresponding output element.
*/
export interface ScalePower<Range, Output> extends ScaleContinuousNumeric<Range, Output> {
/**
* Returns the scales current interpolator factory, which defaults to interpolate.
*/
@@ -428,7 +423,6 @@ export function scaleSqrt<Range, Output>(): ScalePower<Range, Output>;
* convert the interpolated range element to a corresponding output element.
*/
export interface ScaleLogarithmic<Range, Output> extends ScaleContinuousNumeric<Range, Output> {
/**
* Returns a copy of the scales current domain.
*/
@@ -578,16 +572,15 @@ export function scaleLog<Range, Output>(): ScaleLogarithmic<Range, Output>;
* These scales are occasionally useful when working with pixel coordinates, say in conjunction with an axis or brush.
*/
export interface ScaleIdentity {
/**
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A numeric value from the domain.
*/
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A numeric value from the domain.
*/
(value: number | { valueOf(): number }): number;
/**
@@ -688,7 +681,6 @@ export interface ScaleIdentity {
*/
export function scaleIdentity(): ScaleIdentity;
// -------------------------------------------------------------------------------
// Time Scale Factories
// -------------------------------------------------------------------------------
@@ -710,16 +702,15 @@ export function scaleIdentity(): ScaleIdentity;
* convert the interpolated range element to a corresponding output element.
*/
export interface ScaleTime<Range, Output> {
/**
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A temporal value from the domain. If the value is not a Date, it will be coerced to Date.
*/
* Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation.
*
* @param value A temporal value from the domain. If the value is not a Date, it will be coerced to Date.
*/
(value: Date | number | { valueOf(): number }): Output;
/**
@@ -1022,14 +1013,13 @@ export function scaleUtc<Range, Output>(): ScaleTime<Range, Output>;
* The generic corresponds to the data type of the output of the interpolator underlying the scale.
*/
export interface ScaleSequential<Output> {
/**
* Given a value from the domain, returns the corresponding value from the output range, subject to interpolation.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* @param value A numeric value from the domain.
*/
* Given a value from the domain, returns the corresponding value from the output range, subject to interpolation.
*
* If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range.
*
* @param value A numeric value from the domain.
*/
(value: number | { valueOf(): number }): Output;
/**
@@ -1209,7 +1199,7 @@ export interface ScaleQuantize<Range> {
*/
range(range: Range[]): this;
/**
/**
* Returns approximately count representative values from the scales domain.
*
* If count is not specified, it defaults to 10.
@@ -1282,7 +1272,6 @@ export function scaleQuantize<Range>(): ScaleQuantize<Range>;
* The generic correponds to the data type of range elements.
*/
export interface ScaleQuantile<Range> {
/**
* Given a value in the input domain, returns the corresponding value in the output range.
*
@@ -1542,7 +1531,6 @@ export function scaleOrdinal<Domain extends { toString(): string }, Range>(range
*/
export const scaleImplicit: { name: 'implicit' };
// -------------------------------------------------------------------------------
// Band Scale Factory
// -------------------------------------------------------------------------------
@@ -1828,7 +1816,6 @@ export function scalePoint(): ScalePoint<string>;
*/
export function scalePoint<Domain extends { toString(): string }>(): ScalePoint<Domain>;
// -------------------------------------------------------------------------------
// Categorical Color Schemas for Ordinal Scales
// -------------------------------------------------------------------------------

View File

@@ -1,4 +1,3 @@
/**
* Typescript definition tests for d3/d3-selection module
*
@@ -9,7 +8,6 @@
import * as d3Selection from 'd3-selection';
// ---------------------------------------------------------------------------------------
// Some preparatory work for definition testing below
// ---------------------------------------------------------------------------------------
@@ -56,7 +54,6 @@ interface CircleDatumAlternative {
// Tests of Top-Level Selection Functions
// ---------------------------------------------------------------------------------------
// test top-level .selection() -----------------------------------------------------------
const topSelection: d3Selection.Selection<HTMLElement, any, null, undefined> = d3Selection.selection();
@@ -101,16 +98,13 @@ maybeSVG2 = d3Selection.select<SVGSVGElement | null, any>(maybeSVG1.node());
// fails, as node type mismatches selection type
// let body7: d3Selection.Selection<HTMLBodyElement | null, any, HTMLElement, undefined> = d3Selection.select<HTMLBodyElement | null, any>(maybeSVG1.node());
// test "special case DOM objects"
d3Selection.select(xDoc);
d3Selection.select(xWindow);
// test top-level selectAll() -------------------------------------------------------------
// Using selectAll(), selectAll(null) or selectAll(undefined) creates an empty selection
let emptyRootSelection: d3Selection.Selection<null, undefined, null, undefined> = d3Selection.selectAll();
@@ -137,7 +131,6 @@ const baseTypeElements2: d3Selection.Selection<d3Selection.BaseType, any, null,
// element types match, but datum is of type 'any' as it cannot be inferred from .nodes()
const divElements3: d3Selection.Selection<HTMLDivElement, any, null, undefined> = d3Selection.selectAll(divElements.nodes());
// Using selectAll(...) with node array argument and type parameters creates selection
// with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type 'null' with datum of type 'undefined'
@@ -145,10 +138,8 @@ const divElements4: d3Selection.Selection<HTMLDivElement, DivDatum, null, undefi
// d3Selection.selectAll<HTMLDivElement, DivDatum>(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement
// selectAll(...) accepts NodeListOf<...> argument
const xSVGCircleElementList: NodeListOf<SVGCircleElement> = document.querySelectorAll('circle');
const circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefined> = d3Selection.selectAll(xSVGCircleElementList);
@@ -156,14 +147,10 @@ const circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefi
const documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll(document.links);
// ---------------------------------------------------------------------------------------
// Tests of Sub-Selection Functions
// ---------------------------------------------------------------------------------------
// select(...) sub-selection --------------------------------------------------------------
// Expected: datum propagates down from selected element to sub-selected descendant element
@@ -211,12 +198,10 @@ firstG = svgEl.select(function(d, i, g) {
return this.querySelector('g')!; // this of type SVGSVGElement by type inference
});
// firstG = svgEl.select(function() {
// return this.querySelector('a'); // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by firstG
// });
// selectAll(...) sub-selection --------------------------------------------------------------
// Expected: datum from selected element(s) does not propagate down to sub-selected descendant elements.
@@ -234,14 +219,12 @@ let elementsUnknownData: d3Selection.Selection<d3Selection.BaseType, any, SVGSVG
let gElementsOldData: d3Selection.Selection<SVGGElement, CircleDatum, SVGSVGElement, SVGDatum> = svgEl.selectAll<SVGGElement, CircleDatum>('g');
// gElementsOldData = svgEl.selectAll('g'); // fails default type parameters of selectAll for group element type and datum type do not match
// Using selectAll(...) sub-selection with a selector function argument.
function svgGroupSelectorAll(this: SVGSVGElement, d: SVGDatum, i: number, groups: SVGSVGElement[]): NodeListOf<SVGGElement> {
return this.querySelectorAll('g'); // this-type compatible with group element-type to which the selector function will be appplied
}
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(svgGroupSelectorAll);
function wrongSvgGroupSelectorAll(this: HTMLElement, d: SVGDatum, i: number, groups: HTMLElement[]): NodeListOf<SVGGElement> {
@@ -305,7 +288,6 @@ maybeG.selectAll(function(d, i, g) {
// selector(...) and selectorAll(...) ----------------------------------------------------
// d3Selection.select<SVGGElement>(d3Selection.selector<SVGGElement>('g')); // fails, selector as argument to top-level select not supported
// supported on sub-selection
@@ -352,12 +334,10 @@ filterdGElements2 = d3Selection.selectAll<SVGElement, any>('.any-svg-type').filt
// return that.tagName === 'g'|| that.tagName === 'G';
// }); // fails without using narrowing generic on filter method
// matcher() -----------------------------------------------------------------------------
filterdGElements = gElementsOldData.filter(d3Selection.matcher('.top-level'));
// ---------------------------------------------------------------------------------------
// Tests of Modification
// ---------------------------------------------------------------------------------------
@@ -377,7 +357,6 @@ str = body.html();
// Setters tests -------------------------------------------------------------------------
let circles: d3Selection.Selection<SVGCircleElement, CircleDatumAlternative, HTMLElement, any>;
let divs: d3Selection.Selection<HTMLDivElement, DivDatum, HTMLElement, any>;
@@ -425,7 +404,6 @@ divs = divs
return d.padding === '0px'; // boolean return value
});
// style(...) Tests
divs = divs
@@ -451,7 +429,6 @@ divs = divs
// .style('color', function() { return 'green'; }, 'test') // fails, test: invalid priority value
.style('color', () => 'green', 'important'); // boolean return + test: priority = 'important';
// property(...) Tests
circles = circles
@@ -514,7 +491,6 @@ body = body
// Tests of Datum and Data Join
// ---------------------------------------------------------------------------------------
const data: CircleDatum[] = [
{ nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo' },
{ nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar' },
@@ -527,7 +503,6 @@ const data2: CircleDatumAlternative[] = [
{ nodeId: 'c4', cx: 10, cy: 15, r: 10, name: 'newbie', label: 'Newbie', color: 'red' }
];
// Tests of Datum -----------------------------------------------------------------------
// TEST GETTER
@@ -564,7 +539,6 @@ newBodyDatum = body.datum(function(d, i, g) {
// return { newFoo: 'new foo' };
// }).datum(); // inferred type
// SCENARIO 1: Fully type-parameterized
// object-based
@@ -616,10 +590,8 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la
return d.length > 0 && d[0].color === 'green';
});
// Tests of Data Join --------------------------------------------------------------------
const dimensions: SVGDatum = {
width: 500,
height: 300
@@ -741,7 +713,6 @@ circles2 = enterCircles.merge(circles2); // merge enter and update selections
// FURTHER DATA-JOIN TESTs (function argument, changes in data type between old and new data)
const matrix = [
[11975, 5871, 8916, 2868],
[1951, 10048, 2060, 6171],
@@ -876,7 +847,6 @@ newParagraph2 = body.insert(typeValueFunction, 'p.second-paragraph');
newParagraph2 = body.insert(typeValueFunction, beforeValueFunction);
newParagraph2 = body.insert(typeValueFunction);
// sort(...) -----------------------------------------------------------------------------
// NB: Return new selection of same type
@@ -932,12 +902,10 @@ circles = circles.each(function(d, i, g) { // check chaining return type by re-
// call() -------------------------------------------------------------------------------
function enforceMinRadius(selection: d3Selection.Selection<SVGCircleElement, CircleDatumAlternative, any, any>, minRadius: number): void {
selection.attr('r', function(d) {
const r: number = +d3Selection.select(this).attr('r');
return Math.max(r, minRadius);
});
}
// returns 'this' selection
@@ -959,7 +927,6 @@ circles = circles.call(enforceMinRadius, 40); // check chaining return type by r
let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | ArrayLike<HTMLBodyElement>) => void);
body = body.on('click', function(d, i, g) {
const that: HTMLBodyElement = this;
// const that2: SVGElement = this; // fails, type mismatch
@@ -981,7 +948,6 @@ if (listener) {
// remove listener
body = body.on('click', null); // check chaining return type by re-assigning
// dispatch(...) -------------------------------------------------------------------------
const fooEventParam: d3Selection.CustomEventParameters = {
@@ -1009,7 +975,6 @@ body = body.dispatch('fooEvent', function(d, i, g) { // re-assign for chaining t
return eParam;
});
// event and customEvent() ----------------------------------------------------------------
// TODO: Tests of event are related to issue #3 (https://github.com/tomwanzek/d3-v4-definitelytyped/issues/3)

View File

@@ -44,7 +44,6 @@ export interface EnterElement {
*/
export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement;
/**
* Interface for optional parameters map, when dispatching custom events
* on a selection
@@ -69,7 +68,6 @@ export interface CustomEventParameters {
*/
export type ValueFn<T extends BaseType, Datum, Result> = (this: T, datum: Datum, index: number, groups: T[] | ArrayLike<T>) => Result;
/**
* TransitionLike is a helper interface to represent a quasi-Transition, without specifying the full Transition interface in this file.
* For example, whereever d3-zoom allows a Transition to be passed in as an argument, it internally immediately invokes its `selection()`
@@ -88,8 +86,6 @@ export interface TransitionLike<GElement extends BaseType, Datum> {
tween(name: string, tweenFn: ValueFn<GElement, Datum, ((t: number) => void)>): TransitionLike<GElement, Datum>;
}
// --------------------------------------------------------------------------
// All Selection related interfaces and function
// --------------------------------------------------------------------------
@@ -155,7 +151,6 @@ export function selectAll<GElement extends BaseType, OldDatum>(nodes: GElement[]
*/
export function selectAll<GElement extends BaseType, OldDatum>(nodes: ArrayLike<GElement>): Selection<GElement, OldDatum, null, undefined>;
/**
* A D3 Selection of elements.
*
@@ -165,7 +160,6 @@ export function selectAll<GElement extends BaseType, OldDatum>(nodes: ArrayLike<
* The fourth generic "PDatum" refers to the type of the datum of the parent element(s).
*/
interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum> {
// Sub-selection -------------------------
/**
@@ -558,17 +552,17 @@ interface Selection<GElement extends BaseType, Datum, PElement extends BaseType,
*/
filter(selector: string): Selection<GElement, Datum, PElement, PDatum>;
/**
* Filters the selection, returning a new selection that contains only the elements for
* which the specified filter is true.
*
* The returned filtered selection preserves the parents of this selection, but like array.filter,
* it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed.
*
* The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types
* contained in a pre-filter selection are narrowed to a subset as part of the filtering.
*
* @param selector A CSS selector string to match when filtering.
*/
* Filters the selection, returning a new selection that contains only the elements for
* which the specified filter is true.
*
* The returned filtered selection preserves the parents of this selection, but like array.filter,
* it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed.
*
* The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types
* contained in a pre-filter selection are narrowed to a subset as part of the filtering.
*
* @param selector A CSS selector string to match when filtering.
*/
filter<FilteredElement extends BaseType>(selector: string): Selection<FilteredElement, Datum, PElement, PDatum>;
/**
* Filter the selection, returning a new selection that contains only the elements for
@@ -625,7 +619,6 @@ interface Selection<GElement extends BaseType, Datum, PElement extends BaseType,
*/
lower(): this;
// Data Join ---------------------------------
/**
@@ -853,8 +846,6 @@ interface Selection<GElement extends BaseType, Datum, PElement extends BaseType,
* Returns the total number of elements in this selection.
*/
size(): number;
}
/**
@@ -867,8 +858,7 @@ type SelectionFn = () => Selection<HTMLElement, any, null, undefined>;
* Selects the root element, document.documentElement. This function can also be used to test for selections
* (instanceof d3.selection) or to extend the selection prototype.
*/
export var selection: SelectionFn;
export const selection: SelectionFn;
// ---------------------------------------------------------------------------
// on.js event and customEvent related
@@ -899,7 +889,7 @@ interface BaseEvent {
* rather than from the generated UMD bundle; not all bundlers observe jsnext:main.
* Also beware of conflicts with the window.event global.
*/
export var event: any; // Could be of all sorts of types, too general: BaseEvent | Event | MouseEvent | TouchEvent | ... | OwnCustomEventType;
export const event: any; // Could be of all sorts of types, too general: BaseEvent | Event | MouseEvent | TouchEvent | ... | OwnCustomEventType;
/**
* Invokes the specified listener, using the specified "that" as "this" context and passing the specified arguments, if any.
@@ -984,7 +974,6 @@ export function touches(container: ContainerElement, touches?: TouchList): Array
// local.js related
// ---------------------------------------------------------------------------
export interface Local<T> {
/**
* Retrieves a local variable stored on the node (or one of its parents).
@@ -1050,7 +1039,6 @@ export interface NamespaceLocalObject {
*/
export function namespace(prefixedLocal: string): NamespaceLocalObject | string;
// ---------------------------------------------------------------------------
// namespaces.js related
// ---------------------------------------------------------------------------
@@ -1063,8 +1051,7 @@ export interface NamespaceMap { [prefix: string]: string; }
/**
* Map of namespace prefixes to corresponding fully qualified namespace strings
*/
export var namespaces: NamespaceMap;
export const namespaces: NamespaceMap;
// ---------------------------------------------------------------------------
// window.js related
@@ -1078,13 +1065,11 @@ export var namespaces: NamespaceMap;
*/
export function window(DOMNode: Window | Document | Element): Window;
// ---------------------------------------------------------------------------
// creator.js and matcher.js Complex helper closure generating functions
// for explicit bound-context dependent use
// ---------------------------------------------------------------------------
/**
* Given the specified element name, returns a function which creates an element of the given name,
* assuming that "this" is the parent element.

View File

@@ -1990,14 +1990,14 @@ export interface Symbol<This, Datum> {
/**
* Constructs a new symbol generator with the default settings.
*/
export function symbol(): Symbol<any, any>;
export function symbol(): Symbol<any, any>; // tslint:disable-line ban-types
/**
* Constructs a new symbol generator with the default settings.
*
* The generic corrsponds to the data type of the datum underlying the symbol.
*/
export function symbol<Datum>(): Symbol<any, Datum>;
export function symbol<Datum>(): Symbol<any, Datum>; // tslint:disable-line ban-types
/**
* Constructs a new symbol generator with the default settings.
@@ -2005,7 +2005,7 @@ export function symbol<Datum>(): Symbol<any, Datum>;
* The first generic corresponds to the "this" context within which the symbol generator is invoked.
* The second generic corrsponds to the data type of the datum underlying the symbol.
*/
export function symbol<This, Datum>(): Symbol<This, Datum>;
export function symbol<This, Datum>(): Symbol<This, Datum>; // tslint:disable-line ban-types
/**
* An array containing the set of all built-in symbol types: circle, cross, diamond, square, star, triangle, and wye.

Some files were not shown because too many files have changed in this diff Show More