Merge branch 'master' into koa

This commit is contained in:
jKey Lu
2017-02-18 12:32:15 +08:00
3837 changed files with 50116 additions and 7518 deletions
+1
View File
@@ -38,5 +38,6 @@ node_modules
.sublimets
.settings/launch.json
.vs
.vscode
yarn.lock
+3 -3
View File
@@ -1,5 +1,5 @@
- [ ] I tried using the latest `xxxx/xxxx.d.ts` file in this repo and had problems.
- [ ] I tried using the `@types/xxxx` package and had problems.
- [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
- [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there).
- [ ] I want to talk about `xxxx/xxxx.d.ts`.
- The authors of that type definition are cc/ @....
- [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond.
- Authors: @....
+2 -2
View File
@@ -3,8 +3,8 @@ 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#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes).
- [ ] 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.
+3 -1
View File
@@ -110,7 +110,9 @@ 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 -- new-package-name`.
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.)
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.
+255
View File
@@ -0,0 +1,255 @@
import * as Ably from 'ably';
declare var console: { log(message: any): void };
const ApiKey = 'appId.keyId:secret';
const client = new Ably.Realtime(ApiKey);
const restClient = new Ably.Rest(ApiKey);
// Connection
// Successful connection:
client.connection.on('connected', function() {
// successful connection
});
// Failed connection:
client.connection.on('failed', function() {
// failed connection
});
// Subscribing to a channel
var channel = client.channels.get('test');
channel.subscribe(function(message) {
message.name; // 'greeting'
message.data; // 'Hello World!'
});
// Only certain events:
channel.subscribe('myEvent', function(message) {
message.name; // 'myEvent'
message.data; // 'myData'
});
// Publishing to a channel
// Publish a single message with name and data
channel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
channel.publish('greeting', 'Hello World!', function(err) {
if(err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
// Publish several messages at once
channel.publish([{name: 'greeting', data: 'Hello World!'}], function() { });
// Querying the History
channel.history(function(err, messagesPage) {
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { nextPage; }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards'}, function(err, messagesPage) {
console.log(messagesPage.items.length);
});
// Presence on a channel
// Getting presence:
channel.presence.get(function(presenceSet) {
presenceSet; // array of PresenceMessages
});
// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set.
// Entering (and leaving) the presence set:
channel.presence.enter('my status', function(err) {
// now I am entered
});
channel.presence.update('new status', function(err) {
// my presence data is updated
});
channel.presence.leave(null, function(err) {
// I've left the presence set
});
channel.presence.enterClient('myClientId', 'status', function(err) {
});
// and similiarly, updateClient and leaveClient
// Querying the Presence History
channel.presence.history(function(err, messagesPage) { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {});
// Symmetrical end-to-end encrypted payloads on a channel
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// 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(function(err, key) {
var channel = client.channels.get('channelName', { cipher: { key: key } });
channel.subscribe(function(message) {
message.name; // 'name is not encrypted'
message.data; // 'sensitive data is encrypted'
});
channel.publish('name is not encrypted', 'sensitive data is encrypted');
});
// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: '<KEY>'}}, function() {
// New encryption settings are in effect
});
// Using the REST API
var restChannel = restClient.channels.get('test');
// Publishing to a channel
// Publish a single message with name and data
restChannel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
restChannel.publish('greeting', 'Hello World!', function(err) {
if(err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
// Publish several messages at once
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], function() {});
// Querying the History
restChannel.history(function(err, messagesPage) {
messagesPage; // PaginatedResult
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) {}); // retrieves the next page as 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' }, function(err, messagesPage) {});
// Presence on a channel
restChannel.presence.get(function(err, presencePage) { // PaginatedResult
presencePage.items; // array of PresenceMessage
presencePage.items[0].data; // payload for first message
presencePage.items.length; // number of messages in the current page of members
presencePage.hasNext(); // true if there are further pages
presencePage.isLast(); // true if this page is the last page
presencePage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult
});
// Querying the Presence History
restChannel.presence.history(function(err, messagesPage) { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(function(nextPage) { }); // retrieves the next page as 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' }, function(err, messagesPage) {});
// Generate Token and Token Request
// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism.
// Requesting a token:
client.auth.requestToken(function(err, tokenDetails) {
// tokenDetails is instance of 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);
});
// requestToken can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.requestToken({}, {}, function(err, tokenDetails) { });
// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms):
client.auth.createTokenRequest(function(err, tokenRequest) {
// now send the tokenRequest back to the client, which will
// use it to request a token and connect to Ably
});
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.createTokenRequest({}, {}, function(err, tokenRequest) { });
// Fetching your application's stats
client.stats({ limit: 50 }, function(err, statsPage) { // statsPage as PaginatedResult
statsPage.items; // array of Stats
statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
statsPage.items.length; // number of stats in the current page of history
statsPage.hasNext(); // true if there are further pages
statsPage.isLast(); // true if this page is the last page
statsPage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult
});
// Fetching the Ably service time
client.time({}, function(err, time) {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
console.log(messages[0].id);
var 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' }]);
console.log(presenceMessages[0].action);
var presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
console.log(presenceMessage.action);
+471
View File
@@ -0,0 +1,471 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ablyLib {
namespace ChannelState {
type INITIALIZED = 'initialized';
type ATTACHING = 'attaching';
type ATTACHED = "attached";
type DETACHING = "detaching";
type DETACHED = "detached";
type SUSPENDED = "suspended";
type FAILED = "failed";
}
type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING;
namespace ConnectionState {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
}
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
namespace ConnectionEvent {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
type UPDATE = "update";
}
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
namespace PresenceAction {
type ABSENT = "absent";
type PRESENT = "present";
type ENTER = "enter";
type LEAVE = "leave";
type UPDATE = "update";
}
type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE;
namespace StatsIntervalGranularity {
type MINUTE = "minute";
type HOUR = "hour";
type DAY = "day";
type MONTH = "month";
}
type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH;
namespace HTTPMethods {
type POST = "POST";
type GET = "GET";
}
type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST;
// Interfaces
interface ClientOptions extends AuthOptions {
/**
* When true will automatically connect to Ably when library is instanced. This is true by default
*/
autoConnect?: boolean;
/**
* Optional clientId that can be used to specify the identity for this client. In most cases
* it is preferable to instead specift a clientId in the token issued to this client.
*/
clientId?: string;
defaultTokenParams?: TokenParams;
/**
* When true, messages published on channels by this client will be echoed back to this client.
* This is true by default
*/
echoMessages?: boolean;
/**
* Use this only if you have been provided a dedicated environment by Ably
*/
environment?: string;
/**
* Logger configuration
*/
log?: LogInfo;
port?: number;
/**
* When true, messages will be queued whilst the connection is disconnected. True by default.
*/
queueMessages?: boolean;
restHost?: string;
realtimeHost?: string;
fallbackHosts?: string[];
/**
* Can be used to explicitly recover a connection.
* See https://www.ably.io/documentation/realtime/connection#connection-state-recovery
*/
recover?: standardCallback | string;
/**
* Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably
*/
tls?: boolean;
tlsPort?: number;
/**
* When true, the more efficient MsgPack binary encoding is used.
* When false, JSON text encoding is used.
*/
useBinaryProtocol?: boolean;
}
interface AuthOptions {
/**
* 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;
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;
token?: TokenDetails | string;
tokenDetails?: TokenDetails;
useTokenAuth?: boolean;
}
interface TokenParams {
capability?: string;
clientId?: string;
nonce?: string;
timestamp?: number;
ttl?: number;
}
interface CipherParams {
algorithm: string;
key: any;
keyLength: number;
mode: string;
}
interface ErrorInfo {
code: number;
message: string;
statusCode: number;
}
interface StatsMessageCount {
count: number;
data: number;
}
interface StatsMessageTypes {
all: StatsMessageCount;
messages: StatsMessageCount;
presence: StatsMessageCount;
}
interface StatsRequestCount {
failed: number;
refused: number;
succeeded: number;
}
interface StatsResourceCount {
mean: number;
min: number;
opened: number;
peak: number;
refused: number;
}
interface StatsConnectionTypes {
all: StatsResourceCount;
plain: StatsResourceCount;
tls: StatsResourceCount;
}
interface StatsMessageTraffic {
all: StatsMessageTypes;
realtime: StatsMessageTypes;
rest: StatsMessageTypes;
webhook: StatsMessageTypes;
}
interface TokenDetails {
capability: string;
clientId?: string;
expires: number;
issued: number;
token: string;
}
interface TokenRequest {
capability: string;
clientId?: string;
keyName: string;
mac: string;
nonce: string;
timestamp: number;
ttl?: number;
}
interface ChannelOptions {
cipher: any;
}
interface RestPresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
}
interface RestPresenceParams {
limit?: number;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceParams {
waitForSync?: boolean;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
untilAttach?: boolean;
}
interface LogInfo {
/**
* 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;
}
interface ChannelEvent {
state: ChannelState;
}
interface ChannelStateChange {
current: ChannelState;
previous: ChannelState;
reason?: ErrorInfo;
resumed: boolean;
}
interface ConnectionStateChange {
current: ConnectionState;
previous: ConnectionState;
reason?: ErrorInfo;
retryIn?: number;
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T> ) => void;
type standardCallback = (error: ErrorInfo, results: any) => void;
type messageCallback<T> = (message: T) => void;
type errorCallback = (error: ErrorInfo) => void;
type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void;
type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void;
type timeCallback = (error: ErrorInfo, time: number) => void;
type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void;
type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void;
type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void;
type fromEncoded<T> = (JsonObject: any, channelOptions?: ChannelOptions) => T;
type fromEncodedArray<T> = (JsonArray: any[], channelOptions?: ChannelOptions) => T[];
// Internal Classes
class EventEmitter<T> {
on: (eventOrCallback: string | T, callback?: T) => void;
once: (eventOrCallback: string | T, callback?: T) => void;
off: (eventOrCallback?: string | T, callback?: T) => void;
}
// Classes
class Auth {
clientId: string;
authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void;
requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
}
class Presence {
get: (params: RestPresenceParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
history: (params: RestPresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
}
class RealtimePresence {
syncComplete: () => boolean;
get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void;
history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
subscribe: (presenceOrCallback: PresenceAction | messageCallback<PresenceMessage>, listener?: messageCallback<PresenceMessage>) => void;
unsubscribe: (presence?: PresenceAction, listener?: messageCallback<PresenceMessage>) => void;
enter: (data?: errorCallback | any, callback?: errorCallback) => void;
update: (data?: errorCallback | any, callback?: errorCallback) => void;
leave: (data?: errorCallback | any, callback?: errorCallback) => void;
enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
}
class Channel {
name: string;
presence: Presence;
history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
}
class RealtimeChannel extends EventEmitter<channelEventCallback> {
name: string;
errorReason: ErrorInfo;
state: ChannelState;
presence: RealtimePresence;
attach: (callback?: standardCallback) => void;
detach: (callback?: standardCallback) => void;
history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
subscribe: (eventOrCallback: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
unsubscribe: (eventOrCallback?: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
setOptions: (options: any, callback?: errorCallback) => void;
}
class Channels<T> {
get: (name: string, channelOptions?: ChannelOptions) => T;
release: (name: string) => void;
}
class Message {
constructor();
static fromEncoded: fromEncoded<Message>;
static fromEncodedArray: fromEncodedArray<Message>;
clientId: string;
connectionId: string;
data: any;
encoding: string;
extras: any;
id: string;
name: string;
timestamp: number;
}
interface MessageStatic {
fromEncoded: fromEncoded<Message>;
fromEncodedArray: fromEncodedArray<Message>;
}
class PresenceMessage {
constructor();
static fromEncoded: fromEncoded<PresenceMessage>;
static fromEncodedArray: fromEncodedArray<PresenceMessage>;
action: PresenceAction;
clientId: string;
connectionId: string;
data: any;
encoding: string;
id: string;
timestamp: number;
}
interface PresenceMessageStatic {
fromEncoded: fromEncoded<PresenceMessage>;
fromEncodedArray: fromEncodedArray<PresenceMessage>;
}
interface Crypto {
generateRandomKey: (callback: (error: ErrorInfo, key: string) => void) => void;
}
class Connection extends EventEmitter<connectionEventCallback> {
errorReason: ErrorInfo;
id: string;
key: string;
recoveryKey: string;
serial: number;
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void;
}
class Stats {
all: StatsMessageTypes;
apiRequests: StatsRequestCount;
channels: StatsResourceCount;
connections: StatsConnectionTypes;
inbound: StatsMessageTraffic;
intervalId: string;
outbound: StatsMessageTraffic;
persisted: StatsMessageTypes;
tokenRequests: StatsRequestCount;
}
class PaginatedResult<T> {
items: T[];
first: (results: paginatedResultCallback<T>) => void;
next: (results: paginatedResultCallback<T>) => void;
current: (results: paginatedResultCallback<T>) => void;
hasNext: () => boolean;
isLast: () => boolean;
}
class HttpPaginatedResponse extends PaginatedResult<any> {
items: string[];
statusCode: number;
success: boolean;
errorCode: number;
errorMessage: string;
headers: any;
}
}
export declare class Rest {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.Channel>;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
export declare class Realtime {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.RealtimeChannel>;
clientId: string;
connection: ablyLib.Connection;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
close: () => void;
connect: () => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
+22
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",
"ably-tests.ts"
]
}
+43 -12
View File
@@ -3,29 +3,60 @@
// Definitions by: Stefan Reichel <https://github.com/bomret>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { IncomingMessage } from "http";
declare namespace accepts {
export interface Headers {
[key: string]: string | string[];
}
export interface Accepts {
charset(charsets: string[]): string | string[] | boolean;
charset(...charsets: string[]): string | string[] | boolean;
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
*/
charset(charsets: string[]): string | false;
charset(...charsets: string[]): string | false;
/**
* Return the charsets that the request accepts, in the order of the client's preference (most preferred first).
*/
charsets(): string[];
encoding(encodings: string[]): string | string[] | boolean;
encoding(...encodings: string[]): string | string[] | boolean;
/**
* Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned.
*/
encoding(encodings: string[]): string | false;
encoding(...encodings: string[]): string | false;
/**
* Return the encodings that the request accepts, in the order of the client's preference (most preferred first).
*/
encodings(): string[];
language(languages: string[]): string | string[] | boolean;
language(...languages: string[]): string | string[] | boolean;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
*/
language(languages: string[]): string | false;
language(...languages: string[]): string | false;
/**
* Return the languages that the request accepts, in the order of the client's preference (most preferred first).
*/
languages(): string[];
type(types: string[]): string | string[] | boolean;
type(...types: string[]): string | string[] | boolean;
/**
* Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned.
*
* The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`.
*/
type(types: string[]): string | false;
type(...types: string[]): string | false;
/**
* Return the types that the request accepts, in the order of the client's preference (most preferred first).
*/
types(): string[];
}
}
declare function accepts(req: IncomingMessage): accepts.Accepts;
declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts;
export = accepts;
+4 -4
View File
@@ -32,7 +32,7 @@ declare module "angular" {
// width of grid columns. "auto" will divide the width of the grid evenly among the columns
colWidth?: string;
// height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels,
// height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels,
// '/2' is half the column width, '*5' is five times the column width, etc.
rowHeight?: string;
@@ -84,7 +84,7 @@ declare module "angular" {
// options to pass to resizable handler
resizable?: {
// whether the items are resizable
// whether the items are resizable
enabled?: boolean;
// location of the resize handles
@@ -104,7 +104,7 @@ declare module "angular" {
// options to pass to draggable handler
draggable?: {
// whether the items are resizable
// whether the items are resizable
enabled?: boolean;
// Distance in pixels from the edge of the viewport after which the viewport should scroll, relative to pointer
@@ -142,4 +142,4 @@ declare module "angular" {
col: number;
}
}
}
}
+1
View File
@@ -106,6 +106,7 @@ declare module 'angular' {
onComplete?: Function;
onRemoving?: Function;
skipHide?: boolean;
multiple?: boolean;
fullscreen?: boolean; // default: false
}
+1
View File
@@ -118,6 +118,7 @@ httpBackendService.flush();
httpBackendService.flush(1234);
httpBackendService.resetExpectations();
httpBackendService.verifyNoOutstandingExpectation();
httpBackendService.verifyNoOutstandingExpectation(false);
httpBackendService.verifyNoOutstandingRequest();
requestHandler = httpBackendService.expect('GET', 'http://test.local');
+2 -1
View File
@@ -132,8 +132,9 @@ declare module 'angular' {
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
*/
verifyNoOutstandingExpectation(): void;
verifyNoOutstandingExpectation(digest?: boolean): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
+2 -2
View File
@@ -51,8 +51,8 @@ declare module 'angular' {
cloakClassName(name: string): ITranslateProvider;
fallbackLanguage(langKey?: string): string;
fallbackLanguage(langKey?: string[]): string;
instant(translationId: string, interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string };
instant(translationId: string, interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): { [key: string]: string };
isPostCompilingEnabled(): boolean;
preferredLanguage(langKey?: string): string;
proposedLanguage(): string;
@@ -7,6 +7,7 @@ testApp.config((
$buttonConfig: ng.ui.bootstrap.IButtonConfig,
$datepickerConfig: ng.ui.bootstrap.IDatepickerConfig,
$datepickerPopupConfig: ng.ui.bootstrap.IDatepickerPopupConfig,
$dropdownConfig: ng.ui.bootstrap.IDropdownConfig,
$modalProvider: ng.ui.bootstrap.IModalProvider,
$paginationConfig: ng.ui.bootstrap.IPaginationConfig,
$pagerConfig: ng.ui.bootstrap.IPagerConfig,
@@ -47,13 +48,18 @@ testApp.config((
$datepickerConfig.showWeeks = false;
$datepickerConfig.startingDay = 1;
$datepickerConfig.yearRange = 10;
$datepickerConfig.monthColumns = 3;
$datepickerConfig.yearColumns = 9;
$datepickerConfig.yearRows = 6;
$datepickerConfig.ngModelOptions.allowInvalid = false;
$datepickerConfig.ngModelOptions.timezone = "EST";
$datepickerConfig.ngModelOptions.updateOn = "click";
/**
* $datepickerPopupConfig tests
*/
$datepickerPopupConfig.altInputFormats = ["mm/dd/YYYY", "mm-dd-YY"];
$datepickerPopupConfig.appendToBody = true;
$datepickerPopupConfig.currentText = 'Select Today';
$datepickerPopupConfig.clearText = 'Reset Selection';
@@ -63,8 +69,18 @@ testApp.config((
$datepickerPopupConfig.datepickerPopupTemplateUrl = 'template.html';
$datepickerPopupConfig.datepickerTemplateUrl = 'template.html';
$datepickerPopupConfig.html5Types.date = 'MM-dd-yyyy';
$datepickerPopupConfig.html5Types['datetime-local'] = 'yyyy-MM-ddTHH:mm:ss.sss';
$datepickerPopupConfig.html5Types.month = 'yyyy-MM';
$datepickerPopupConfig.onOpenFocus = false;
$datepickerPopupConfig.showButtonBar = false;
$datepickerPopupConfig.placement = "auto bottom left";
/**
* $dropdownConfig tests
*/
$dropdownConfig.appendToOpenClass = "some-thing";
$dropdownConfig.openClass = "show";
/**
@@ -77,6 +93,7 @@ testApp.config((
* $paginationConfig tests
*/
$paginationConfig.boundaryLinks = true;
$paginationConfig.boundaryLinkNumbers = true;
$paginationConfig.directionLinks = false;
$paginationConfig.firstText = 'First Page';
$paginationConfig.itemsPerPage = 25;
@@ -88,6 +105,7 @@ testApp.config((
$paginationConfig.rotate = false;
$paginationConfig.templateUrl = 'template.html';
$paginationConfig.totalItems = 13;
$paginationConfig.forceEllipses = true;
/**
@@ -121,11 +139,14 @@ testApp.config((
$timepickerConfig.hourStep = 2;
$timepickerConfig.meridians = ['-AM-', '-PM-'];
$timepickerConfig.minuteStep = 5;
$timepickerConfig.secondStep = 5;
$timepickerConfig.mousewheel = false;
$timepickerConfig.readonlyInput = true;
$timepickerConfig.showMeridian = false;
$timepickerConfig.arrowkeys = false;
$timepickerConfig.showSpinners = false;
$timepickerConfig.showSeconds = true;
$timepickerConfig.templateUrl = "template.html";
/**
* $tooltipProvider tests
@@ -134,6 +155,7 @@ testApp.config((
placement: 'bottom',
animation: false,
popupDelay: 1000,
popupCloseDelay: 1000,
appendToBody: true,
trigger: 'mouseenter hover',
useContentExp: true,
+104 -2
View File
@@ -11,6 +11,7 @@ export type IAccordionConfig = angular.ui.bootstrap.IAccordionConfig;
export type IButtonConfig = angular.ui.bootstrap.IButtonConfig;
export type IDatepickerConfig = angular.ui.bootstrap.IDatepickerConfig;
export type IDatepickerPopupConfig = angular.ui.bootstrap.IDatepickerPopupConfig;
export type IDropdownConfig = angular.ui.bootstrap.IDropdownConfig;
export type IModalProvider = angular.ui.bootstrap.IModalProvider;
export type IModalService = angular.ui.bootstrap.IModalService;
export type IModalServiceInstance = angular.ui.bootstrap.IModalServiceInstance;
@@ -54,6 +55,11 @@ declare module 'angular' {
toggleEvent?: string;
}
interface IDropdownConfigNgOptions extends angular.INgModelOptions {
allowInvalid?: boolean;
timezone?: string;
}
interface IDatepickerConfig {
/**
* Format of day in month.
@@ -155,7 +161,7 @@ declare module 'angular' {
/**
* Defines the initial date, when no model value is specified.
*
*
* @default null
*/
initDate?: any;
@@ -166,9 +172,45 @@ declare module 'angular' {
* @default false
*/
shortcutPropagation?: boolean;
/**
* The number of columns displayed in month selection.
*
* @default 3
*/
monthColumns?: number;
/**
* The number of columns displayed in year selection.
*
* @default 5
*/
yearColumns?: number;
/**
* The number of rows displayed in year selection
*
* @default 4
*/
yearRows?: number;
/**
* All supported angular ngModelOptions plus some
*
* @default {}
*/
ngModelOptions?: IDropdownConfigNgOptions
}
interface IDatepickerPopupConfig {
/**
* A list of alternate formats acceptable for manual entry.
*
* @default []
*/
altInputFormats?: string[];
/**
* The format for displayed dates.
*
@@ -247,8 +289,26 @@ declare module 'angular' {
* @default true
*/
onOpenFocus?: boolean;
/**
* Passing in 'auto' separated by a space before the placement will enable auto positioning, e.g: "auto bottom-left". The popup will attempt to position where it fits in the closest scrollable ancestor.
*
* @default 'auto bottom-left'
*/
placement?: string;
}
interface IDropdownConfig {
/**
* @default: 'uib-dropdown-open'
*/
appendToOpenClass?: string;
/**
* @default: 'open'
*/
openClass?: string;
}
interface IModalProvider {
/**
@@ -543,6 +603,13 @@ declare module 'angular' {
*/
boundaryLinks?: boolean;
/**
* Whether to always display the first and last page numbers. If max-size is smaller than the number of pages, then the first and last page numbers are still shown with ellipses in-between as necessary. NOTE: max-size refers to the center of the range. This option may add up to 2 more numbers on each side of the displayed range for the end value and what would be an ellipsis but is replaced by a number because it is sequential.
*
* @default false
*/
boundaryLinkNumbers?: boolean;
/**
* Text for First button.
*
@@ -563,6 +630,13 @@ declare module 'angular' {
* @default 'template/pagination/pagination.html'
*/
templateUrl?: string;
/**
* Also displays ellipses when rotate is true and max-size is smaller than the number of pages.
*
* @default false
*/
forceEllipses?: boolean;
}
interface IPagerConfig {
@@ -679,6 +753,13 @@ declare module 'angular' {
*/
minuteStep?: number;
/**
* Number of seconds to increase or decrease when using a button.
*
* @default 1
*/
secondStep?: number;
/**
* Whether to display 12H or 24H mode.
*
@@ -720,6 +801,20 @@ declare module 'angular' {
* @default true
*/
showSpinners?: boolean;
/**
* Show seconds input.
*
* @default false
*/
showSeconds?: boolean;
/**
* Add the ability to override the template used on the component.
*
* @default 'uib/template/timepicker/timepicker.html'
*/
templateUrl?: string;
}
@@ -739,12 +834,19 @@ declare module 'angular' {
animation?: boolean;
/**
* For how long should the user have to have the mouse over the element before the tooltip shows (in milliseconds)?
* Popup delay in milliseconds until it opens.
*
* @default 0
*/
popupDelay?: number;
/**
* For how long should the tooltip remain open after the close trigger event?
*
* @default 0
*/
popupCloseDelay?: number;
/**
* Should the tooltip be appended to `$body` instead of the parent element?
*
+5 -5
View File
@@ -143,7 +143,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
private $state: ng.ui.IStateService
) {
$rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event));
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
$rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) =>
this.onStateNotFound(event, unfoundState, fromState, fromParams));
}
@@ -157,8 +157,8 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
// Note that we do not concern ourselves with what to do if this request fails,
// because if it fails, the web page will be redirected away to the login screen.
this.$http({ url: "/api/me", method: "GET" }).success((user: any) => {
this.currentUser = user;
this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpPromiseCallbackArg<any>) => {
this.currentUser = response.data;
// sync the ui-state with the location in the browser, which effectively
// restarts the state change that was stopped previously
@@ -166,14 +166,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
});
}
}
private onStateNotFound(event: ng.IAngularEvent,
unfoundState: ng.ui.IUnfoundState,
fromState: ng.ui.IState,
fromParams: {}) {
var unfoundTo: string = unfoundState.to;
var unfoundToParams: {} = unfoundState.toParams;
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
var unfoundOptions: ng.ui.IStateOptions = unfoundState.options
}
private stateServiceTest() {
+2 -2
View File
@@ -1,9 +1,9 @@
/* tslint:disable:dt-header variable-name */
// Type definitions for Angular JS 1.5 component router
// Project: http://angularjs.org
// Definitions by: David Reher <http://github.com/davidreher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace angular {
/**
* `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed
@@ -263,7 +263,7 @@ declare namespace angular {
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): Object;
subscribe(onNext: (value: any) => void): {};
/**
* Removes the contents of this router's outlet and all descendant outlets
+312 -244
View File
File diff suppressed because it is too large Load Diff
+70 -62
View File
@@ -27,7 +27,7 @@ import ng = angular;
///////////////////////////////////////////////////////////////////////////////
declare namespace angular {
type Injectable<T extends Function> = T | (string | T)[];
type Injectable<T extends Function> = T | Array<string | T>;
// not directly implemented, but ensures that constructed class implements $get
interface IServiceProviderClass {
@@ -64,7 +64,7 @@ declare namespace angular {
* @param config an object for defining configuration options for the application. The following keys are supported:
* - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.
*/
bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService;
bootstrap(element: string|Element|JQuery|Document, modules?: Array<string|Function|any[]>, config?: IAngularBootstrapConfig): auto.IInjectorService;
/**
* Creates a deep copy of source, which should be an object or an array.
@@ -122,7 +122,7 @@ declare namespace angular {
fromJson(json: string): any;
identity<T>(arg?: T): T;
injector(modules?: any[], strictDi?: boolean): auto.IInjectorService;
isArray(value: any): value is Array<any>;
isArray(value: any): value is any[];
isDate(value: any): value is Date;
isDefined(value: any): boolean;
isElement(value: any): boolean;
@@ -514,7 +514,7 @@ declare namespace angular {
$watchCollection<T>(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void;
$watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void;
$watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void;
$watchGroup(watchExpressions: Array<{ (scope: IScope): any }>, listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void;
$parent: IScope;
$root: IRootScopeService;
@@ -662,9 +662,9 @@ declare namespace angular {
}
interface IFilterOrderByItem {
value: any,
type: string,
index: any
value: any;
type: string;
index: any;
}
interface IFilterOrderByComparatorFunc {
@@ -756,7 +756,7 @@ declare namespace angular {
* @param comparator Function used to determine the relative order of value pairs.
* @return An array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.
*/
<T>(array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[];
<T>(array: T[], expression: string|((value: T) => any)|Array<((value: T) => any)|string>, reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[];
}
/**
@@ -1023,7 +1023,7 @@ declare namespace angular {
all<T1, T2, T3, T4>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>]): IPromise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>]): IPromise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>]): IPromise<[T1, T2]>;
all<TAll>(promises: IPromise<TAll>[]): IPromise<TAll[]>;
all<TAll>(promises: Array<IPromise<TAll>>): IPromise<TAll[]>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
@@ -1044,13 +1044,14 @@ declare namespace angular {
*
* @param reason Constant, message, exception or an object representing the rejection reason.
*/
reject(reason?: any): IPromise<any>;
reject(reason?: any): IPromise<never>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
resolve<T>(value: IPromise<T>|T): IPromise<T>;
resolve<T1, T2>(value: IPromise<T1>|T2): IPromise<T1|T2>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*/
@@ -1061,7 +1062,10 @@ declare namespace angular {
* @param value Value or a promise
*/
when<T>(value: IPromise<T>|T): IPromise<T>;
when<TResult, T>(value: IPromise<T>|T, successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
when<T1, T2>(value: IPromise<T1>|T2): IPromise<T1|T2>;
when<TResult, T>(value: IPromise<T>|T, successCallback: (promiseValue: T) => IPromise<TResult>|TResult): IPromise<TResult>;
when<TResult, T>(value: T, successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise<TResult>;
when<TResult, TResult2, T>(value: IPromise<T>, successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback: (reason: any) => TResult2 | IPromise<TResult2>, notifyCallback?: (state: any) => any): IPromise<TResult | TResult2>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*/
@@ -1090,15 +1094,20 @@ declare namespace angular {
interface IPromise<T> {
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
* The successCallBack may return IPromise<void> for when a $q.reject() needs to be returned
* The successCallBack may return IPromise<never> for when a $q.reject() needs to be returned
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult1, TResult2>(successCallback: (promiseValue: T) => IPromise<TResult1>|TResult2, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise<TResult1 | TResult2>;
then<TResult, TCatch>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback: (reason: any) => IPromise<TCatch>|TCatch, notifyCallback?: (state: any) => any): IPromise<TResult | TCatch>;
then<TResult1, TResult2, TCatch1, TCatch2>(successCallback: (promiseValue: T) => IPromise<TResult1>|TResult2, errorCallback: (reason: any) => IPromise<TCatch1>|TCatch2, notifyCallback?: (state: any) => any): IPromise<TResult1 | TResult2 | TCatch1 | TCatch2>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => IPromise<TResult>|TResult): IPromise<TResult>;
catch<TCatch>(onRejected: (reason: any) => IPromise<TCatch>|TCatch): IPromise<T | TCatch>;
catch<TCatch1, TCatch2>(onRejected: (reason: any) => IPromise<TCatch1>|TCatch2): IPromise<T | TCatch1 | TCatch2>;
/**
* Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.
@@ -1245,6 +1254,16 @@ declare namespace angular {
debugInfoEnabled(): boolean;
debugInfoEnabled(enabled: boolean): ICompileProvider;
/**
* Call this method to enable/disable whether directive controllers are assigned bindings before calling the controller's constructor.
* If enabled (true), the compiler assigns the value of each of the bindings to the properties of the controller object before the constructor of this object is called.
* If disabled (false), the compiler calls the constructor first before assigning bindings.
* Defaults to false.
* See: https://docs.angularjs.org/api/ng/provider/$compileProvider#preAssignBindingsEnabled
*/
preAssignBindingsEnabled(): boolean;
preAssignBindingsEnabled(enabled: boolean): ICompileProvider;
/**
* Sets the number of times $onChanges hooks can trigger new changes before giving up and assuming that the model is unstable.
* Increasing the TTL could have performance implications, so you should not change it without proper justification.
@@ -1284,11 +1303,11 @@ declare namespace angular {
}
interface ITemplateLinkingFunctionOptions {
parentBoundTranscludeFn?: ITranscludeFunction,
parentBoundTranscludeFn?: ITranscludeFunction;
transcludeControllers?: {
[controller: string]: { instance: IController }
},
futureParentElement?: JQuery
};
futureParentElement?: JQuery;
}
/**
@@ -1486,18 +1505,6 @@ declare namespace angular {
}
interface IHttpPromise<T> extends IPromise<IHttpPromiseCallbackArg<T>> {
/**
* The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
* If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
* @deprecated
*/
success?(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
/**
* The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
* If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
* @deprecated
*/
error?(callback: IHttpPromiseCallback<any>): IHttpPromise<T>;
}
// See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228
@@ -1510,7 +1517,9 @@ declare namespace angular {
(data: any, headersGetter: IHttpHeadersGetter, status: number): any;
}
type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)};
interface HttpHeaderType {
[requestType: string]: string|((config: IRequestConfig) => string);
}
interface IHttpRequestConfigHeaders {
[requestType: string]: any;
@@ -1593,7 +1602,7 @@ declare namespace angular {
* Register service factories (names or implementations) for interceptors which are called before and after
* each request.
*/
interceptors: (string | Injectable<IHttpInterceptorFactory>)[];
interceptors: Array<string | Injectable<IHttpInterceptorFactory>>;
useApplyAsync(): boolean;
useApplyAsync(value: boolean): IHttpProvider;
@@ -1603,7 +1612,7 @@ declare namespace angular {
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
*/
useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider;
useLegacyPromiseExtensions(value: boolean): boolean | IHttpProvider;
}
///////////////////////////////////////////////////////////////////////////
@@ -1687,16 +1696,15 @@ declare namespace angular {
valueOf(value: any): any;
}
///////////////////////////////////////////////////////////////////////////
// SCEDelegateProvider
// see http://docs.angularjs.org/api/ng.$sceDelegateProvider
///////////////////////////////////////////////////////////////////////////
interface ISCEDelegateProvider extends IServiceProvider {
resourceUrlBlacklist(blacklist: any[]): void;
resourceUrlWhitelist(whitelist: any[]): void;
resourceUrlBlacklist(): any[];
resourceUrlBlacklist(blacklist: any[]): void;
resourceUrlWhitelist(): any[];
resourceUrlWhitelist(whitelist: any[]): void;
}
/**
@@ -1936,33 +1944,33 @@ declare namespace angular {
annotate(fn: Function, strictDi?: boolean): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get<T>(name: string, caller?: string): T;
get(name: '$anchorScroll'): IAnchorScrollService
get(name: '$cacheFactory'): ICacheFactoryService
get(name: '$compile'): ICompileService
get(name: '$controller'): IControllerService
get(name: '$document'): IDocumentService
get(name: '$exceptionHandler'): IExceptionHandlerService
get(name: '$filter'): IFilterService
get(name: '$http'): IHttpService
get(name: '$httpBackend'): IHttpBackendService
get(name: '$httpParamSerializer'): IHttpParamSerializer
get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer
get(name: '$interpolate'): IInterpolateService
get(name: '$interval'): IIntervalService
get(name: '$locale'): ILocaleService
get(name: '$location'): ILocationService
get(name: '$log'): ILogService
get(name: '$parse'): IParseService
get(name: '$q'): IQService
get(name: '$rootElement'): IRootElementService
get(name: '$rootScope'): IRootScopeService
get(name: '$sce'): ISCEService
get(name: '$sceDelegate'): ISCEDelegateService
get(name: '$templateCache'): ITemplateCacheService
get(name: '$templateRequest'): ITemplateRequestService
get(name: '$timeout'): ITimeoutService
get(name: '$window'): IWindowService
get<T>(name: '$xhrFactory'): IXhrFactory<T>
get(name: '$anchorScroll'): IAnchorScrollService;
get(name: '$cacheFactory'): ICacheFactoryService;
get(name: '$compile'): ICompileService;
get(name: '$controller'): IControllerService;
get(name: '$document'): IDocumentService;
get(name: '$exceptionHandler'): IExceptionHandlerService;
get(name: '$filter'): IFilterService;
get(name: '$http'): IHttpService;
get(name: '$httpBackend'): IHttpBackendService;
get(name: '$httpParamSerializer'): IHttpParamSerializer;
get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer;
get(name: '$interpolate'): IInterpolateService;
get(name: '$interval'): IIntervalService;
get(name: '$locale'): ILocaleService;
get(name: '$location'): ILocationService;
get(name: '$log'): ILogService;
get(name: '$parse'): IParseService;
get(name: '$q'): IQService;
get(name: '$rootElement'): IRootElementService;
get(name: '$rootScope'): IRootScopeService;
get(name: '$sce'): ISCEService;
get(name: '$sceDelegate'): ISCEDelegateService;
get(name: '$templateCache'): ITemplateCacheService;
get(name: '$templateRequest'): ITemplateRequestService;
get(name: '$timeout'): ITimeoutService;
get(name: '$window'): IWindowService;
get<T>(name: '$xhrFactory'): IXhrFactory<T>;
has(name: string): boolean;
instantiate<T>(typeConstructor: Function, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
+20
View File
@@ -0,0 +1,20 @@
{
"extends": "../tslint.json",
"rules": {
"class-name": true,
"curly": true,
"no-consecutive-blank-lines": true,
"no-shadowed-variable": true,
"quotemark": [true, "single"],
"align": true,
"callable-types": false,
"forbidden-types": false,
"indent": [true, "spaces"],
"interface-name": false,
"linebreak-style": [true, "LF"],
"no-empty-interface": false,
"unified-signatures": false,
"variable-name": [true, "check-format"],
"void-return": false
}
}
-1
View File
@@ -31,7 +31,6 @@ declare namespace archiver {
}
export interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
append(source: STREAM.Readable | Buffer | string, name: nameInterface): void;
directory(dirpath: string, destpath: nameInterface | string): void;
+145 -17
View File
@@ -1,23 +1,151 @@
/// <reference types="auth0-js" />
import 'auth0-js';
var auth0 = new Auth0({
let webAuth = new auth0.WebAuth({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
clientID: 'dsa7d77dsa7d7'
});
auth0.login({
connection: 'google-oauth2',
popup: true,
popupOptions: {
width: 450,
height: 800
webAuth.authorize({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
responseType: 'token',
redirectUri: 'https://example.com/auth/callback'
});
webAuth.parseHash(window.location.hash, (err, authResult) => {
if (err) {
return console.log(err);
}
}, (err, profile, idToken, accessToken, state) => {
if (err) {
alert("something went wrong: " + err.message);
return;
}
alert('hello ' + profile.name);
// The contents of authResult depend on which authentication parameters were used.
// It can include the following:
// authResult.accessToken - access token for the API specified by `audience`
// authResult.expiresIn - string with the access token's expiration time in seconds
// authResult.idToken - ID token JWT containing user profile information
webAuth.client.userInfo(authResult.accessToken, (err, user) => {
// Now you have the user's information
});
});
webAuth.renewAuth({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback',
// this will use postMessage to comunicate between the silent callback
// and the SPA. When false the SDK will attempt to parse the url hash
// should ignore the url hash and no extra behaviour is needed.
usePostMessage: true
}, function (err, authResult) {
// Renewed tokens or error
});
webAuth.changePassword({connection: 'the_connection',
email: 'me@example.com',
password: '123456'
}, (err) => {});
webAuth.passwordlessStart({
connection: 'the_connection',
email: 'me@example.com',
send: 'code'
}, (err, data) => {});
webAuth.signupAndAuthorize({
connection: 'the_connection',
email: 'me@example.com',
password: '123456',
scope: 'openid'
}, function (err, data) {
});
webAuth.client.login({
ealm: 'Username-Password-Authentication', //connection name or HRD domain
username: 'info@auth0.com',
password: 'areallystrongpassword',
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
}, function(err, authResult) {
// Auth tokens in the result or an error
});
let authentication = new auth0.Authentication({
domain: 'me.auth0.com',
clientID: '...',
redirectUri: 'http://page.com/callback',
responseType: 'code',
_sendTelemetry: false
});
authentication.buildAuthorizeUrl({state:'1234'});
authentication.buildAuthorizeUrl({
responseType: 'token',
redirectUri: 'http://anotherpage.com/callback2',
prompt: 'none',
state: '1234',
connection_scope: 'scope1,scope2'
});
authentication.buildLogoutUrl('asdfasdfds');
authentication.buildLogoutUrl();
authentication.userInfo('abcd1234', (err, data) => {
//user info retrieved
});
authentication.delegation({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
refresh_token: 'your_refresh_token',
api_type: 'app'
}, (err, data) => {
});
authentication.loginWithDefaultDirectory({
username: 'someUsername',
password: '123456'
}, (err, data) => {
});
authentication.oauthToken({
username: 'someUsername',
password: '123456',
grantType: 'password'
}, (err, data) => {
});
authentication.getUserCountry((err, data) => {
});
authentication.getSSOData();
authentication.getSSOData(true, (err, data) => {});
authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password: '123456'}, () => {});
authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {});
authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {});
authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {});
authentication.loginWithResourceOwner({
username: 'the username',
password: 'the password',
connection: 'the_connection',
scope: 'openid'
}, (err, data) => {});
let management = new auth0.Management({
domain: 'me.auth0.com',
token: 'token'
});
management.getUser('asd', (err, user) => {});
management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {});
management.linkUser('asd', 'eqwe', (err, user) => {});
+452 -132
View File
@@ -1,136 +1,456 @@
// Type definitions for Auth0.js
// Type definitions for Auth0.js 8.1
// Project: https://github.com/auth0/auth0.js
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions by: Adrian Chia <https://github.com/adrianchia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** Extensions to the browser Window object. */
interface Window {
/** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */
token: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: Function): void;
decodeJwt(jwt: string): any;
login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void;
loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
logout(query: string): void;
getConnections(callback?: Function): void;
refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getProfile(id_token: string, callback?: Function): Auth0UserProfile;
getSSOData(withActiveDirectories: any, callback?: Function): void;
parseHash(hash: string): Auth0DecodedHash;
signup(options: Auth0SignupOptions, callback: Function): void;
validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void;
}
/** Represents constructor options for the Auth0 client. */
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLocationHash?: boolean;
responseType?: string;
domain: string;
forceJSONP?: boolean;
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;
locale: string;
name: string;
nickname: string;
picture: string;
user_id: string;
/** Represents one or more Identities that may be associated with the User. */
identities: Auth0Identity[];
user_metadata?: any;
app_metadata?: any;
}
/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */
interface MicrosoftUserProfile extends Auth0UserProfile {
emails: string[];
}
/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */
interface AdfsUserProfile extends Auth0UserProfile {
issuer: string;
}
/** Represents multiple identities assigned to a user. */
interface Auth0Identity {
access_token: string;
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
interface Auth0DecodedHash {
access_token: string;
idToken: string;
profile: Auth0UserProfile;
state: any;
error: string;
}
interface Auth0PopupOptions {
width: number;
height: number;
}
interface Auth0LoginOptions {
auto_login?: boolean;
responseType?: string;
connection?: string;
email?: string;
username?: string;
password?: string;
popup?: boolean;
popupOptions?: Auth0PopupOptions;
}
interface Auth0SignupOptions extends Auth0LoginOptions {
auto_login: boolean;
}
interface Auth0Error {
code: any;
details: any;
name: string;
message: string;
status: any;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
expires_in: string;
/** The JWT for delegated access. */
id_token: string;
/** The type of token being returned. Possible values: "Bearer" */
token_type: string;
}
declare const Auth0: Auth0Static;
declare module "auth0-js" {
export = Auth0
declare namespace auth0 {
export class Authentication {
constructor(options: AuthOptions);
passwordless: PasswordlessAuthentication;
dbConnection: DBConnection;
/**
* Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction
*
* @method buildAuthorizeUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
buildAuthorizeUrl(options: any): string;
/**
* Builds and returns the Logout url in order to initialize a new authN/authZ transaction
*
* @method buildLogoutUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
buildLogoutUrl(options?: any): string;
/**
* Makes a call to the `oauth/token` endpoint with `password` grant type
*
* @method loginWithDefaultDirectory
* @param {Object} options: https://auth0.com/docs/api-auth/grant/password
* @param {Function} callback
*/
loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ro` endpoint
* @param {any} options
* @param {Function} callback
* @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead.
*/
loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint with `password-realm` grant type
* @param {any} options
* @param {Function} callback
*/
login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `oauth/token` endpoint
* @param {any} options
* @param {Function} callback
*/
oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
* @deprecated `getSSOData` will be soon deprecated.
*/
getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Makes a call to the `/userinfo` endpoint and returns the user profile
*
* @method userInfo
* @param {String} accessToken
* @param {Function} callback
*/
userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Makes a call to the `/delegation` endpoint
*
* @method delegation
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation
* @param {Function} callback
* @deprecated `delegation` will be soon deprecated.
*/
delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any;
/**
* Fetches the user country based on the ip.
*
* @method getUserCountry
* @param {Function} callback
*/
getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void;
}
export class PasswordlessAuthentication {
constructor(request: any, option: any);
/**
* Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
buildVerifyUrl(options: any): string;
/**
* Initializes a new passwordless authN/authZ transaction
*
* @method start
* @param {Object} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Function} callback
*/
start(options: PasswordlessStartOptions, callback: any): void;
/**
* Verifies the passwordless TOTP and returns an error if any.
*
* @method buildVerifyUrl
* @param {Object} options
* @param {Function} callback
*/
verify(options: any, callback: any): void;
}
export class DBConnection {
constructor(request: any, option: any);
/**
* Signup a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} calback
*/
signup(options: any, callback: any): void;
/**
* Initializes the change password flow
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: ChangePasswordOptions, callback: any): void;
}
export class Management {
constructor(options: ManagementOptions);
/**
* Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id
*
* @method getUser
* @param {String} userId
* @param {Function} callback
*/
getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Updates the user metdata. It will patch the user metdata with the attributes sent.
* https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
*
* @method patchUserMetadata
* @param {String} userId
* @param {Object} userMetadata
* @param {Function} callback
*/
patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void;
/**
* Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities
*
* @method linkUser
* @param {String} userId
* @param {String} secondaryUserToken
* @param {Function} callback
*/
linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void;
}
export class WebAuth {
constructor(options: AuthOptions);
client: Authentication;
popup: Popup;
redirect: Redirect;
/**
* Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
authorize(options: any): void;
/**
* Parse the url hash and extract the returned tokens depending on the transaction.
*
* Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed
* by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be
* accepted.
*
* @method parseHash
* @param {Object} options:
* @param {String} options.state [OPTIONAL] to verify the response
* @param {String} options.nonce [OPTIONAL] to verify the id_token
* @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash
* @param {Function} callback: any(err, token_payload)
*/
parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Decodes the id_token and verifies the nonce.
*
* @method validateToken
* @param {String} token
* @param {String} state
* @param {String} nonce
* @param {Function} callback: function(err, {payload, transaction})
*/
validateToken(token: string, state: string, nonce: string, callback: any): void;
/**
* Executes a silent authentication transaction under the hood in order to fetch a new token.
*
* @method renewAuth
* @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint
* @param {Function} callback
*/
renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Initialices a change password transaction
*
* @method changePassword
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Signs up a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signup(options: any, callback: any): void;
/**
* Signs up a new user, automatically logs the user in after the signup and returns the user token.
* The login will be done using /oauth/token with password-realm grant type.
*
* @method signupAndAuthorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void;
/**
* Redirects to the auth0 logout page
*
* @method logout
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
logout(options: any): void;
passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void;
/**
* Verifies the passwordless TOTP and redirects to finish the passwordless transaction
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
}
export class Redirect {
constructor(client: any, options: any);
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
export class Popup {
constructor(client: any, options: any);
/**
* Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser.
*
* @method preload
* @param {Object} options: receives the window height and width and any other window feature to be sent to window.open
*/
preload(options: any): any;
/**
* Internal use.
*
* @method getPopupHandler
*/
getPopupHandler(options: any, preload: boolean): any;
/**
* Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
* @param {Function} callback
*/
authorize(options: any, callback: any): void;
/**
* Initializes the legacy Lock login flow in a popup
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
*/
loginWithCredentials(options: any, callback: any): void;
/**
* Verifies the passwordless TOTP and returns the requested token
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: any): void;
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndLogin(options: any, callback: any): void;
}
interface ManagementOptions {
domain: string;
token: string;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface AuthOptions {
domain: string;
clientID: string;
responseType?: string;
responseMode?: string;
redirectUri?: string;
scope?: string;
audience?: string;
leeway?: number;
_disableDeprecationWarnings?: boolean;
_sendTelemetry?: boolean;
_telemetryInfo?: any;
}
interface PasswordlessAuthOptions {
connection: string;
verificationCode: string;
phoneNumber: string;
email: string;
}
interface Auth0Error {
error: any;
errorDescription: string;
}
interface Auth0DecodedHash {
accessToken?: string;
idToken?: string;
idTokenPayload?: any;
refreshToken?: string;
state?: string;
expiresIn?: number;
tokenType?: string;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
ExpiresIn: number;
/** The JWT for delegated access. */
idToken: string;
/** The type of token being returned. Possible values: "Bearer" */
tokenType: string;
}
interface ChangePasswordOptions {
connection: string;
email: string;
password?: string;
}
interface PasswordlessStartOptions {
connection: string;
send: string;
phoneNumber?: string;
email?: string;
authParams?: any;
}
interface PasswordlessVerifyOptions {
connection: string;
verificationCode: string;
phoneNumber?: string;
email?: string;
}
}
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"auth0-js-tests.ts"
]
}
}
+23
View File
@@ -0,0 +1,23 @@
import 'auth0-js';
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
});
auth0.login({
connection: 'google-oauth2',
popup: true,
popupOptions: {
width: 450,
height: 800
}
}, (err, profile, idToken, accessToken, state) => {
if (err) {
alert("something went wrong: " + err.message);
return;
}
alert('hello ' + profile.name);
});
+136
View File
@@ -0,0 +1,136 @@
// Type definitions for Auth0.js 7.0
// Project: https://github.com/auth0/auth0.js
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** Extensions to the browser Window object. */
interface Window {
/** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */
token: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: (error?: Auth0Error, valid?: any) => void): void;
decodeJwt(jwt: string): any;
login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void;
loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
logout(query: string): void;
getConnections(callback?: (error?: Auth0Error, valid?: any) => void): void;
refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getProfile(id_token: string, callback?: (error?: Auth0Error, valid?: any) => void): Auth0UserProfile;
getSSOData(withActiveDirectories: any, callback?: (error?: Auth0Error, valid?: any) => void): void;
parseHash(hash: string): Auth0DecodedHash;
signup(options: Auth0SignupOptions, callback: (error?: Auth0Error, valid?: any) => void): void;
validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void;
}
/** Represents constructor options for the Auth0 client. */
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLocationHash?: boolean;
responseType?: string;
domain: string;
forceJSONP?: boolean;
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;
locale: string;
name: string;
nickname: string;
picture: string;
user_id: string;
/** Represents one or more Identities that may be associated with the User. */
identities: Auth0Identity[];
user_metadata?: any;
app_metadata?: any;
}
/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */
interface MicrosoftUserProfile extends Auth0UserProfile {
emails: string[];
}
/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */
interface AdfsUserProfile extends Auth0UserProfile {
issuer: string;
}
/** Represents multiple identities assigned to a user. */
interface Auth0Identity {
access_token: string;
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
interface Auth0DecodedHash {
access_token: string;
idToken: string;
profile: Auth0UserProfile;
state: any;
error: string;
}
interface Auth0PopupOptions {
width: number;
height: number;
}
interface Auth0LoginOptions {
auto_login?: boolean;
responseType?: string;
connection?: string;
email?: string;
username?: string;
password?: string;
popup?: boolean;
popupOptions?: Auth0PopupOptions;
}
interface Auth0SignupOptions extends Auth0LoginOptions {
auto_login: boolean;
}
interface Auth0Error {
code: any;
details: any;
name: string;
message: string;
status: any;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
expires_in: string;
/** The JWT for delegated access. */
id_token: string;
/** The type of token being returned. Possible values: "Bearer" */
token_type: string;
}
declare const Auth0: Auth0Static;
declare module "auth0-js" {
export = Auth0;
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"paths": {
"auth0-js": ["auth0-js/v7"],
"auth0-js/*": ["auth0-js/v7/*"]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"auth0-js-tests.ts"
]
}
+2 -2
View File
@@ -1,5 +1,5 @@
/// <reference types="auth0-js" />
/// <reference path="index.d.ts" />
import 'auth0-js/v7';
import Auth0Lock from 'auth0-lock';
const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID";
const DOMAIN = "YOUR_DOMAIN_AT.auth0.com";
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Brian Caruso <https://github.com/carusology>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js" />
/// <reference types="auth0-js/v7" />
interface Auth0LockAdditionalSignUpFieldOption {
value: string;
+5
View File
@@ -0,0 +1,5 @@
{
"dependencies": {
"@types/auth0-js": "latest"
}
}
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"auth0-lock-tests.ts"
]
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
/// <reference types="auth0-js" />
import 'auth0-js/v7';
var widget: Auth0WidgetStatic = new Auth0Widget({
domain: 'mine.auth0.com',
+1 -2
View File
@@ -3,8 +3,7 @@
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js" />
/// <reference types="auth0-js/v7" />
interface Auth0WidgetStatic {
new(params: Auth0Constructor): Auth0WidgetStatic;
+5
View File
@@ -0,0 +1,5 @@
{
"dependencies": {
"@types/auth0-js": "latest"
}
}
+1 -1
View File
@@ -19,4 +19,4 @@
"index.d.ts",
"auth0.widget-tests.ts"
]
}
}
+341 -22
View File
@@ -1,6 +1,6 @@
// Type definitions for auth0 v2.3.1
// Type definitions for auth0 2.4
// Project: https://github.com/auth0/node-auth0
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as Promise from 'bluebird';
@@ -10,8 +10,8 @@ export interface ManagementClientOptions {
domain?: string;
}
export type UserMetadata = {};
export type AppMetadata = {};
export interface UserMetadata { }
export interface AppMetadata { }
export interface UserData {
connection: string;
@@ -71,34 +71,353 @@ export interface UpdateUserParameters {
id: string;
}
export class ManagementClient {
constructor(options: ManagementClientOptions);
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
updateUser(params: UpdateUserParameters, data: User): Promise<User>;
updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise<User>;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise<User>;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void
}
export interface AuthenticationClientOptions {
clientId?: string;
domain: string;
}
export interface RequestChangePasswordEmailData {
interface Environment {
name: string;
version: string;
}
export interface ClientInfo {
name: string;
version: string;
dependencies: any[];
environment: Environment[];
}
export interface RequestEmailOptions {
email: string;
authParams: {};
}
export interface RequestSMSOptions {
phone_number: string;
}
export interface VerifyOptions {
username: string;
password: string;
}
export interface DelegationTokenOptions {
id_token: string;
api_type: string;
scope: string;
target: string;
grant_type: string;
}
export interface ResetPasswordOptions {
connection: string;
email: string;
password: string;
}
export interface ResetPasswordEmailOptions {
email: string;
connection: string;
}
export interface ObjectWithId {
id: string;
}
export interface Data {
name?: string;
[propName: string]: any;
}
export interface ClientParams {
client_id: string;
}
export interface DeleteMultifactorParams {
id: string;
provider: string;
}
export interface LinkAccountsParams {
id: string;
provider: string;
user_id: string;
}
export interface LinkAccountsData {
user_id: string;
connection_id: string;
}
export interface Token {
aud: string;
jti: string;
}
export interface StatsParams {
from: string;
to: string;
}
export interface ImportUsersOptions {
connection_id: string;
users: string;
}
export interface UserIdParams {
user_id: string;
}
export interface PasswordChangeTicketParams {
result_url: string;
user_id: string;
email: string;
new_password: string;
}
export interface EmailVerificationTicketOptions {
user_id: string;
result_url: string;
}
export class AuthenticationClient {
constructor(options: AuthenticationClientOptions);
getClientInfo(): ClientInfo;
requestMagicLink(data: RequestEmailOptions): Promise<any>;
requestMagicLink(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void;
requestEmailCode(data: RequestEmailOptions): Promise<any>;
requestEmailCode(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void;
requestSMSCode(data: RequestSMSOptions): Promise<any>;
requestSMSCode(data: RequestSMSOptions, cb: (err: Error, message: string) => void): void;
verifyEmailCode(data: VerifyOptions): Promise<any>;
verifyEmailCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void;
verifySMSCode(data: VerifyOptions): Promise<any>;
verifySMSCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void;
getDelegationToken(data: DelegationTokenOptions): Promise<any>;
getDelegationToken(data: DelegationTokenOptions, cb: (err: Error, message: string) => void): void;
changePassword(data: ResetPasswordOptions): Promise<any>;
changePassword(data: ResetPasswordOptions, cb: (err: Error, message: string) => void): void;
requestChangePasswordEmail(data: ResetPasswordEmailOptions): Promise<any>;
requestChangePasswordEmail(data: ResetPasswordEmailOptions, cb: (err: Error, message: string) => void): void;
getProfile(accessToken: string): Promise<any>;
getProfile(accessToken: string, cb: (err: Error, message: string) => void): void;
getCredentialsGrant(scope: string): Promise<any>;
getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void;
}
export class ManagementClient {
constructor(options: ManagementClientOptions);
getClientInfo(): ClientInfo;
// Connections
getConnections(): Promise<User>;
getConnections(cb: (err: Error, data: any) => void): void;
createConnection(data: ObjectWithId): Promise<User>;
createConnection(data: ObjectWithId, cb: (err: Error, data: any) => void): void;
getConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
getConnection(params: ObjectWithId): Promise<User>;
deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
deleteConnection(params: ObjectWithId): Promise<User>;
deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
deleteConnection(params: ObjectWithId): Promise<User>;
updateConnection(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
updateConnection(params: ObjectWithId, data: Data): Promise<User>;
// Clients
getClients(): Promise<User>;
getClients(cb: (err: Error, data: any) => void): void;
getClient(params: ClientParams): Promise<User>;
getClient(params: ClientParams, cb: (err: Error, data: any) => void): void;
createClient(data: Data): Promise<User>;
createClient(data: Data, cb: (err: Error, data: any) => void): void;
updateClient(params: ClientParams, data: Data): Promise<User>;
updateClient(params: ClientParams, data: Data, cb: (err: Error, data: any) => void): void;
deleteClient(params: ClientParams): Promise<User>;
deleteClient(params: ClientParams, cb: (err: Error, data: any) => void): void;
// Client Grants
getClientGrants(): Promise<User>;
getClientGrants(cb: (err: Error, data: any) => void): void;
createClientGrant(data: Data): Promise<User>;
createClientGrant(data: Data, cb: (err: Error, data: any) => void): void;
updateClientGrant(params: ObjectWithId, data: Data): Promise<User>;
updateClientGrant(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
deleteClientGrant(params: ObjectWithId): Promise<User>;
deleteClientGrant(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
// Device Keys
getDeviceCredentials(): Promise<User>;
getDeviceCredentials(cb: (err: Error, data: any) => void): void;
createDevicePublicKey(data: Data): Promise<User>;
createDevicePublicKey(data: Data, cb: (err: Error, data: any) => void): void;
deleteDeviceCredential(params: ClientParams): Promise<User>;
deleteDeviceCredential(params: ClientParams, cb: (err: Error, data: any) => void): void;
// Rules
getRules(): Promise<User>;
getRules(cb: (err: Error, data: any) => void): void;
getRule(params: ClientParams): Promise<User>;
getRule(params: ClientParams, cb: (err: Error, data: any) => void): void;
createRules(data: Data): Promise<User>;
createRules(data: Data, cb: (err: Error, data: any) => void): void;
updateRule(params: ObjectWithId, data: Data): Promise<User>;
updateRule(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
deleteRule(params: ObjectWithId): Promise<User>;
deleteRule(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
// Users
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
getUser(params?: ObjectWithId): Promise<User[]>;
getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
updateUser(params: UpdateUserParameters, data: User): Promise<User>;
updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise<User>;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void;
deleteAllUsers(): Promise<User>;
deleteAllUsers(cb: (err: Error, data: any) => void): void;
deleteUser(params?: ObjectWithId): Promise<any>;
deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise<User>;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void;
deleteUserMultifactor(params: DeleteMultifactorParams): Promise<any>;
deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void;
unlinkUsers(params: LinkAccountsParams): Promise<any>;
unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void;
linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise<any>;
linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void;
// Tokens
getBlacklistedTokens(): Promise<any>;
getBlacklistedTokens(cb?: (err: Error, data: any) => void): void;
blacklistToken(token: Token): Promise<any>;
blacklistToken(token: Token, cb: (err: Error, data: any) => void): void;
// Providers
getEmailProvider(): Promise<any>;
getEmailProvider(cb?: (err: Error, data: any) => void): void;
configureEmailProvider(data: Data): Promise<any>;
configureEmailProvider(data: Data, cb: (err: Error, data: any) => void): void;
deleteEmailProvider(): Promise<any>;
deleteEmailProvider(cb?: (err: Error, data: any) => void): void;
updateEmailProvider(data: Data): Promise<any>;
updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void;
// Statistics
getActiveUsersCount(): Promise<any>;
getActiveUsersCount(cb?: (err: Error, data: any) => void): void;
getDailyStats(data: StatsParams): Promise<any>;
getDailyStats(data: StatsParams, cb: (err: Error, data: any) => void): void;
// Tenant
getTenantSettings(): Promise<any>;
getTenantSettings(cb?: (err: Error, data: any) => void): void;
updateTenantSettings(data: Data): Promise<any>;
updateTenantSettings(data: Data, cb?: (err: Error, data: any) => void): void;
// Jobs
getJob(params: ObjectWithId): Promise<any>;
getJob(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
importUsers(data: ImportUsersOptions): Promise<any>;
importUsers(data: ImportUsersOptions, cb?: (err: Error, data: any) => void): void;
sendEmailVerification(data: UserIdParams): Promise<any>;
sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void;
// Tickets
createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise<any>;
createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void;
createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise<any>;
createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void;
// Logs
getLog(params: ObjectWithId): Promise<any>;
getLog(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
getLogs(): Promise<any>;
getLogs(cb?: (err: Error, data: any) => void): void;
// Resource Server
createResourceServer(data: Data): Promise<any>;
createResourceServer(data: Data, cb?: (err: Error, data: any) => void): void;
getResourceServers(): Promise<any>;
getResourceServers(cb?: (err: Error, data: any) => void): void;
getResourceServer(data: ObjectWithId): Promise<any>;
getResourceServer(data: ObjectWithId, cb?: (err: Error, data: any) => void): void;
deleteResourceServer(params: ObjectWithId): Promise<any>;
deleteResourceServer(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
updateResourceServer(params: ObjectWithId, data: Data): Promise<any>;
updateResourceServer(params: ObjectWithId, data: Data, cb?: (err: Error, data: any) => void): void;
requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise<string>;
requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void;
}
+18
View File
@@ -8,3 +8,21 @@ autosize(document.querySelector('textarea'));
// from a single element
autosize(document.getElementById('my-textarea'));
// update a NodeList
autosize.update(document.querySelectorAll('textarea'));
// update a single Node
autosize.update(document.querySelector('textarea'));
// update a single element
autosize.update(document.getElementById('my-textarea'));
// destroy a NodeList
autosize.destroy(document.querySelectorAll('textarea'));
// destroy a single Node
autosize.destroy(document.querySelector('textarea'));
// destroy a single element
autosize.destroy(document.getElementById('my-textarea'));
+5 -1
View File
@@ -1,12 +1,16 @@
// Type definitions for jquery.autosize 3.0.7
// Project: http://www.jacklmoore.com/autosize/
// Definitions by: Aaron T. King <https://github.com/kingdango>
// Definitions by: Aaron T. King <https://github.com/kingdango>, keika299 <https://github.com/keika299>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace autosize {
interface AutosizeStatic {
(el: Element): void;
(el: NodeList): void;
update(el: Element): void;
update(el: NodeList): void;
destroy(el: Element): void;
destroy(el: NodeList): void;
}
}
+47
View File
@@ -6,11 +6,48 @@ var anyObj: any = { abc: 123 };
var num: number = 5;
var error: Error = new Error();
var b: boolean = true;
var apiGwEvt: AWSLambda.APIGatewayEvent;
var clientCtx: AWSLambda.ClientContext;
var clientContextEnv: AWSLambda.ClientContextEnv;
var clientContextClient: AWSLambda.ClientContextClient;
var context: AWSLambda.Context;
var identity: AWSLambda.CognitoIdentity;
var proxyResult: AWSLambda.ProxyResult;
/* API Gateway Event */
str = apiGwEvt.body;
str = apiGwEvt.headers["example"];
str = apiGwEvt.httpMethod;
b = apiGwEvt.isBase64Encoded;
str = apiGwEvt.path;
str = apiGwEvt.pathParameters["example"];
str = apiGwEvt.queryStringParameters["example"];
str = apiGwEvt.stageVariables["example"];
str = apiGwEvt.requestContext.accountId;
str = apiGwEvt.requestContext.apiId;
str = apiGwEvt.requestContext.httpMethod;
str = apiGwEvt.requestContext.identity.accessKey;
str = apiGwEvt.requestContext.identity.accountId;
str = apiGwEvt.requestContext.identity.apiKey;
str = apiGwEvt.requestContext.identity.caller;
str = apiGwEvt.requestContext.identity.cognitoAuthenticationProvider;
str = apiGwEvt.requestContext.identity.cognitoAuthenticationType;
str = apiGwEvt.requestContext.identity.cognitoIdentityId;
str = apiGwEvt.requestContext.identity.cognitoIdentityPoolId;
str = apiGwEvt.requestContext.identity.sourceIp;
str = apiGwEvt.requestContext.identity.user;
str = apiGwEvt.requestContext.identity.userAgent;
str = apiGwEvt.requestContext.identity.userArn;
str = apiGwEvt.requestContext.stage;
str = apiGwEvt.requestContext.requestId;
str = apiGwEvt.requestContext.resourceId;
str = apiGwEvt.requestContext.resourcePath;
str = apiGwEvt.resource;
/* Lambda Proxy Result */
num = proxyResult.statusCode;
str = proxyResult.headers["example"];
str = proxyResult.body
/* Context */
b = context.callbackWaitsForEmptyEventLoop;
@@ -54,6 +91,15 @@ function callback(cb: AWSLambda.Callback) {
cb(error);
cb(null, anyObj);
}
/* Proxy Callback */
function proxyCallback(cb: AWSLambda.ProxyCallback) {
cb();
cb(null);
cb(error);
cb(null, proxyResult);
}
/* Compatibility functions */
context.done();
context.done(error);
@@ -66,3 +112,4 @@ context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => {};
let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => {};
+47 -1
View File
@@ -1,8 +1,44 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>, Toby Hede <https://github.com/tobyhede>
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>, Toby Hede <https://github.com/tobyhede>, Rich Buggy <https://github.com/buggy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// API Gateway "event"
interface APIGatewayEvent {
body: string | null;
headers: { [name: string]: string };
httpMethod: string;
isBase64Encoded: boolean;
path: string;
pathParameters: { [name: string]: string } | null;
queryStringParameters: { [name: string]: string } | null;
stageVariables: { [name: string]: string } | null;
requestContext: {
accountId: string;
apiId: string;
httpMethod: string;
identity: {
accessKey: string | null;
accountId: string | null;
apiKey: string | null;
caller: string | null;
cognitoAuthenticationProvider: string | null;
cognitoAuthenticationType: string | null;
cognitoIdentityId: string | null;
cognitoIdentityPoolId: string | null;
sourceIp: string;
user: string | null;
userAgent: string | null;
userArn: string | null;
},
stage: string;
requestId: string;
resourceId: string;
resourcePath: string;
};
resource: string;
}
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
interface Context {
@@ -58,6 +94,14 @@ interface ClientContextEnv {
locale: string;
}
interface ProxyResult {
statusCode: number;
headers?: {
[header: string]: string;
},
body: string;
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -67,6 +111,7 @@ interface ClientContextEnv {
* @param callback optional callback to return information to the caller, otherwise return value is null.
*/
export type Handler = (event: any, context: Context, callback?: Callback) => void;
export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => void;
/**
* Optional callback parameter.
@@ -76,5 +121,6 @@ export type Handler = (event: any, context: Context, callback?: Callback) => vo
* @param result an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
*/
export type Callback = (error?: Error, result?: any) => void;
export type ProxyCallback = (error?: Error, result?: ProxyResult) => void;
export as namespace AWSLambda;
-107
View File
@@ -1,107 +0,0 @@
enum HttpMethod { GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH }
enum ResponseType { arraybuffer, blob, document, json, text }
interface Repository {
id: number;
name: string;
}
interface Issue {
id: number;
title: string;
}
axios.interceptors.request.use<any>(config => {
console.log("Method:" + config.method + " Url:" +config.url);
return config;
});
const requestId: number = axios.interceptors.request.use<any>(
(config) => {
console.log("Method:" + config.method + " Url:" +config.url);
return config;
},
(error: any) => error);
axios.interceptors.request.eject(requestId);
axios.interceptors.request.eject(7);
axios.interceptors.response.use<any>(config => {
console.log("Status:" + config.status);
return config;
});
const responseId: number = axios.interceptors.response.use<any>(
config => {
console.log("Status:" + config.status);
return config;
},
(error: any) => error);
axios.interceptors.response.eject(responseId);
axios.get<Repository>("https://api.github.com/repos/mzabriskie/axios")
.then(r => console.log(r.config.method));
var getRepoDetails = axios<Repository>({
url: "https://api.github.com/repos/mzabriskie/axios",
method: HttpMethod[HttpMethod.GET],
headers: {},
}).then(r => {
console.log("ID:" + r.data.id + " Name: " + r.data.name);
return r;
});
axios.post("http://example.com/", {}, {
transformRequest: (data: any) => data
});
axios.post("http://example.com/", {
headers: {'X-Custom-Header': 'foobar'}
}, {
transformRequest: [
(data: any) => data
]
});
var config: Axios.AxiosXHRConfigBase<any> = {headers: {}};
config.headers['X-Custom-Header'] = 'baz';
axios.post("http://example.com/", config);
var getRepoIssue = axios.get<Issue>("https://api.github.com/repos/mzabriskie/axios/issues/1");
var axiosInstance = axios.create({
baseURL: "https://api.github.com/repos/mzabriskie/axios/",
timeout: 1000
});
axiosInstance.request({url: "issues/1"}).then(res => {
if (res.headers['content-type'].startsWith('application/json')) {
throw new Error('Unexpected content-type');
}
});
axios.all<Repository, Repository>([getRepoDetails, getRepoDetails]).then(([repo1, repo2]) => {
var sumIds = repo1.data.id + repo2.data.id;
console.log("Sum ID:" + sumIds);
return sumIds;
});
var repoSum = (repo1: Axios.AxiosXHR<Repository>, repo2: Axios.AxiosXHR<Repository>) => {
var sumIds = repo1.data.id + repo2.data.id;
console.log("Sum ID:" + sumIds);
return sumIds;
};
axios.all<Repository, Repository>([getRepoDetails, getRepoDetails]).then(axios.spread(repoSum));
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = "AUTH_TOKEN";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN";
-316
View File
@@ -1,316 +0,0 @@
// Type definitions for axios 0.9.1
// Project: https://github.com/mzabriskie/axios
// Definitions by: Marcel Buesing <https://github.com/marcelbuesing>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Axios {
interface IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IThenable<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IThenable<U>;
}
interface IPromise<R> extends IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
}
/**
* HTTP Basic auth details
*/
interface AxiosHttpBasicAuth {
username: string;
password: string;
}
/**
* Common axios XHR config interface
* <T> - request body data type
*/
interface AxiosXHRConfigBase<T> {
/**
* will be prepended to `url` unless `url` is absolute.
* It can be convenient to set `baseURL` for an instance
* of axios to pass relative URLs to methods of that instance.
*/
baseURL?: string;
/**
* custom headers to be sent
*/
headers?: {[key: string]: any};
/**
* URL parameters to be sent with the request
*/
params?: Object;
/**
* optional function in charge of serializing `params`
* (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
*/
paramsSerializer?: (params: Object) => string;
/**
* specifies the number of milliseconds before the request times out.
* If the request takes longer than `timeout`, the request will be aborted.
*/
timeout?: number;
/**
* indicates whether or not cross-site Access-Control requests
* should be made using credentials
*/
withCredentials?: boolean;
/**
* indicates that HTTP Basic auth should be used, and supplies
* credentials. This will set an `Authorization` header,
* overwriting any existing `Authorization` custom headers you have
* set using `headers`.
*/
auth?: AxiosHttpBasicAuth;
/**
* indicates the type of data that the server will respond with
* options are 'arraybuffer', 'blob', 'document', 'json', 'text'
*/
responseType?: string;
/**
* name of the cookie to use as a value for xsrf token
*/
xsrfCookieName?: string;
/**
* name of the http header that carries the xsrf token value
*/
xsrfHeaderName?: string;
/**
* Change the request data before it is sent to the server.
* This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
* The last function in the array must return a string or an ArrayBuffer
*/
transformRequest?: (<U>(data: T) => U) | [<U>(data: T) => U];
/**
* change the response data to be made before it is passed to then/catch
*/
transformResponse?: <U>(data: T) => U;
/**
* defines whether to resolve or reject the promise for a given HTTP response status code.
* If returns `true` (or is set to `null` or `undefined`), the promise will be resolved;
* otherwise, the promise will be rejected
*/
validateStatus?: (status: number) => boolean | undefined;
}
/**
* <T> - request body data type
*/
interface AxiosXHRConfig<T> extends AxiosXHRConfigBase<T> {
/**
* server URL that will be used for the request, options are:
* GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH
*/
url: string;
/**
* request method to be used when making the request
*/
method?: string;
/**
* data to be sent as the request body
* Only applicable for request methods 'PUT', 'POST', and 'PATCH'
* When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
*/
data?: T;
}
interface AxiosXHRConfigDefaults<T> extends AxiosXHRConfigBase<T> {
/**
* custom headers to be sent
*/
headers: {
common: {[index: string]: string};
patch: {[index: string]: string};
post: {[index: string]: string};
put: {[index: string]: string};
};
}
/**
* <T> - expected response type,
* <U> - request body data type
*/
interface AxiosXHR<T> {
/**
* Response that was provided by the server
*/
data: T;
/**
* HTTP status code from the server response
*/
status: number;
/**
* HTTP status message from the server response
*/
statusText: string;
/**
* headers that the server responded with
*/
headers: {[index: string]: any};
/**
* config that was provided to `axios` for the request
*/
config: AxiosXHRConfig<T>;
}
interface Interceptor {
/**
* intercept request before it is sent
*/
request: RequestInterceptor;
/**
* intercept response of request when it is received.
*/
response: ResponseInterceptor
}
type InterceptorId = number;
interface RequestInterceptor {
/**
* <U> - request body data type
*/
use<U>(fulfilledFn: (config: AxiosXHRConfig<U>) => AxiosXHRConfig<U>): InterceptorId;
use<U>(fulfilledFn: (config: AxiosXHRConfig<U>) => AxiosXHRConfig<U>,
rejectedFn: (error: any) => any)
: InterceptorId;
eject(interceptorId: InterceptorId): void;
}
interface ResponseInterceptor {
/**
* <T> - expected response type
*/
use<T>(fulfilledFn: (config: Axios.AxiosXHR<T>) => Axios.AxiosXHR<T>): InterceptorId;
use<T>(fulfilledFn: (config: Axios.AxiosXHR<T>) => Axios.AxiosXHR<T>,
rejectedFn: (error: any) => any)
: InterceptorId;
eject(interceptorId: InterceptorId): void;
}
/**
* <T> - expected response type,
* <U> - request body data type
*/
interface AxiosInstance {
/**
* Send request as configured
*/
<T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* Send request as configured
*/
new <T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* Send request as configured
*/
request<T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* intercept requests or responses before they are handled by then or catch
*/
interceptors: Interceptor;
/**
* Config defaults
*/
defaults: AxiosXHRConfigDefaults<any>;
/**
* equivalent to `Promise.all`
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>, T9 | IPromise<AxiosXHR<T9>>, T10 | IPromise<AxiosXHR<T10>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>, AxiosXHR<T9>, AxiosXHR<T10>]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>, T9 | IPromise<AxiosXHR<T9>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>, AxiosXHR<T9>]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>]>;
all<T1, T2, T3, T4, T5>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>]>;
all<T1, T2, T3, T4>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>]>;
all<T1, T2, T3>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>]>;
all<T1, T2>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>]>;
/**
* spread array parameter to `fn`.
* note: alternative to `spread`, destructuring assignment.
*/
spread<T1, T2, U>(fn: (t1: T1, t2: T2) => U): (arr: ([T1, T2])) => U;
/**
* convenience alias, method = GET
*/
get<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = DELETE
*/
delete<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = HEAD
*/
head<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = POST
*/
post<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = PUT
*/
put<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = PATCH
*/
patch<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
}
/**
* <T> - expected response type,
*/
interface AxiosStatic extends AxiosInstance {
/**
* create a new instance of axios with a custom config
*/
create<T>(config: AxiosXHRConfigBase<T>): AxiosInstance;
}
}
declare var axios: Axios.AxiosStatic;
declare module "axios" {
export = axios;
}
+13
View File
@@ -109,3 +109,16 @@ const v1: Visitor = {
path.scope.rename("n");
}
};
// Binding.kind
const BindingKindTest: Visitor = {
Identifier(path) {
const kind = path.scope.getBinding("str").kind;
kind === 'module';
kind === 'const';
kind === 'let';
kind === 'var';
// The following should fail when uncommented
// kind === 'anythingElse';
},
};
+1 -1
View File
@@ -126,7 +126,7 @@ export class Binding {
identifier: t.Identifier;
scope: Scope;
path: NodePath<Node>;
kind: 'var' | 'let' | 'const';
kind: 'var' | 'let' | 'const' | 'module';
referenced: boolean;
references: number;
referencePaths: NodePath<Node>[];
+4 -2
View File
@@ -3,9 +3,11 @@
// Definitions by: Clément Bourgeois <https://github.com/moonpyk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as Express from 'express';
/// <reference types="node" />
declare function auth(req: Express.Request): auth.BasicAuthResult;
import * as http from 'http';
declare function auth(req: http.IncomingMessage): auth.BasicAuthResult;
declare namespace auth {
interface BasicAuthResult {
+2 -2
View File
@@ -10,7 +10,7 @@ function test() {
var utils = bezier.getUtils();
var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } };
var abc: BezierJs.ABC = { A: null, B: null, C: null };
var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 };
var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1, interval:{ start: 0, end: 1 } };
var bbox: BezierJs.BBox = bezier.bbox();
var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] };
@@ -95,4 +95,4 @@ function test() {
utils.round(.999, .001);
utils.shapeintersections(shape, bbox, shape, bbox);
}
}
+1
View File
@@ -51,6 +51,7 @@ declare namespace BezierJs {
e: number;
r: number;
s: number;
interval: { start: number; end: number; };
}
interface Shape {
startcap: BezierCap;
+1 -1
View File
@@ -5,7 +5,7 @@
declare module 'bintrees' {
type Callback = <T>(err: Error, item: T) => void;
type Callback = <T>(item: T) => void;
type Comparator = <T>(a: T, b: T) => number;
class Iterator<T> {
+21 -19
View File
@@ -1,20 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bittorrent-protocol-tests.ts"
]
}
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bittorrent-protocol-tests.ts"
]
}
+4 -1
View File
@@ -1,3 +1,6 @@
{
"extends": "../tslint.json"
"extends": "../tslint.json",
"rules": {
"no-misused-new": false
}
}
+74 -9
View File
@@ -1,6 +1,6 @@
// Type definitions for body-parser
// Project: http://expressjs.com
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/>
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/>, Gevik Babakhani <https://github.com/blendsdk/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -41,7 +41,14 @@ declare function bodyParser(options?: {
}): express.RequestHandler;
declare namespace bodyParser {
export function json(options?: {
/**
* Interface for defining the options for the json() middleware
*
* @export
* @interface JsonOptions
*/
export interface JsonOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@@ -66,9 +73,15 @@ declare namespace bodyParser {
* passed to JSON.parse().
*/
reviver?: (key: string, value: any) => any;
}): express.RequestHandler;
}
export function raw(options?: {
/**
* Interface for defining the options the raw() middleware
*
* @export
* @interface RawOptions
*/
export interface RawOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@@ -85,9 +98,15 @@ declare namespace bodyParser {
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
}): express.RequestHandler;
}
export function text(options?: {
/**
* Interface for defining the options for the text() middleware
*
* @export
* @interface TextOptions
*/
export interface TextOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@@ -108,9 +127,15 @@ declare namespace bodyParser {
* the default charset to parse as, if not specified in content-type. (default: 'utf-8')
*/
defaultCharset?: string;
}): express.RequestHandler;
}
export function urlencoded(options: {
/**
* Interface for defining the options for the urlencoded() middleware
*
* @export
* @interface UrlEncodedOptions
*/
export interface UrlEncodedOptions {
/**
* if deflated bodies will be inflated. (default: true)
*/
@@ -131,7 +156,47 @@ declare namespace bodyParser {
* parse extended syntax with the qs module.
*/
extended: boolean;
}): express.RequestHandler;
}
/**
* Returns middleware that only parses json. This parser accepts any Unicode encoding
* of the body and supports automatic inflation of gzip and deflate encodings.
*
* @export
* @param {JsonOptions} [options]
* @returns {express.RequestHandler}
*/
export function json(options?: JsonOptions): express.RequestHandler;
/**
* Returns middleware that parses all bodies as a Buffer. This parser supports automatic
* inflation of gzip and deflate encodings.
*
* @export
* @param {RawOptions} [options]
* @returns {express.RequestHandler}
*/
export function raw(options?: RawOptions): express.RequestHandler;
/**
* Returns middleware that parses all bodies as a string. This parser supports
* automatic inflation of gzip and deflate encodings.
*
* @export
* @param {TextOptions} [options]
* @returns {express.RequestHandler}
*/
export function text(options?: TextOptions): express.RequestHandler;
/**
* Returns middleware that only parses urlencoded bodies. This parser accepts only
* UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
*
* @export
* @param {UrlEncodedOptions} [options]
* @returns {express.RequestHandler}
*/
export function urlencoded(options?: UrlEncodedOptions): express.RequestHandler;
}
export = bodyParser;
+1
View File
@@ -2,6 +2,7 @@
// Project: http://bookshelfjs.org/
// Definitions by: Andrew Schurman <http://github.com/arcticwaters>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import Knex = require('knex');
import knex = require('knex');
+1 -1
View File
@@ -58,7 +58,7 @@ declare class BufferStream extends stream.Duplex {
shortcut for buffer.length
*/
length: number;
}
} // https://github.com/dodo/node-bufferstream/blob/master/src/buffer-stream.coffee#L28
declare namespace BufferStream {
export interface Opts {
+9
View File
@@ -248,6 +248,15 @@ declare namespace c3 {
*/
width?: number;
};
spline?: {
interpolation?: {
/**
* Set custom spline interpolation
*/
type?: 'linear' | 'linear-closed' | 'basis' | 'basis-open' | 'basis-closed' | 'bundle' | 'cardinal' | 'cardinal-open' | 'cardinal-closed' | 'monotone';
};
};
}
interface Data {
+1 -1
View File
@@ -147,7 +147,7 @@ export namespace types {
three,
quorum,
all,
localQuorm,
localQuorum,
eachQuorum,
serial,
localSerial,
+3 -2
View File
@@ -8,6 +8,7 @@
/// <reference types="enzyme" />
/// <reference types="chai" />
/// <reference types="react" />
/// <reference types="cheerio" />
declare namespace Chai {
type EnzymeSelector = string | React.StatelessComponent<any> | React.ComponentClass<any> | { [key: string]: any };
@@ -143,9 +144,9 @@ declare namespace Chai {
}
declare module "chai-enzyme" {
import { ShallowWrapper, ReactWrapper, CheerioWrapper } from "enzyme";
import { ShallowWrapper, ReactWrapper } from "enzyme";
type DebugWrapper = ShallowWrapper<any,any> | CheerioWrapper<any, any> | ReactWrapper<any, any>;
type DebugWrapper = ShallowWrapper<any,any> | Cheerio | ReactWrapper<any, any>;
function chaiEnzyMe(wrapper?: (debugWrapper: DebugWrapper) => string): (chai: any) => void;
module chaiEnzyMe {
+1
View File
@@ -55,6 +55,7 @@ declare namespace ChaiHttp {
send(data: Object): Request;
auth(user: string, name: string): Request;
field(name: string, val: string): Request;
buffer(): Request;
end(callback?: (err: any, res: Response) => void): FinishedRequest;
}
+17 -3
View File
@@ -9,19 +9,19 @@ import ChaiJsonSchema = require('chai-json-schema');
chai.use(ChaiJsonSchema);
chai.should();
let goodApple = {
const goodApple = {
skin: 'thin',
colors: ['red', 'green', 'yellow'],
taste: 10
};
let badApple = {
const badApple = {
colors: ['brown'],
taste: 0,
worms: 2
};
let fruitSchema = {
const fruitSchema = {
title: 'fresh fruit schema v1',
type: 'object',
required: ['skin', 'colors', 'taste'],
@@ -54,3 +54,17 @@ badApple.should.not.be.jsonSchema(fruitSchema);
//tdd style
assert.jsonSchema(goodApple, fruitSchema);
assert.notJsonSchema(badApple, fruitSchema);
// tv4
const schema = {
items: {
type: 'boolean'
}
};
const data1 = [true, false];
const data2 = [true, 123];
expect(chai.tv4.validate(data1, schema)).to.be.true;
expect(chai.tv4.validate(data2, schema)).to.be.false;
+5
View File
@@ -5,6 +5,7 @@
// <reference types="node"/>
// <reference types="chai" />
import tv4 = require('tv4');
declare global {
namespace Chai {
@@ -16,6 +17,10 @@ declare global {
export interface LanguageChains {
jsonSchema(schema: any, msg?: string): void;
}
export interface ChaiStatic {
tv4: tv4.TV4;
}
}
}
+1
View File
@@ -358,6 +358,7 @@ declare namespace Chai {
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
includeDeepMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
+3 -2
View File
@@ -71,7 +71,7 @@ declare namespace Chart {
}
export interface ChartPoint {
x?: number;
x?: number | string | Date;
y?: number;
}
@@ -103,6 +103,7 @@ declare namespace Chart {
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
scales?: ChartScales;
cutoutPercentage?: number;
}
export interface ChartFontOptions {
@@ -430,4 +431,4 @@ declare namespace Chart {
}
export = Chart;
export as namespace Chart;
export as namespace Chart;
+7 -6
View File
@@ -1,6 +1,6 @@
// Type definitions for Chrome extension development
// Project: http://developer.chrome.com/extensions/
// Definitions by: Matthew Kimber <https://github.com/matthewkimber>, otiai10 <https://github.com/otiai10>, couven92 <https://github.com/couven92>, RReverser <https://github.com/rreverser>
// Definitions by: Matthew Kimber <https://github.com/matthewkimber>, otiai10 <https://github.com/otiai10>, couven92 <https://github.com/couven92>, RReverser <https://github.com/rreverser>, sreimer15 <https://github.com/sreimer15>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="filesystem" />
@@ -7062,13 +7062,12 @@ declare namespace chrome.webNavigation {
transitionQualifiers: string[];
}
interface WebNavigationEventFilter {
/** Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event. */
url: chrome.events.UrlFilter[];
interface WebNavigationRequestFilter extends chrome.webRequest.RequestFilter {
/** fulfills the webRequest.RequestFilter interface even though it is under web navigation **/
}
interface WebNavigationEvent<T extends WebNavigationCallbackDetails> extends chrome.events.Event<(details: T) => void> {
addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void;
addListener(callback: (details: T) => void, filters?: WebNavigationRequestFilter): void;
}
interface WebNavigationFramedEvent extends WebNavigationEvent<WebNavigationFramedCallbackDetails> {}
@@ -7178,7 +7177,8 @@ declare namespace chrome.webRequest {
*/
types?: string[];
/** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */
urls: string[];
urls: string[] | RegExp[] | "<all_urls>";
/** Optional. */
windowId?: number;
}
@@ -7267,6 +7267,7 @@ declare namespace chrome.webRequest {
interface WebResponseHeadersDetails extends WebResponseDetails {
/** Optional. The HTTP response headers that have been received with this response. */
responseHeaders?: HttpHeader[];
method: string; /** standard HTTP method i.e. GET, POST, PUT, etc. */
}
interface WebResponseCacheDetails extends WebResponseHeadersDetails {
+23
View File
@@ -171,6 +171,29 @@ function catBlock () {
["blocking"]);
}
// webNavigation.onBeforeNavigate.addListener example similar api to onBeforeRequest but without extra spec
function beforeRedditNavigation() {
chrome.webNavigation.onBeforeNavigate.addListener(function (requestDetails) {
console.log("URL we want to redirect to: " + requestDetails.url);
// NOTE: This will search for top level frames with the value -1.
if (requestDetails.parentFrameId != -1) {
return;
}
let url = new URL(requestDetails.url);
let splitUrl = url.hostname.split('.');
//` Note: Does not cover the XX.co.uk type edge case
let host = (splitUrl[(splitUrl.length -1) - 1]);
if (host === null) {
return;
} else if (host === "reddit") {
alert("Were you trying to go on reddit, during working hours? :(")
return;
}
},{urls: ["http://*/*"], types: ["image"]});
}
// contrived settings example
function proxySettings() {
chrome.proxy.settings.get({ incognito: true }, (details) => {
+11 -2
View File
@@ -16,7 +16,7 @@ declare module "codemirror" {
and return a {list, from, to} object, where list is an array of strings or objects (the completions), and
from and to give the start and end of the token that is being completed as {line, ch} objects. An optional
selectedHint property (an integer) can be added to the completion object to control the initially selected hint. */
function showHint(cm: CodeMirror.Doc, hinter?: (doc: CodeMirror.Doc) => Hints, options?: ShowHintOptions): void;
function showHint(cm: CodeMirror.Doc, hinter?: HintFunction, options?: ShowHintOptions): void;
interface Hints {
from: Position;
@@ -47,9 +47,18 @@ declare module "codemirror" {
showHint: (options: ShowHintOptions) => void;
}
interface HintFunction {
(doc: CodeMirror.Doc): Hints;
}
interface AsyncHintFunction {
(doc: CodeMirror.Doc, callback: (hints: Hints) => any): any;
async?: boolean;
}
interface ShowHintOptions {
completeSingle: boolean;
hint: (doc: CodeMirror.Doc) => Hints;
hint: HintFunction | AsyncHintFunction;
}
/** The Handle used to interact with the autocomplete dialog box.*/
+7 -3
View File
@@ -118,6 +118,8 @@ declare namespace CodeMirror {
The other arguments and the returned value have the same interpretation as they have in findPosH. */
findPosV(start: CodeMirror.Position, amount: number, unit: string): { line: number; ch: number; hitSide?: boolean; };
/** Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position. */
findWordAt(pos: CodeMirror.Position): CodeMirror.Range;
/** Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option. */
setOption(option: string, value: any): void;
@@ -672,9 +674,11 @@ declare namespace CodeMirror {
(line: number, ch?: number): Position;
}
interface Range{
from: CodeMirror.Position;
to: CodeMirror.Position;
interface Range {
anchor: CodeMirror.Position;
head: CodeMirror.Position;
from(): CodeMirror.Position;
to(): CodeMirror.Position;
}
interface Position {
+6
View File
@@ -7,6 +7,12 @@ var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, {
mode: "javascript"
});
var range = myCodeMirror2.findWordAt(CodeMirror.Pos(0, 2));
var anchor = range.anchor;
var head = range.head;
var from = range.from();
var to = range.to();
var myTextArea: HTMLTextAreaElement;
var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
+14
View File
@@ -31,3 +31,17 @@ CodeMirror.showHint(doc, function (cm) {
to: pos
};
});
var asyncHintFunc : CodeMirror.AsyncHintFunction =
(doc: CodeMirror.Doc, callback: (hints: CodeMirror.Hints) => any) => {
callback({
from: pos,
list: ["one", "two"],
to: pos
});
};
asyncHintFunc.async = true;
doc.showHint({
completeSingle: false,
hint: asyncHintFunc
})
+16
View File
@@ -0,0 +1,16 @@
import * as commentJson from 'comment-json';
const result = commentJson.parse(`
/**
block comment at the top
*/
// comment at the top
{
// comment for a
// comment line 2 for a
/* block comment */
"a": 1 // comment at right
}
// comment at the bottom
`);
const str = commentJson.stringify(result);
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for comment-json 1.1
// Project: https://github.com/kaelzhang/node-comment-json
// Definitions by: Jason Dent <https://github.com/Jason3S>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type Reviver = (k: number | string, v: any) => any;
export function parse(json: string, reviver?: Reviver, removes_comments?: boolean): any;
export function stringify(value: any, replacer?: any, space?: string | number): string;
+22
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",
"comment-json-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+5
View File
@@ -29,3 +29,8 @@ var hidden1: any = config.util.makeHidden({}, "");
var hidden2: any = config.util.makeHidden({}, "", "");
var env: string = config.util.getEnv("");
var configSources: config.IConfigSource[] = config.util.getConfigSources();
var configSource: config.IConfigSource = configSources[0];
var configSourceName: string = configSource.name;
var configSourceOriginal: string | undefined = configSource.original;
+9
View File
@@ -34,6 +34,9 @@ declare namespace c {
// Return the config for the project based on directory param if not directory then return default one (config).
loadFileConfigs(configDir: string): any;
// Return the sources for the configurations
getConfigSources(): IConfigSource[];
}
interface IConfig {
@@ -41,6 +44,12 @@ declare namespace c {
has(setting: string): boolean;
util: IUtil;
}
interface IConfigSource {
name: string;
original?: string;
parsed: any;
}
}
export = c;
+5 -1
View File
@@ -951,10 +951,14 @@ declare namespace Consul {
}
namespace Watch {
interface WatchOptions {
key?: string;
}
interface Options {
method: Function;
options?: CommonOptions;
options?: CommonOptions & WatchOptions;
}
}
@@ -0,0 +1,7 @@
import * as cookie from "cookie-signature";
let val = cookie.sign('hello', 'tobiiscool');
val = cookie.sign('hello', 'tobiiscool');
cookie.unsign(val, 'tobiiscool');
cookie.unsign(val, 'luna');
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for cookie-signature 1.0
// Project: https://github.com/tj/node-cookie-signature
// Definitions by: François Nguyen <https://github.com/lith-light-g>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Sign the given `val` with `secret`.
* @param {string} val
* @param {string} secret
* @return {string}
*/
export function sign(value: string, secret: string): string;
/**
* Unsign and decode the given `val` with `secret`,
* returning `false` if the signature is invalid.
* @param {string} val
* @param {string} secret
* @return {string|boolean}
*/
export function unsign(value: string, secret: string): string | boolean;
+22
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",
"cookie-signature-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+21 -21
View File
@@ -1,23 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova-plugin-app-version-tests.ts"
]
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova-plugin-app-version-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
# Installation
> `npm install --save @types/cordova-plugin-device-name`
# Summary
This package contains type definitions for cordova-plugin-device-name (https://www.npmjs.com/package/cordova-plugin-device-name)
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cordova-plugin-device-name
@@ -0,0 +1,4 @@
/// <reference types="cordova" />
var deviceName = cordova.plugins.deviceName;
console.log(deviceName.name) // e.g: Becvert's iPad
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for cordova-plugin-device-name v1.1.0
// Project: https://www.npmjs.com/package/cordova-plugin-device-name
// Definitions by: Larry Bahr <https://github.com/larrybahr>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Licensed under the MIT license.
interface CordovaPlugins {
/**
* cordova-plugin-device-name interface
*/
deviceName: CordovaPluginDeviceName.CordovaPluginDeviceName;
}
/**
* Keep the type global namespace clean by using a module
*/
declare module CordovaPluginDeviceName {
interface CordovaPluginDeviceName {
/**
* User-friendly name of the device.
* @example cordova.plugins.deviceName.name // e.g: Larry's Android
*/
name: string;
}
}
@@ -18,6 +18,6 @@
},
"files": [
"index.d.ts",
"axios-tests.ts"
"cordova-plugin-device-name-tests.ts"
]
}
@@ -529,4 +529,56 @@ cordova.plugins.diagnostic.requestAndCheckMotionAuthorization(function(status){
console.log("Motion authorization is " +status);
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isExternalStorageAuthorized(function(authorized){
console.log("Location authorization is " + (authorized ? "authorized" : "unauthorized"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.getExternalStorageAuthorizationStatus(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("External storage authorization allowed");
}
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.requestExternalStorageAuthorization(function(status){
if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){
console.log("External storage authorization allowed");
}
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.getExternalSdCardDetails(function(details){
console.log("External SD card details: " + JSON.stringify(details));
}, function(error){
console.error(error);
});
cordova.plugins.diagnostic.isNFCPresent(function(present){
console.log("NFC hardware is " + (present ? "present" : "absent"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isNFCEnabled(function(enabled){
console.log("NFC is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.isNFCAvailable(function(available){
console.log("NFC is " + (available ? "available" : "not available"));
}, function(error){
console.error("The following error occurred: "+error);
});
cordova.plugins.diagnostic.registerNFCStateChangeHandler(function(state){
if(state === cordova.plugins.diagnostic.NFCState.POWERED_ON){
console.log("NFC is ready to use");
}
});
+98 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for cordova.plugins.diagnostic v3.3.0
// Type definitions for cordova.plugins.diagnostic v3.4.x
// Project: https://github.com/dpa99c/cordova-diagnostic-plugin
// Definitions by: Dave Alden <https://github.com/dpa99c/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -56,6 +56,14 @@ interface Diagnostic {
bluetoothState?: any;
/**
* ANDROID ONLY
* Constants for the various NFC power states.
* @type {Object}
*/
NFCState?: any;
/**
* Checks if app is able to access device location.
* @param successCallback
@@ -164,8 +172,8 @@ interface Diagnostic {
/**
* ANDROID and iOS ONLY
* Returns true if the device setting for location is on.
* On Android this returns true if Location Mode is switched on.
* Returns true if the device setting for location is on.
* On Android this returns true if Location Mode is switched on.
* On iOS this returns true if Location Services is switched on.
* @param successCallback
* @param errorCallback
@@ -567,6 +575,93 @@ interface Diagnostic {
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the application is authorized to use external storage.
* @param successCallback
* @param errorCallback
*/
isExternalStorageAuthorized?: (
successCallback: (authorized: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Returns the authorisation status for runtime permission to use the external storage.
* @param successCallback
* @param errorCallback
*/
getExternalStorageAuthorizationStatus?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Requests authorisation for runtime permission to use the external storage.
* @param successCallback
* @param errorCallback
*/
requestExternalStorageAuthorization?: (
successCallback: (status: string) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Returns details of external SD card(s): absolute path, is writable, free space
* @param successCallback
* @param errorCallback
*/
getExternalSdCardDetails?: (
successCallback: (status: any) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if NFC hardware is present on device.
* @param successCallback
* @param errorCallback
*/
isNFCPresent?: (
successCallback: (present: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if the device setting for NFC is switched on.
* @param successCallback
* @param errorCallback
*/
isNFCEnabled?: (
successCallback: (present: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Checks if NFC is available to the app.
* @param successCallback
* @param errorCallback
*/
isNFCAvailable?: (
successCallback: (present: boolean) => void,
errorCallback: (error: string) => void
) => void;
/**
* ANDROID ONLY
* Registers a function to be called when a change in NFC state occurs.
* Pass in a falsey value to de-register the currently registered function.
* @param successCallback
*/
registerNFCStateChangeHandler?: (
successCallback: (state: string) => void
) => void;
/**
* iOS ONLY
* Checks if the application is authorized to use the Camera Roll in Photos app.
+8
View File
@@ -0,0 +1,8 @@
# Installation
> `npm install --save-dev @types/cordova_app_version_plugin`
# Summary
This package contains type definitions for cordova_app_version_plugin (https://www.npmjs.com/package/cordova_app_version_plugin)
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cordova_app_version_plugin
@@ -0,0 +1,3 @@
/// <reference types="cordova" />
var appVersion = window.cordova.plugins.version.getAppVersion(); // e.g. "1.5.0"
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for cordova_app_version_plugin v0.2.6
// Project: https://www.npmjs.com/package/cordova_app_version_plugin
// Definitions by: Larry Bahr <https://github.com/larrybahr>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Licensed under the MIT license.
interface CordovaPlugins {
/**
* cordova_app_version_plugin interface
*/
version: CordovaAppVersionPlugin.CordovaAppVersionPlugin;
}
/**
* Keep the type global namespace clean by using a module
*/
declare module CordovaAppVersionPlugin {
interface CordovaAppVersionPlugin {
/**
* App version from config.xml's version (e.g. <widget id="my.app.id" version="1.5.0">)
* @example window.cordova.plugins.version.getAppVersion() // e.g: "1.5.0"
*/
getAppVersion(): string;
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"cordova_app_version_plugin-tests.ts"
]
}
+2 -1
View File
@@ -10,7 +10,8 @@ declare namespace creditCardType {
interface CreditCardTypeInfo {
niceType?: string
type?: CardBrand
pattern?: RegExp
prefixPattern?: RegExp
exactPattern?: RegExp
gaps?: Array<number>
lengths?: Array<number>
code?: {
+3 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for cron 1.0.9
// Type definitions for cron 1.2
// Project: https://www.npmjs.com/package/cron
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -6,9 +6,9 @@
interface CronJobStatic {
new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob;
new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean): CronJob;
new (options: {
cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any
cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any; runOnInit?: boolean
}): CronJob;
}
interface CronJob {
+3
View File
@@ -0,0 +1,3 @@
import { AES } from '../index';
export = AES;
+3
View File
@@ -0,0 +1,3 @@
import * as Core from '../index';
export = Core;
+4
View File
@@ -0,0 +1,4 @@
import { enc } from '../index';
declare const Base64: typeof enc.Base64;
export = Base64;
+4
View File
@@ -0,0 +1,4 @@
import { enc } from '../index';
declare const Hex: typeof enc.Hex;
export = Hex;
+4
View File
@@ -0,0 +1,4 @@
import { enc } from '../index';
declare const Latin1: typeof enc.Latin1;
export = Latin1;
+4
View File
@@ -0,0 +1,4 @@
import { enc } from '../index';
declare const Utf16: typeof enc.Utf16;
export = Utf16;
+4
View File
@@ -0,0 +1,4 @@
import { enc } from '../index';
declare const Utf8: typeof enc.Utf8;
export = Utf8;
+3
View File
@@ -0,0 +1,3 @@
import { EvpKDF } from '../index';
export = EvpKDF;

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