Merge remote-tracking branch 'refs/remotes/DefinitelyTyped/master'

This commit is contained in:
Jeongho Nam
2017-02-11 12:23:11 +09:00
3141 changed files with 31715 additions and 4014 deletions
+1
View File
@@ -38,5 +38,6 @@ node_modules
.sublimets
.settings/launch.json
.vs
.vscode
yarn.lock
+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.
+253
View File
@@ -0,0 +1,253 @@
import * as Ably from 'ably';
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;
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ably-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1
View File
@@ -106,6 +106,7 @@ declare module 'angular' {
onComplete?: Function;
onRemoving?: Function;
skipHide?: boolean;
multiple?: boolean;
fullscreen?: boolean; // default: false
}
@@ -155,6 +155,7 @@ testApp.config((
placement: 'bottom',
animation: false,
popupDelay: 1000,
popupCloseDelay: 1000,
appendToBody: true,
trigger: 'mouseenter hover',
useContentExp: true,
+9 -2
View File
@@ -161,7 +161,7 @@ declare module 'angular' {
/**
* Defines the initial date, when no model value is specified.
*
*
* @default null
*/
initDate?: any;
@@ -834,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?
*
+10
View File
@@ -1254,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.
+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;
-125
View File
@@ -1,125 +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;
}
function makePromise(val: any) {
return <Axios.IPromise<any>>{
then: () => val,
catch: () => val
};
}
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);
const requestId2: number = axios.interceptors.request.use<any>(
(config) => {
console.log("Method:" + config.method + " Url:" +config.url);
return makePromise(config);
},
(error: any) => error);
axios.interceptors.response.use<any>(config => {
console.log("Status:" + config.status);
return config;
});
axios.interceptors.response.use<any>(config => {
console.log("Status:" + config.status);
return makePromise(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";
-328
View File
@@ -1,328 +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;
use<U>(fulfilledFn: (config: AxiosXHRConfig<U>) => IPromise<AxiosXHRConfig<U>>): InterceptorId;
use<U>(fulfilledFn: (config: AxiosXHRConfig<U>) => IPromise<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>) => IPromise<Axios.AxiosXHR<T>>): InterceptorId;
use<T>(fulfilledFn: (config: Axios.AxiosXHR<T>) => Axios.AxiosXHR<T>,
rejectedFn: (error: any) => any)
: InterceptorId;
use<T>(fulfilledFn: (config: Axios.AxiosXHR<T>) => IPromise<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>[];
+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> {
+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;
}
+2 -2
View File
@@ -71,7 +71,7 @@ declare namespace Chart {
}
export interface ChartPoint {
x?: number;
x?: number | string | Date;
y?: number;
}
@@ -430,4 +430,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
})
+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 -2
View File
@@ -578,7 +578,7 @@ declare class Dockerode {
getTask(id: string): Dockerode.Task;
getNode(id: string): Node;
getNode(id: string): Dockerode.Node;
getNetwork(id: string): Dockerode.Network;
@@ -640,4 +640,4 @@ declare class Dockerode {
modem: any;
}
export = Dockerode;
export = Dockerode;
+1 -1
View File
@@ -458,7 +458,7 @@ declare namespace Draft {
entityMap: { [key: string]: RawDraftEntity };
}
function convertFromHTMLtoContentBlocks(html: string, DOMBuilder: Function, blockRenderMap?: DraftBlockRenderMap): Array<ContentBlock>;
function convertFromHTMLtoContentBlocks(html: string, DOMBuilder?: Function, blockRenderMap?: DraftBlockRenderMap): Array<ContentBlock>;
function convertFromRawToDraftState(rawState: RawDraftContentState): ContentState;
function convertFromDraftStateToRaw(contentState: ContentState): RawDraftContentState;
}
+16 -5
View File
@@ -3,10 +3,21 @@
// Definitions by: Zsolt Kovacs <https://github.com/zskovacs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class Dragster {
constructor(elem: HTMLElement);
removeListeners(): void;
reset(): void;
declare namespace Dragster {
interface Dragster {
removeListeners(): void;
reset(): void;
}
interface DragsterStatic {
(elem: HTMLElement): Dragster;
new (elem: HTMLElement): Dragster;
}
}
export = Dragster;
// Support through imports.
declare var Dragster: Dragster.DragsterStatic;
export = Dragster;
// Support as a global
export as namespace Dragster;
+91
View File
@@ -0,0 +1,91 @@
/// <reference path="index.d.ts"/>
//constructor
var constructorNoOptions = new Dropkick('#my-select');
var constructorNoOptions2 = new Dropkick(new HTMLSelectElement());
var constructorOptions = new Dropkick('#my-select', {});
var constructorOptions2 = new Dropkick(new HTMLSelectElement(), {});
//options
var options : DropkickOptions = {
disabled: true,
form: new HTMLFormElement(),
length: 1,
mobile: true,
multiple: true,
options: ['test'],
selectedIndex: 0,
selectedOptions: ['test'],
value: 'test',
change() { },
close() { },
open() { },
initialize: () => { }
}
var withFullOptions = new Dropkick('#test', options);
var dk = new Dropkick('#test');
//fields (same as options)
var o1 = dk.disabled;
var o2 = dk.form;
var o3 = dk.length;
var o4 = dk.mobile;
var o5 = dk.multiple;
var o6 = dk.options;
var o7 = dk.selectedIndex;
var o8 = dk.selectedOptions;
var o9 = dk.value;
//methods
dk.add('new');
dk.add(new HTMLSelectElement());
dk.add('new', 'old');
dk.add('new', 1);
dk.disable();
dk.disable(false);
dk.disable(4, true);
dk.disable(4);
dk.dispose();
dk.focus();
dk.hide(4);
dk.hide(4, false);
var node = dk.item(4);
dk.open();
dk.refresh();
dk.remove(4);
dk.reset();
dk.reset(true);
var words = dk.search("qwer", "fuzzy");
var node2 = dk.select(4);
var node3 = dk.select("AL");
var node4 = dk.select(4, true);
var node5 = dk.selectOne(4);
var node6 = dk.selectOne(4, true);
//real life example
var fieldValue = '';
var selectOptions : DropkickOptions = {
open(this: Dropkick) {
const optionsList = (<any>this).data.elem.lastChild; //undocumented but useful data field
if (optionsList.scrollWidth > optionsList.offsetWidth) {
optionsList.style.width = optionsList.scrollWidth + 25 + 'px';
}
},
change: () => {
fieldValue = select.value;
}
};
var select = new Dropkick('#select', options);
+51
View File
@@ -0,0 +1,51 @@
// Type definitions for dropkickjs 2.1
// Project: http://dropkickjs.com/
// Definitions by: Dmitry Pesterev <https://github.com/VorobeY1326/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface DropkickOptions {
disabled?: boolean;
form?: Node;
length?: number;
mobile?: boolean;
multiple?: boolean;
options?: string[];
selectedIndex?: number;
selectedOptions?: string[];
value?: string;
change?: () => void;
close?: () => void;
initialize?: () => void;
open?: () => void;
}
declare class Dropkick {
constructor(id: string|HTMLElement, options?: DropkickOptions);
add(value: string | Node, before?: number | string): void;
close(): void;
disable(disabled?: boolean): void;
disable(index: number, disabled?: boolean): void;
dispose(): void;
focus(): void;
hide(index: number, hidden?: boolean): void;
item(index: number): Node;
open(): void;
refresh(): void;
remove(index: number): void;
reset(clear?: boolean): void;
search(string: string, mode?: string): string[];
select(element: number|string, selectDisabled?: boolean): Node;
selectOne(element: number, selectDisabled?: boolean): Node;
disabled: boolean;
form: Node;
length: number;
mobile: boolean;
multiple: boolean;
options: string[];
selectedIndex: number;
selectedOptions: string[];
value: string;
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"dropkickjs-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1 -1
View File
@@ -2779,7 +2779,7 @@ declare namespace Electron {
* The protocol scheme in the form ‘scheme:’. Currently supported values are ‘http:’ or ‘https:’.
* Defaults to ‘http:’.
*/
Protocol?: 'http:' | 'https:';
protocol?: 'http:' | 'https:';
/**
* The server host provided as a concatenation of the hostname and the port number ‘hostname:port’.
*/
+35
View File
@@ -0,0 +1,35 @@
import * as envToObject from 'env-to-object';
const map = {
'NODE_ENV': {
'keypath': 'env',
'type': 'string'
},
'PORT': {
'keypath': 'server.port',
'type': 'number'
},
'SSL': {
'keypath': 'server.ssl',
'type': 'boolean'
},
'LOG_LEVEL': {
'keypath': 'logger.level',
'type': 'string'
},
'INT': {
'keypath': 'int',
'type': 'integer',
'radix': '2'
}
};
const result1:any = envToObject(map);
const result2:any = envToObject(map, {
parsers: {
'my-custom-type': (str: string, opts: any) => {
let foo: any = JSON.parse(str);
return foo;
}
}
});
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for env-to-object 1.1
// Project: https://github.com/kgryte/node-env-to-object#readme
// Definitions by: TANAKA Koichi <https://github.com/MugeSo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace env {
export interface Mappings {
[enviromentVariableName: string]: Mapping;
}
export type Mapping = IntegerMapping | BooleanMapping | GenericMapping;
interface GenericMapping {
keypath: string;
type?: string;
[opt: string]: any;
}
interface IntegerMapping extends GenericMapping {
type: "integer";
radix: number;
}
interface BooleanMapping {
type: "boolean";
strict: boolean;
}
export interface Parsers {
[parserName: string]: (str: string, opts: any) => any;
}
export interface Options {
parsers: Parsers;
}
}
declare function env(map: env.Mappings, options?: env.Options): any;
export = env;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"env-to-object-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+116 -319
View File
@@ -1,48 +1,44 @@
import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme";
import * as React from "react";
import {Component, ReactElement, HTMLAttributes} from "react";
import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme";
import {shallow, mount, render, ShallowWrapper, ReactWrapper} from "enzyme";
import {Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent} from "react";
// Help classes/interfaces
interface MyComponentProps {
propsProperty: any;
stringProp: string;
numberProp?: number;
}
interface StatelessProps {
stateless: any;
stateless: string;
}
interface MyComponentState {
stateProperty: any;
stateProperty: string;
}
class MyComponent extends Component<MyComponentProps, MyComponentState> {
setState(...args: any[]) {
console.log(args);
}
}
const MyStatelessComponent = (props: StatelessProps) => <span />;
// API
namespace SpyLifecycleTest {
spyLifecycle(MyComponent);
}
// ShallowWrapper
namespace ShallowWrapperTest {
var shallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState> =
shallow<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
shallow<MyComponentProps, MyComponentState>(<MyComponent stringProp="value"/>);
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
objectVal: {},
boolVal: boolean,
stringVal: string,
numOrStringVal: number | string,
elementWrapper: ShallowWrapper<HTMLAttributes<{}>, {}>
elementWrapper: ShallowWrapper<HTMLAttributes<{}>, {}>,
statelessWrapper: ShallowWrapper<StatelessProps, never>;
function test_shallow_options() {
shallow(<MyComponent propsProperty={1}/>, {
shallow(<MyComponent stringProp="1"/>, {
context: {
test: "a",
},
@@ -51,11 +47,10 @@ namespace ShallowWrapperTest {
}
function test_find() {
elementWrapper = shallowWrapper.find('.selector');
shallowWrapper = shallowWrapper.find(MyComponent);
shallowWrapper.find(MyStatelessComponent).props().stateless;
shallowWrapper.find(MyStatelessComponent).shallow();
shallowWrapper.find({ prop: 'value' });
statelessWrapper = shallowWrapper.find(MyStatelessComponent);
shallowWrapper = shallowWrapper.find({ prop: 'value' });
elementWrapper = shallowWrapper.find('.selector');
}
function test_findWhere() {
@@ -64,15 +59,16 @@ namespace ShallowWrapperTest {
}
function test_filter() {
shallowWrapper = shallowWrapper.filter(MyComponent);
statelessWrapper = statelessWrapper.filter(MyStatelessComponent);
shallowWrapper = shallowWrapper.filter({ numberProp: 12 });
elementWrapper = shallowWrapper.filter('.selector');
shallowWrapper = shallowWrapper.filter(MyComponent).shallow();
shallowWrapper.filter({ prop: 'val' });
}
function test_filterWhere() {
shallowWrapper =
shallowWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
wrapper.props().stringProp;
return true;
});
}
@@ -95,11 +91,11 @@ namespace ShallowWrapperTest {
function test_dive() {
interface TmpProps {
foo: any
foo: any;
}
interface TmpState {
bar: any
bar: any;
}
const diveWrapper: ShallowWrapper<TmpProps, TmpState> = shallowWrapper.dive<TmpProps, TmpState>({ context: { foobar: 'barfoo' }});
@@ -122,11 +118,11 @@ namespace ShallowWrapperTest {
}
function test_isEmpty() {
boolVal = shallowWrapper.isEmpty()
boolVal = shallowWrapper.isEmpty();
}
function test_exists() {
boolVal = shallowWrapper.exists()
boolVal = shallowWrapper.exists();
}
function test_not() {
@@ -135,19 +131,21 @@ namespace ShallowWrapperTest {
function test_children() {
shallowWrapper = shallowWrapper.children();
shallowWrapper.children(MyStatelessComponent).props().stateless;
shallowWrapper.children({ prop: 'myprop' });
shallowWrapper = shallowWrapper.children(MyComponent);
statelessWrapper = shallowWrapper.children(MyStatelessComponent);
shallowWrapper = shallowWrapper.children({ prop: 'value' });
elementWrapper = shallowWrapper.children('.selector');
}
function test_childAt() {
const childWrapper: ShallowWrapper<any, any> = shallowWrapper.childAt(0);
interface TmpType1 {
foo: any
foo: any;
}
interface TmpType2 {
bar: any
bar: any;
}
const childWrapper2: ShallowWrapper<TmpType1, TmpType2> = shallowWrapper.childAt<TmpType1, TmpType2>(0);
@@ -155,6 +153,10 @@ namespace ShallowWrapperTest {
function test_parents() {
shallowWrapper = shallowWrapper.parents();
shallowWrapper = shallowWrapper.parents(MyComponent);
statelessWrapper = shallowWrapper.parents(MyStatelessComponent);
shallowWrapper = shallowWrapper.parents({ prop: 'myprop' });
elementWrapper = shallowWrapper.parents('.selector');
}
function test_parent() {
@@ -162,9 +164,10 @@ namespace ShallowWrapperTest {
}
function test_closest() {
elementWrapper = shallowWrapper.closest('.selector');
shallowWrapper = shallowWrapper.closest(MyComponent);
statelessWrapper = shallowWrapper.closest(MyStatelessComponent);
shallowWrapper = shallowWrapper.closest({ prop: 'myprop' });
elementWrapper = shallowWrapper.closest('.selector');
}
function test_shallow() {
@@ -175,15 +178,10 @@ namespace ShallowWrapperTest {
shallowWrapper = shallowWrapper.unmount();
}
function test_render() {
var cheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState> = shallowWrapper.render();
}
function test_text() {
stringVal = shallowWrapper.text();
}
function test_html() {
stringVal = shallowWrapper.html();
}
@@ -206,23 +204,28 @@ namespace ShallowWrapperTest {
function test_state() {
const state: MyComponentState = shallowWrapper.state();
shallowWrapper.state('key');
const tmp: String = shallowWrapper.state<String>('key');
const prop: string = shallowWrapper.state('stateProperty');
const prop2: number = shallowWrapper.state<number>('key');
const prop3 = shallowWrapper.state('key');
}
function test_context() {
shallowWrapper.context();
shallowWrapper.context('key');
const tmp: String = shallowWrapper.context<String>('key');
const tmp: string = shallowWrapper.context<string>('key');
}
function test_props() {
objectVal = shallowWrapper.props();
const props: MyComponentProps = shallowWrapper.props();
const props2: MyComponentProps = shallowWrapper.find(MyComponent).props();
const props3: StatelessProps = shallowWrapper.find(MyStatelessComponent).props();
const props4: HTMLAttributes<any> = shallowWrapper.find('.selector').props();
}
function test_prop() {
shallowWrapper.prop('key');
const tmp: String = shallowWrapper.prop<String>('key');
const tmp: number = shallowWrapper.prop('numberProp');
const tmp2: string = shallowWrapper.prop<string>('key');
const tmp3 = shallowWrapper.prop('key');
}
function test_key() {
@@ -239,7 +242,7 @@ namespace ShallowWrapperTest {
}
function test_setProps() {
shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }, () => console.log('props updated'));
shallowWrapper = shallowWrapper.setProps({ stringProp: 'foo' });
}
function test_setContext() {
@@ -259,20 +262,20 @@ namespace ShallowWrapperTest {
}
function test_type() {
var stringOrFunction: String | Function = shallowWrapper.type();
const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = shallowWrapper.type();
}
function test_name() {
var str: String = shallowWrapper.name();
stringVal = shallowWrapper.name();
}
function test_forEach() {
shallowWrapper =
shallowWrapper.forEach(wrapper => wrapper.shallow().props().propsProperty);
shallowWrapper.forEach(wrapper => wrapper.shallow().props().stringProp);
}
function test_map() {
var arrayNumbers: Array<Number> =
var arrayNumbers: number[] =
shallowWrapper.map(wrapper => wrapper.props().numberProp);
}
@@ -286,13 +289,15 @@ namespace ShallowWrapperTest {
function test_reduceRight() {
const total: number =
shallowWrapper.reduceRight<number>(
(amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
(amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
);
}
function test_some() {
boolVal = shallowWrapper.some('.selector');
boolVal = shallowWrapper.some(MyComponent);
boolVal = shallowWrapper.some(MyStatelessComponent);
boolVal = shallowWrapper.some({ prop: 'myprop' });
boolVal = shallowWrapper.some('.selector');
}
function test_someWhere() {
@@ -300,8 +305,10 @@ namespace ShallowWrapperTest {
}
function test_every() {
boolVal = shallowWrapper.every('.selector');
boolVal = shallowWrapper.every(MyComponent);
boolVal = shallowWrapper.every(MyStatelessComponent);
boolVal = shallowWrapper.every({ prop: 'myprop' });
boolVal = shallowWrapper.every('.selector');
}
function test_everyWhere() {
@@ -321,13 +328,14 @@ namespace ShallowWrapperTest {
// ReactWrapper
namespace ReactWrapperTest {
var reactWrapper: ReactWrapper<MyComponentProps, MyComponentState> =
mount<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
mount<MyComponentProps, MyComponentState>(<MyComponent stringProp="value"/>);
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ReactWrapper<HTMLAttributes<{}>, {}>
objectVal: {},
boolVal: boolean,
stringVal: string,
elementWrapper: ReactWrapper<HTMLAttributes<{}>, {}>,
statelessWrapper: ReactWrapper<StatelessProps, never>;
function test_unmount() {
reactWrapper = reactWrapper.unmount();
@@ -336,7 +344,7 @@ namespace ReactWrapperTest {
function test_mount() {
reactWrapper = reactWrapper.mount();
mount(<MyComponent propsProperty={1}/>, {
mount(<MyComponent stringProp='1'/>, {
attachTo: document.getElementById('test'),
context: {
a: "b"
@@ -348,11 +356,11 @@ namespace ReactWrapperTest {
reactWrapper = reactWrapper.ref('refName');
interface TmpType1 {
foo: string
foo: string;
}
interface TmpType2 {
bar: string
bar: string;
}
const tmp: ReactWrapper<TmpType1, TmpType2> = reactWrapper.ref<TmpType1, TmpType2>('refName');
@@ -365,8 +373,8 @@ namespace ReactWrapperTest {
function test_find() {
elementWrapper = reactWrapper.find('.selector');
reactWrapper = reactWrapper.find(MyComponent);
reactWrapper.find(MyStatelessComponent).props().stateless;
reactWrapper.find({ prop: 'myprop' });
statelessWrapper = reactWrapper.find(MyStatelessComponent);
reactWrapper = reactWrapper.find({ prop: 'myprop' });
}
function test_findWhere() {
@@ -375,15 +383,16 @@ namespace ReactWrapperTest {
}
function test_filter() {
elementWrapper = reactWrapper.filter('.selector');
reactWrapper = reactWrapper.filter(MyComponent);
reactWrapper = reactWrapper.filter({ prop: 'myprop' });
statelessWrapper = statelessWrapper.filter(MyStatelessComponent);
reactWrapper = reactWrapper.filter({ numberProp: 12 });
elementWrapper = reactWrapper.filter('.selector');
}
function test_filterWhere() {
reactWrapper =
reactWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
wrapper.props().stringProp;
return true;
});
}
@@ -421,7 +430,7 @@ namespace ReactWrapperTest {
}
function test_isEmpty() {
boolVal = reactWrapper.isEmpty()
boolVal = reactWrapper.isEmpty();
}
function test_not() {
@@ -430,17 +439,21 @@ namespace ReactWrapperTest {
function test_children() {
reactWrapper = reactWrapper.children();
reactWrapper = reactWrapper.children(MyComponent);
statelessWrapper = reactWrapper.children(MyStatelessComponent);
reactWrapper = reactWrapper.children({ prop: 'myprop' });
elementWrapper = reactWrapper.children('.selector');
}
function test_childAt() {
const childWrapper: ReactWrapper<any, any> = reactWrapper.childAt(0);
interface TmpType1 {
foo: any
foo: any;
}
interface TmpType2 {
bar: any
bar: any;
}
const childWrapper2: ReactWrapper<TmpType1, TmpType2> = reactWrapper.childAt<TmpType1, TmpType2>(0);
@@ -448,6 +461,10 @@ namespace ReactWrapperTest {
function test_parents() {
reactWrapper = reactWrapper.parents();
reactWrapper = reactWrapper.parents(MyComponent);
statelessWrapper = reactWrapper.parents(MyStatelessComponent);
reactWrapper = reactWrapper.parents({ prop: 'myprop' });
elementWrapper = reactWrapper.parents('.selector');
}
function test_parent() {
@@ -455,9 +472,10 @@ namespace ReactWrapperTest {
}
function test_closest() {
elementWrapper = reactWrapper.closest('.selector');
reactWrapper = reactWrapper.closest(MyComponent);
statelessWrapper = reactWrapper.closest(MyStatelessComponent);
reactWrapper = reactWrapper.closest({ prop: 'myprop' });
elementWrapper = reactWrapper.closest('.selector');
}
function test_text() {
@@ -485,24 +503,29 @@ namespace ReactWrapperTest {
}
function test_state() {
reactWrapper.state();
reactWrapper.state('key');
const tmp: String = reactWrapper.state<String>('key');
const state: MyComponentState = reactWrapper.state();
const prop: string = reactWrapper.state('stateProperty');
const prop2: number = reactWrapper.state<number>('key');
const prop3 = reactWrapper.state('key');
}
function test_context() {
reactWrapper.context();
reactWrapper.context('key');
const tmp: String = reactWrapper.context<String>('key');
const tmp: string = reactWrapper.context<string>('key');
}
function test_props() {
objectVal = reactWrapper.props();
const props: MyComponentProps = reactWrapper.props();
const props2: MyComponentProps = reactWrapper.find(MyComponent).props();
const props3: StatelessProps = reactWrapper.find(MyStatelessComponent).props();
const props4: HTMLAttributes<any> = reactWrapper.find('.selector').props();
}
function test_prop() {
reactWrapper.prop('key');
const tmp: String = reactWrapper.prop<String>('key');
const tmp: number = reactWrapper.prop('numberProp');
const tmp2: string = reactWrapper.prop<string>('key');
const tmp3 = reactWrapper.prop('key');
}
function test_key() {
@@ -519,7 +542,7 @@ namespace ReactWrapperTest {
}
function test_setProps() {
reactWrapper = reactWrapper.setProps({ propsProperty: 'foo' });
reactWrapper = reactWrapper.setProps({ stringProp: 'foo' });
}
function test_setContext() {
@@ -539,40 +562,42 @@ namespace ReactWrapperTest {
}
function test_type() {
var stringOrFunction: String | Function = reactWrapper.type();
const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = reactWrapper.type();
}
function test_name() {
var str: String = reactWrapper.name();
stringVal = reactWrapper.name();
}
function test_forEach() {
reactWrapper =
reactWrapper.forEach(wrapper => wrapper.props().propsProperty);
reactWrapper.forEach(wrapper => wrapper.props().stringProp);
}
function test_map() {
var arrayNumbers: Array<Number> =
var arrayNumbers: number[] =
reactWrapper.map(wrapper => wrapper.props().numberProp);
}
function test_reduce() {
const total: number =
reactWrapper.reduce<number>(
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
);
}
function test_reduceRight() {
const total: number =
reactWrapper.reduceRight<number>(
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp')
);
}
function test_some() {
boolVal = reactWrapper.some('.selector');
boolVal = reactWrapper.some(MyComponent);
boolVal = reactWrapper.some(MyStatelessComponent);
boolVal = reactWrapper.some({ prop: 'myprop' });
boolVal = reactWrapper.some('.selector');
}
function test_someWhere() {
@@ -580,8 +605,10 @@ namespace ReactWrapperTest {
}
function test_every() {
boolVal = reactWrapper.every('.selector');
boolVal = reactWrapper.every(MyComponent);
boolVal = reactWrapper.every(MyStatelessComponent);
boolVal = reactWrapper.every({ prop: 'myprop' });
boolVal = reactWrapper.every('.selector');
}
function test_everyWhere() {
@@ -594,239 +621,9 @@ namespace ReactWrapperTest {
// CheerioWrapper
namespace CheerioWrapperTest {
var cheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState> =
render<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
const wrapper: Cheerio =
shallow(<div />).render() ||
mount(<div />).render();
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: CheerioWrapper<HTMLAttributes<{}>, {}>
function test_find() {
elementWrapper = cheerioWrapper.find('.selector');
cheerioWrapper = cheerioWrapper.find(MyComponent);
cheerioWrapper.find(MyStatelessComponent).props().stateless;
cheerioWrapper.find({ prop: 'myprop' });
}
function test_findWhere() {
cheerioWrapper =
cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_filter() {
elementWrapper = cheerioWrapper.filter('.selector');
cheerioWrapper = cheerioWrapper.filter(MyComponent);
cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' });
}
function test_filterWhere() {
cheerioWrapper =
cheerioWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
return true;
});
}
function test_contains() {
boolVal = cheerioWrapper.contains(<div className="foo bar"/>);
}
function test_containsMatchingElement() {
boolVal = cheerioWrapper.contains(<div className="foo bar"/>);
}
function test_containsAllMatchingElements() {
boolVal = cheerioWrapper.containsAllMatchingElements([<div className="foo bar"/>]);
}
function test_containsAnyMatchingElement() {
boolVal = cheerioWrapper.containsAnyMatchingElements([<div className="foo bar"/>]);
}
function test_equals() {
boolVal = cheerioWrapper.equals(<div className="foo bar"/>);
}
function test_matchesElement() {
boolVal = cheerioWrapper.matchesElement(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = cheerioWrapper.find('.my-button').hasClass('disabled');
}
function test_is() {
boolVal = cheerioWrapper.is('.some-class');
}
function test_isEmpty() {
boolVal = cheerioWrapper.isEmpty()
}
function test_not() {
elementWrapper = cheerioWrapper.find('.foo').not('.bar');
}
function test_children() {
cheerioWrapper = cheerioWrapper.children();
}
function test_childAt() {
const childWrapper: CheerioWrapper<any, any> = cheerioWrapper.childAt(0);
interface TmpType1 {
foo: any
}
interface TmpType2 {
bar: any
}
const childWrapper2: CheerioWrapper<TmpType1, TmpType2> = cheerioWrapper.childAt<TmpType1, TmpType2>(0);
}
function test_parents() {
cheerioWrapper = cheerioWrapper.parents();
}
function test_parent() {
cheerioWrapper = cheerioWrapper.parent();
}
function test_closest() {
elementWrapper = cheerioWrapper.closest('.selector');
cheerioWrapper = cheerioWrapper.closest(MyComponent);
cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' });
}
function test_text() {
stringVal = cheerioWrapper.text();
}
function test_html() {
stringVal = cheerioWrapper.html();
}
function test_get() {
reactElement = cheerioWrapper.get(1);
}
function test_at() {
cheerioWrapper = cheerioWrapper.at(1);
}
function test_first() {
cheerioWrapper = cheerioWrapper.first();
}
function test_last() {
cheerioWrapper = cheerioWrapper.last();
}
function test_state() {
cheerioWrapper.state();
cheerioWrapper.state('key');
const tmp: String = cheerioWrapper.state<String>('key');
}
function test_context() {
cheerioWrapper.context();
cheerioWrapper.context('key');
const tmp: String = cheerioWrapper.context<String>('key');
}
function test_props() {
objectVal = cheerioWrapper.props();
}
function test_prop() {
cheerioWrapper.prop('key');
const tmp: String = cheerioWrapper.prop<String>('key');
}
function test_key() {
stringVal = cheerioWrapper.key();
}
function test_simulate(...args: any[]) {
cheerioWrapper.simulate('click');
cheerioWrapper.simulate('click', args);
}
function test_setState() {
cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' });
}
function test_setProps() {
cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' });
}
function test_setContext() {
cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' });
}
function test_instance() {
var myComponent: MyComponent = cheerioWrapper.instance();
}
function test_update() {
cheerioWrapper = cheerioWrapper.update();
}
function test_debug() {
stringVal = cheerioWrapper.debug();
}
function test_type() {
var stringOrFunction: String | Function = cheerioWrapper.type();
}
function test_name() {
var str: String = cheerioWrapper.name();
}
function test_forEach() {
cheerioWrapper =
cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => {
});
}
function test_map() {
var arrayNumbers: Array<Number> =
cheerioWrapper.map(wrapper => wrapper.props().numberProp);
}
function test_reduce() {
const total: number =
cheerioWrapper.reduce<number>(
(amount: number, n: CheerioWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_reduceRight() {
const total: number =
cheerioWrapper.reduceRight<number>(
(amount: number, n: CheerioWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_some() {
boolVal = cheerioWrapper.some('.selector');
boolVal = cheerioWrapper.some(MyComponent);
}
function test_someWhere() {
boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_every() {
boolVal = cheerioWrapper.every('.selector');
boolVal = cheerioWrapper.every(MyComponent);
}
function test_everyWhere() {
boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
wrapper.toggleClass('className');
}
+74 -149
View File
@@ -1,16 +1,27 @@
// Type definitions for Enzyme v2.7.0
// Type definitions for Enzyme 2.7
// Project: https://github.com/airbnb/enzyme
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>, Ivo Stratev <https://github.com/NoHomey>, Tom Crockett <https://github.com/pelotom>
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>, Ivo Stratev <https://github.com/NoHomey>, Tom Crockett <https://github.com/pelotom>, jwbay <https://githb.com/jwbay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react";
/// <reference types="cheerio" />
import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react";
type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>;
export class ElementClass extends Component<any, any> {
}
/* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent.
* The optional static properties on them break overload ordering for wrapper methods if they're not
* all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics
*/
interface ComponentClass<Props> {
new(props?: Props, context?: any): Component<Props, any>;
}
type StatelessComponent<Props> = (props: Props, context?: any) => JSX.Element;
/**
* Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the
* following three categories:
@@ -21,34 +32,12 @@ export class ElementClass extends Component<any, any> {
* 4. A React Stateless component
* 5. A React component property map
*/
export type EnzymeSelector = string | StatelessComponent<any> | ComponentClass<any> | { [key: string]: any };
export type EnzymePropSelector = { [key: string]: any };
export interface EnzymePropSelector {
[key: string]: any;
}
export type EnzymeSelector = string | StatelessComponent<any> | ComponentClass<any> | EnzymePropSelector;
interface CommonWrapper<P, S> {
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
find<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
find(props: EnzymePropSelector): CommonWrapper<any, any>;
find(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): CommonWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
filter(props: EnzymePropSelector): CommonWrapper<any, any>;
filter(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true.
* @param predicate
@@ -71,13 +60,13 @@ interface CommonWrapper<P, S> {
* Returns whether or not all the given react elements exists in the shallow render tree
* @param nodes
*/
containsAllMatchingElements(nodes: ReactElement<any>[]): boolean;
containsAllMatchingElements(nodes: Array<ReactElement<any>>): boolean;
/**
* Returns whether or not one of the given react elements exists in the shallow render tree.
* @param nodes
*/
containsAnyMatchingElements(nodes: ReactElement<any>[]): boolean;
containsAnyMatchingElements(nodes: Array<ReactElement<any>>): boolean;
/**
* Returns whether or not the current render tree is equal to the given node, based on the expected value.
@@ -118,54 +107,6 @@ interface CommonWrapper<P, S> {
*/
not(selector: EnzymeSelector): this;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
children(props: EnzymePropSelector): CommonWrapper<any, any>;
children(selector: string): CommonWrapper<HTMLAttributes, any>;
children(): CommonWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: number): CommonWrapper<any, any>;
childAt<P2, S2>(index: number): CommonWrapper<P2, S2>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
parents(props: EnzymePropSelector): CommonWrapper<any, any>;
parents(selector: string): CommonWrapper<HTMLAttributes, any>;
parents(): CommonWrapper<any, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): CommonWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
closest(props: EnzymePropSelector): CommonWrapper<any, any>;
closest(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Returns a string of the rendered text of the current render tree. This function should be looked at with
* skepticism if being used to test what the actual HTML output of the component will be. If that is what you
@@ -209,14 +150,14 @@ interface CommonWrapper<P, S> {
* @param [key]
*/
state(): S;
state(key: string): any;
state<K extends keyof S>(key: K): S[K];
state<T>(key: string): T;
/**
* Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
*/
context(key?: string): any;
context<T>(key?: string): T;
context(): any;
context<T>(key: string): T;
/**
* Returns the props hash for the current node of the wrapper.
@@ -231,7 +172,7 @@ interface CommonWrapper<P, S> {
* NOTE: can only be called on a wrapper of a single node.
* @param key
*/
prop(key: string): any;
prop<K extends keyof P>(key: K): P[K];
prop<T>(key: string): T;
/**
@@ -260,7 +201,7 @@ interface CommonWrapper<P, S> {
* @param state
* @param [callback]
*/
setState(state: S, callback?: () => void): this;
setState<K extends keyof S>(state: Pick<S, K>, callback?: () => void): this;
/**
* A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test
@@ -274,7 +215,7 @@ interface CommonWrapper<P, S> {
* @param props
* @param [callback]
*/
setProps(props: P, callback?: () => void): this;
setProps<K extends keyof P>(props: Pick<P, K>): this;
/**
* A method that sets the context of the root component, and re-renders. Useful for when you are wanting to
@@ -284,7 +225,7 @@ interface CommonWrapper<P, S> {
* NOTE: can only be called on a wrapper instance that is also the root instance.
* @param state
*/
setContext(context: Object): this;
setContext(context: any): this;
/**
* Gets the instance of the component being rendered as the root node passed into shallow().
@@ -308,14 +249,6 @@ interface CommonWrapper<P, S> {
*/
debug(): string;
/**
* Returns the type of the current node of this wrapper. If it's a composite component, this will be the
* component constructor. If it's native DOM node, it will be a string of the tag name.
*
* Note: can only be called on a wrapper of a single node.
*/
type(): string | Function;
/**
* Returns the name of the current node of the wrapper.
*/
@@ -329,7 +262,7 @@ interface CommonWrapper<P, S> {
* @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first
* argument, and will be run with a context of the original instance.
*/
forEach(fn: (wrapper: this) => any): this;
forEach(fn: (wrapper: this, index: number) => any): this;
/**
* Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map
@@ -339,7 +272,7 @@ interface CommonWrapper<P, S> {
* to the returned array. Should expect a ShallowWrapper as the first argument, and will be run
* with a context of the original instance.
*/
map<V>(fn: (wrapper: this) => V): V[];
map<V>(fn: (wrapper: this, index: number) => V): V[];
/**
* Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node
@@ -381,12 +314,29 @@ interface CommonWrapper<P, S> {
*/
everyWhere(fn: (wrapper: this) => boolean): boolean;
/**
* Returns true if renderer returned null
*/
isEmptyRender(): boolean;
/**
* Renders the component to static markup and returns a Cheerio wrapper around the result.
*/
render(): Cheerio;
/**
* Returns the type of the current node of this wrapper. If it's a composite component, this will be the
* component constructor. If it's native DOM node, it will be a string of the tag name.
*
* Note: can only be called on a wrapper of a single node.
*/
type(): string | ComponentClass<P> | StatelessComponent<P> ;
length: number;
}
export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
shallow(): ShallowWrapper<P, S>;
render(): CheerioWrapper<P, S>;
unmount(): ShallowWrapper<any, any>;
/**
@@ -394,7 +344,7 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper<P2, {}>;
find<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
find(props: EnzymePropSelector): ShallowWrapper<any, any>;
find(selector: string): ShallowWrapper<HTMLAttributes, any>;
@@ -402,16 +352,15 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
filter(props: EnzymePropSelector): ShallowWrapper<any, any>;
filter(selector: string): ShallowWrapper<HTMLAttributes, any>;
filter<P2>(component: ComponentClass<P2> | StatelessComponent<P2>): this;
filter(props: Partial<P>): this;
filter(selector: string): this;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): ShallowWrapper<any, any>;
findWhere(predicate: (wrapper: ShallowWrapper<any, any>) => boolean): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
@@ -419,10 +368,9 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
children(props: EnzymePropSelector): ShallowWrapper<any, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
children(selector: string): ShallowWrapper<HTMLAttributes, any>;
children(): ShallowWrapper<any, any>;
children(props?: EnzymePropSelector): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
@@ -432,13 +380,13 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
childAt<P2, S2>(index: number): ShallowWrapper<P2, S2>;
/**
* Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result.
* NOTE: can only be called on wrapper of a single non-DOM component element node.
* @param [options]
*/
dive<P2, S2>(options?: ShallowRendererProps): ShallowWrapper<P2, S2>;
* Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result.
* NOTE: can only be called on wrapper of a single non-DOM component element node.
* @param [options]
*/
dive<P2, S2>(options?: ShallowRendererProps): ShallowWrapper<P2, S2>;
/**
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
@@ -446,10 +394,9 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
parents(props: EnzymePropSelector): ShallowWrapper<any, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
parents(selector: string): ShallowWrapper<HTMLAttributes, any>;
parents(): ShallowWrapper<any, any>;
parents(props?: EnzymePropSelector): ShallowWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
@@ -459,7 +406,7 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
closest(props: EnzymePropSelector): ShallowWrapper<any, any>;
closest(selector: string): ShallowWrapper<HTMLAttributes, any>;
@@ -467,17 +414,11 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ShallowWrapper<any, any>;
/**
* Returns true if renderer returned null
*/
isEmptyRender(): boolean;
}
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
render(): CheerioWrapper<P, S>;
/**
* Returns a wrapper of the node that matches the provided reference name.
@@ -503,7 +444,7 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ReactWrapper<P2, {}>;
find<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
find(props: EnzymePropSelector): ReactWrapper<any, any>;
find(selector: string): ReactWrapper<HTMLAttributes, any>;
@@ -511,16 +452,15 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): ReactWrapper<any, any>;
findWhere(predicate: (wrapper: ReactWrapper<any, any>) => boolean): ReactWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
filter(props: EnzymePropSelector): ReactWrapper<any, any>;
filter(selector: string): ReactWrapper<HTMLAttributes, any>;
filter<P2>(component: ComponentClass<P2> | StatelessComponent<P2>): this;
filter(props: Partial<P>): this;
filter(selector: string): this;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
@@ -528,10 +468,9 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
children(props: EnzymePropSelector): ReactWrapper<any, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
children(selector: string): ReactWrapper<HTMLAttributes, any>;
children(): ReactWrapper<any, any>;
children(props?: EnzymePropSelector): ReactWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
@@ -548,10 +487,9 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
parents(props: EnzymePropSelector): ReactWrapper<any, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
parents(selector: string): ReactWrapper<HTMLAttributes, any>;
parents(): ReactWrapper<any, any>;
parents(props?: EnzymePropSelector): ReactWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
@@ -561,7 +499,7 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
closest(props: EnzymePropSelector): ReactWrapper<any, any>;
closest(selector: string): ReactWrapper<HTMLAttributes, any>;
@@ -569,15 +507,6 @@ export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ReactWrapper<any, any>;
/**
* Returns true if renderer returned null
*/
isEmptyRender(): boolean;
}
export interface CheerioWrapper<P, S> extends CommonWrapper<P, S> {
}
export interface ShallowRendererProps {
@@ -626,8 +555,4 @@ export function mount<P, S>(node: ReactElement<P>, options?: MountRendererProps)
* @param node
* @param [options]
*/
export function render<P, S>(node: ReactElement<P>, options?: any): CheerioWrapper<P, S>;
export function describeWithDOM(description: string, fn: Function): void;
export function spyLifecycle(component: typeof Component): void;
export function render<P, S>(node: ReactElement<P>, options?: any): Cheerio;
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+18
View File
@@ -0,0 +1,18 @@
import WeakMap = require('es6-weak-map');
new WeakMap<{}, string>();
var tuples: [number, string][] = [ [0, 'foo'], [1, 'bar'] ];
new WeakMap<number, string>(tuples);
var map = new WeakMap<{}, string>();
var obj = {};
map.set(obj, 'foo');
map.get(obj);
map.has(obj);
map.delete(obj);
map.get(obj);
map.has(obj);
map.set(obj, 'bar');
map.has(obj);
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for es6-weak-map 1.2
// Project: https://github.com/medikoo/es6-weak-map
// Definitions by: Pine Mizune <https://github.com/pine>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = WeakMap;
export as namespace WeakMap;
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
declare class WeakMap<K, V> {
constructor();
constructor(iterable: Iterable<[K, V]>);
delete(key: K): boolean;
get(key: K): V;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"es6-weak-map-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
@@ -58,7 +58,10 @@ configuration = {
configuration = {
// ...
plugins: [
new optimize.CommonsChunkPlugin("commons", "commons.js"),
new optimize.CommonsChunkPlugin({
name: "commons",
filename: "commons.js",
}),
new ExtractTextPlugin("[name].css")
]
};
+11 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for FullCalendar 2.7.2
// Project: http://fullcalendar.io/
// Definitions by: Neil Stalker <https://github.com/nestalk>, Marcelo Camargo <https://github.com/hasellcamargo>
// Definitions by: Neil Stalker <https://github.com/nestalk>, Marcelo Camargo <https://github.com/hasellcamargo>, Patrick Niemann <https://github.com/panic175>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery"/>
@@ -363,6 +363,11 @@ declare global {
*/
fullCalendar(method: 'updateEvent', event: EventObject): void;
/**
* Reports changes for multiple events and renders them on the calendar.
*/
fullCalendar(method: 'updateEvents', events: Array<EventObject>): void;
/**
* Retrieves events that FullCalendar has in memory.
*/
@@ -402,6 +407,11 @@ declare global {
* Renders a new event on the calendar.
*/
fullCalendar(method: 'renderEvent', event: EventObject, stick?: boolean): void;
/**
* Renders new events on the calendar.
*/
fullCalendar(method: 'renderEvents', events: Array<EventObject>, stick?: boolean): void;
/**
* Rerenders all events on the calendar.
+2
View File
@@ -1,3 +1,5 @@
import * as FusionCharts from "fusioncharts";
FusionCharts.addEventListener('ready',(eventObject)=>{
eventObject.stopPropagation();
});
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var charts: (H: FusionChartStatic) => FusionChartStatic;
export = charts;
export as namespace charts;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var gantt: (H: FusionChartStatic) => FusionChartStatic;
export = gantt;
export as namespace gantt;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var maps: (H: FusionChartStatic) => FusionChartStatic;
export = maps;
export as namespace maps;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var powercharts: (H: FusionChartStatic) => FusionChartStatic;
export = powercharts;
export as namespace powercharts;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var ssgrid: (H: FusionChartStatic) => FusionChartStatic;
export = ssgrid;
export as namespace ssgrid;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var treemap: (H: FusionChartStatic) => FusionChartStatic;
export = treemap;
export as namespace treemap;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var widgets: (H: FusionChartStatic) => FusionChartStatic;
export = widgets;
export as namespace widgets;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var zoomscatter: (H: FusionChartStatic) => FusionChartStatic;
export = zoomscatter;
export as namespace zoomscatter;
+7 -7
View File
@@ -1,6 +1,6 @@
// Type definitions for FusionCharts 3.11.2
// Type definitions for fusioncharts 3.11
// Project: http://www.fusioncharts.com
// Definitions by: Shivaraj KV <https://github.com/shivarajkv>
// Definitions by: Rohit Kumar <https://github.com/rohitkr>, Shivaraj KV <https://github.com/shivarajkv>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -136,9 +136,9 @@ declare namespace FusionCharts {
outputTo(callback: (message: any) => any): void;
enable(state:any,outputTo?:(message: any) =>any,outputFormat?:any):void
enable(state: any, outputTo?: (message: any) => any, outputFormat?: any): void;
enableFirebugLite():any;
enableFirebugLite(): any;
}
interface FusionCharts {
@@ -154,7 +154,7 @@ declare namespace FusionCharts {
configureLink(param: {} | any[], level?: number): void;
setChartAttribute(attributes: ChartObject | String, value?: string): void;
setChartAttribute(attributes: ChartObject | string, value?: string): void;
getChartAttribute(attribute?: string | string[]): ChartObject;
@@ -273,7 +273,7 @@ declare namespace FusionCharts {
formatNumber(num: number, type?: string, config?: {}): Element;
setCurrentRenderer(name: string): void
setCurrentRenderer(name: string): void;
getCurrentRenderer(): string;
@@ -285,7 +285,7 @@ declare namespace FusionCharts {
options: {};
debugger:Debugger;
debugger: Debugger;
}
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var usa: (H: FusionChartStatic) => FusionChartStatic;
export = usa;
export as namespace usa;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var world: (H: FusionChartStatic) => FusionChartStatic;
export = world;
export as namespace world;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var carbon: (H: FusionChartStatic) => FusionChartStatic;
export = carbon;
export as namespace carbon;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var fint: (H: FusionChartStatic) => FusionChartStatic;
export = fint;
export as namespace fint;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var ocean: (H: FusionChartStatic) => FusionChartStatic;
export = ocean;
export as namespace ocean;
+7
View File
@@ -0,0 +1,7 @@
import { FusionChartStatic } from "fusioncharts";
declare var zune: (H: FusionChartStatic) => FusionChartStatic;
export = zune;
export as namespace zune;
+14
View File
@@ -18,6 +18,20 @@
},
"files": [
"index.d.ts",
"fusioncharts.charts.d.ts",
"fusioncharts.powercharts.d.ts",
"fusioncharts.widgets.d.ts",
"fusioncharts.maps.d.ts",
"fusioncharts.zoomscatter.d.ts",
"fusioncharts.ssgrid.d.ts",
"fusioncharts.gantt.d.ts",
"fusioncharts.treemap.d.ts",
"maps/fusioncharts.usa.d.ts",
"maps/fusioncharts.world.d.ts",
"themes/fusioncharts.theme.carbon.d.ts",
"themes/fusioncharts.theme.fint.d.ts",
"themes/fusioncharts.theme.ocean.d.ts",
"themes/fusioncharts.theme.zune.d.ts",
"fusioncharts-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+6
View File
@@ -19,6 +19,12 @@ function test_getAuthInstance(){
var auth = gapi.auth2.getAuthInstance();
}
function test_getAuthResponse(){
var user = gapi.auth2.getAuthInstance().currentUser.get();
var authResponse = user.getAuthResponse();
var authResponseWithAuth = user.getAuthResponse(true);
}
function test_render(){
var success = (googleUser: gapi.auth2.GoogleUser): void => {
console.log(googleUser);
+1 -1
View File
@@ -151,7 +151,7 @@ declare namespace gapi.auth2 {
/**
* Get the response object from the user's auth session.
*/
getAuthResponse(): AuthResponse;
getAuthResponse(includeAuthorizationData?: boolean): AuthResponse;
/**
* Returns true if the user granted the specified scopes.
+102 -26
View File
@@ -1,26 +1,24 @@
var featureCollection: GeoJSON.FeatureCollection<any> = {
let featureCollection: GeoJSON.FeatureCollection<any> = {
type: "FeatureCollection",
features: [
{
features: [
{
type: "Feature",
geometry: {
type: "Point",
type: "Point",
coordinates: [102.0, 0.5]
},
properties: {
prop0: "value0"
}
},
{
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: [
[102.0, 0.0],
[103.0, 1.0],
[104.0, 0.0],
[102.0, 0.0],
[103.0, 1.0],
[104.0, 0.0],
[105.0, 1.0]
]
},
@@ -29,7 +27,7 @@ var featureCollection: GeoJSON.FeatureCollection<any> = {
prop1: 0.0
}
},
{
{
type: "Feature",
geometry: {
type: "Polygon",
@@ -52,9 +50,9 @@ var featureCollection: GeoJSON.FeatureCollection<any> = {
type: "proj4"
}
}
}
};
var feature: GeoJSON.Feature<GeoJSON.Polygon> = {
let featureWithPolygon: GeoJSON.Feature<GeoJSON.Polygon> = {
type: "Feature",
bbox: [-180.0, -90.0, 180.0, 90.0],
geometry: {
@@ -67,29 +65,29 @@ var feature: GeoJSON.Feature<GeoJSON.Polygon> = {
};
var point: GeoJSON.Point = {
let point: GeoJSON.Point = {
type: "Point",
coordinates: [100.0, 0.0]
};
// This type is commonly used in the turf package
var pointCoordinates: number[] = point.coordinates
let pointCoordinates: number[] = point.coordinates;
var lineString: GeoJSON.LineString = {
let lineString: GeoJSON.LineString = {
type: "LineString",
coordinates: [ [100.0, 0.0], [101.0, 1.0] ]
};
var polygon: GeoJSON.Polygon = {
let polygon: GeoJSON.Polygon = {
type: "Polygon",
coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
]
};
var polygonWithHole: GeoJSON.Polygon = {
let polygonWithHole: GeoJSON.Polygon = {
type: "Polygon",
coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
@@ -97,12 +95,12 @@ var polygonWithHole: GeoJSON.Polygon = {
]
};
var multiPoint: GeoJSON.MultiPoint = {
let multiPoint: GeoJSON.MultiPoint = {
type: "MultiPoint",
coordinates: [ [100.0, 0.0], [101.0, 1.0] ]
};
var multiLineString: GeoJSON.MultiLineString = {
let multiLineString: GeoJSON.MultiLineString = {
type: "MultiLineString",
coordinates: [
[ [100.0, 0.0], [101.0, 1.0] ],
@@ -110,25 +108,103 @@ var multiLineString: GeoJSON.MultiLineString = {
]
};
var multiPolygon: GeoJSON.MultiPolygon = {
let multiPolygon: GeoJSON.MultiPolygon = {
type: "MultiPolygon",
coordinates: [
[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
[[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
[[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
]
}
};
var geometryCollection: GeoJSON.GeometryCollection = {
let geometryCollection: GeoJSON.GeometryCollection = {
type: "GeometryCollection",
"geometries": [
{
{
type: "Point",
coordinates: [100.0, 0.0]
},
{
{
type: "LineString",
coordinates: [ [101.0, 0.0], [102.0, 1.0] ]
}
]
}
};
let feature: GeoJSON.Feature<GeoJSON.GeometryObject> = {
type: "Feature",
geometry: lineString,
properties: null
};
feature = {
type: "Feature",
geometry: polygon,
properties: null
};
feature = {
type: "Feature",
geometry: polygonWithHole,
properties: null
};
feature = {
type: "Feature",
geometry: multiPoint,
properties: null
};
feature = {
type: "Feature",
geometry: multiLineString,
properties: null
};
feature = {
type: "Feature",
geometry: multiPolygon,
properties: null
};
feature = {
type: "Feature",
geometry: geometryCollection,
properties: null
};
featureCollection = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: lineString,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: polygon,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: polygonWithHole,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: multiPoint,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: multiLineString,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: multiPolygon,
properties: {test: 'OK'}
}, {
type: "Feature",
geometry: geometryCollection,
properties: {test: 'OK'}
}
],
crs: {
type: "link",
properties: {
href: "http://example.com/crs/42",
type: "proj4"
}
}
};
+40 -50
View File
@@ -1,4 +1,4 @@
// Type definitions for GeoJSON Format Specification
// Type definitions for GeoJSON Format Specification Revision 1.0
// Project: http://geojson.org/
// Definitions by: Jacob Bruun <https://github.com/cobster/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -8,8 +8,7 @@ declare namespace GeoJSON {
/***
* http://geojson.org/geojson-spec.html#geojson-objects
*/
export interface GeoJsonObject
{
export interface GeoJsonObject {
type: string;
bbox?: number[];
crs?: CoordinateReferenceSystem;
@@ -18,116 +17,107 @@ declare namespace GeoJSON {
/***
* http://geojson.org/geojson-spec.html#positions
*/
export type Position = number[]
export type Position = number[];
/***
* http://geojson.org/geojson-spec.html#geometry-objects
*/
export interface GeometryObject extends GeoJsonObject
{
coordinates: any
interface DirectGeometryObject extends GeoJsonObject {
coordinates: Position[][][] | Position[][] | Position[] | Position;
}
/**
* GeometryObject supports geometry collection as well
*/
export type GeometryObject = DirectGeometryObject | GeometryCollection;
/***
* http://geojson.org/geojson-spec.html#point
*/
export interface Point extends GeometryObject
{
type: 'Point'
coordinates: Position
export interface Point extends DirectGeometryObject {
type: 'Point';
coordinates: Position;
}
/***
* http://geojson.org/geojson-spec.html#multipoint
*/
export interface MultiPoint extends GeometryObject
{
type: 'MultiPoint'
coordinates: Position[]
export interface MultiPoint extends DirectGeometryObject {
type: 'MultiPoint';
coordinates: Position[];
}
/***
* http://geojson.org/geojson-spec.html#linestring
*/
export interface LineString extends GeometryObject
{
type: 'LineString'
coordinates: Position[]
export interface LineString extends DirectGeometryObject {
type: 'LineString';
coordinates: Position[];
}
/***
* http://geojson.org/geojson-spec.html#multilinestring
*/
export interface MultiLineString extends GeometryObject
{
type: 'MultiLineString'
coordinates: Position[][]
export interface MultiLineString extends DirectGeometryObject {
type: 'MultiLineString';
coordinates: Position[][];
}
/***
* http://geojson.org/geojson-spec.html#polygon
*/
export interface Polygon extends GeometryObject
{
type: 'Polygon'
coordinates: Position[][]
export interface Polygon extends DirectGeometryObject {
type: 'Polygon';
coordinates: Position[][];
}
/***
* http://geojson.org/geojson-spec.html#multipolygon
*/
export interface MultiPolygon extends GeometryObject
{
type: 'MultiPolygon'
coordinates: Position[][][]
export interface MultiPolygon extends DirectGeometryObject {
type: 'MultiPolygon';
coordinates: Position[][][];
}
/***
* http://geojson.org/geojson-spec.html#geometry-collection
*/
export interface GeometryCollection extends GeoJsonObject
{
type: 'GeometryCollection'
export interface GeometryCollection extends GeoJsonObject {
type: 'GeometryCollection';
geometries: GeometryObject[];
}
/***
* http://geojson.org/geojson-spec.html#feature-objects
*/
export interface Feature<T extends GeometryObject> extends GeoJsonObject
{
type: 'Feature'
export interface Feature<T extends GeometryObject> extends GeoJsonObject {
type: 'Feature';
geometry: T;
properties: any;
properties: {} | null;
id?: string;
}
/***
* http://geojson.org/geojson-spec.html#feature-collection-objects
*/
export interface FeatureCollection<T extends GeometryObject> extends GeoJsonObject
{
type: 'FeatureCollection'
features: Feature<T>[];
export interface FeatureCollection<T extends GeometryObject> extends GeoJsonObject {
type: 'FeatureCollection';
features: Array<Feature<T>>;
}
/***
* http://geojson.org/geojson-spec.html#coordinate-reference-system-objects
*/
export interface CoordinateReferenceSystem
{
export interface CoordinateReferenceSystem {
type: string;
properties: any;
}
export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem
{
properties: { name: string }
export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem {
properties: { name: string };
}
export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem
{
properties: { href: string; type: string }
export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem {
properties: { href: string; type: string };
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"no-single-declare-module": false
}
}
+41
View File
@@ -0,0 +1,41 @@
import Hapi = require('hapi');
import hapiAuthJwt2 = require('hapi-auth-jwt2');
var server = new Hapi.Server();
server.connection({port: 8000});
interface User {
id: number;
name: string;
}
interface Users {
[id: number]: User
}
var users:Users = {
1: {
id: 1,
name: 'Test User'
}
};
var validate = function(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) {
if (!users[decoded.id]) {
return callback(null, false);
}
return callback(null, true);
}
server.register(hapiAuthJwt2, function(err) {
server.auth.strategy('jwt', 'jwt', <hapiAuthJwt2.Options>{
key: 'NeverShareYourSecret',
validateFunc: validate,
verifyOptions: {
algorithms: ['HS256']
}
});
});
server.start();
+126
View File
@@ -0,0 +1,126 @@
// Type definitions for hapi-auth-jwt2 7.0
// Project: http://github.com/dwyl/hapi-auth-jwt2
// Definitions by: Warren Seymour <http://github.com/warrenseymour>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import {Request, Response} from 'hapi';
/**
* A key lookup function
*
* @param decoded the *decoded* but *unverified* JWT received from client
* @param callback the key lookup callback
*/
type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void;
/**
* Called when key lookup function has completed
*
* @param err an internal error
* @param key the secret key
* @param extraInfo any additional information that you would like
* to use in `validateFunc` which can be accessed via
* `request.plugins['hapi-auth-jwt2'].extraInfo`
*/
type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void;
/**
* Called when Validation has completed
*
* @param err an internal error
* @param valid `true` if the JWT was valid, otherwise `false`
* @param credentials alternative credentials to be set instead of `decoded`
*/
type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void;
/**
* Options passed to `hapi.auth.strategy` when this plugin is used
*/
export interface Options {
/**
* The secret key used to check the signature of the token *or* a *key lookup function*
*/
key?: string | KeyLookup;
/**
* The function which is run once the Token has been decoded
*
* @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization*
* @param request the original *request* received from the client
* @param callback the validation callback
*/
validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void;
/**
* Settings to define how tokens are verified by the jsonwebtoken library
*/
verifyOptions?: {
/**
* Ignore expired tokens
*/
ignoreExpiration?: boolean;
/**
* Do not enforce token audience
*/
audience?: boolean;
/**
* Do not require the issuer to be valid
*/
issuer?: boolean;
/**
* List of allowed algorithms
*/
algorithms?: string[];
};
/**
* function called to decorate the response with authentication headers
* before the response headers or payload is written
*
* @param request the Request object
* @param reply is called if an error occurred
*/
responseFunc?(request: Request, reply: (err: any, response: Response) => void): void;
/**
* If you prefer to pass your token via url, simply add a token url
* parameter to your request or use a custom parameter by setting `urlKey.
* To disable the url parameter set urlKey to `false` or ''.
* @default 'token'
*/
urlKey?: string | boolean;
/**
* If you prefer to set your own cookie key or your project has a cookie
* called 'token' for another purpose, you can set a custom key for your
* cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies
* set cookieKey to `false` or ''.
* @default 'token'
*/
cookieKey?: string | boolean;
/**
* If you want to set a custom key for your header token use the
* `headerKey` option. To disable header token set headerKey to `false` or
* ''.
* @default 'authorization'
*/
headerKey?: string | boolean;
/**
* Allow custom token type, e.g. `Authorization: <tokenType> 12345678`
*/
tokenType?: string;
/**
* Set to `true` to receive the complete token (`decoded.header`,
* `decoded.payload` and `decoded.signature`) as decoded argument to key
* lookup and `verifyFunc` callbacks (*not `validateFunc`*)
* @default false
*/
complete?: boolean;
}
export default function hapiAuthJwt2(): void;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi-auth-jwt2-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+15
View File
@@ -39,3 +39,18 @@ class TestController implements Controller {
const server = new hapi.Server();
server.route(new TestController().routes());
@controller('/test')
class SimpleTestController implements Controller {
foo: string;
constructor(foo: string) {
this.foo = foo;
}
baseUrl: string;
routes: () => hapi.IRouteConfiguration[];
}
server.route(new SimpleTestController('bar').routes());
+1 -1
View File
@@ -5,7 +5,7 @@
import * as hapi from 'hapi';
interface ControllerStatic {
new (): Controller;
new (...args: any[]): Controller;
}
export interface Controller {
baseUrl: string;
+2 -1
View File
@@ -33,7 +33,8 @@ class AppController {
title: {
text: 'My Awesome Chart'
},
loading: true
loading: true,
noData: 'No data here'
};
constructor($timeout: ng.ITimeoutService) {
var vm = this;
+2
View File
@@ -35,6 +35,8 @@ declare global {
};
//function (optional) - setup some logic for the chart
func?: (chart: ChartObject) => void;
//no data text (optional) to show if all series are empty
noData?: string;
}
//Instantiated Chart
+7
View File
@@ -701,6 +701,13 @@ declare namespace Highcharts {
* @default false
*/
reversed?: boolean;
/**
* If true, the first series in a stack will be drawn on top in a positive, non-reversed Y axis. If false, the first series is in the base of the stack.
* Only used for yAxis
* @default true
* @since 3.0.10
*/
reversedStacks?: boolean;
/**
* Whether to show the axis line and title when the axis has no data.
* @default true
@@ -1,34 +1,24 @@
import HtmlWebpackPlugin = require("html-webpack-plugin");
import { Configuration } from "webpack";
import * as HtmlWebpackPlugin from 'html-webpack-plugin';
const a: Configuration = {
plugins: [
new HtmlWebpackPlugin()
]
};
new HtmlWebpackPlugin();
const b: Configuration = {
plugins: [
new HtmlWebpackPlugin({
title: "test"
})
]
};
const optionsArray: HtmlWebpackPlugin.Options[] = [
{
title: 'test',
},
{
minify: {
caseSensitive: true,
},
},
{
chunksSortMode: function compare(a, b) {
return 1;
},
},
{
arbitrary: 'data',
},
];
const minify: HtmlWebpackPlugin.MinifyConfig = {
caseSensitive: true
};
new HtmlWebpackPlugin({
minify
});
new HtmlWebpackPlugin({
chunksSortMode: function compare(a, b) {
return 1;
}
});
new HtmlWebpackPlugin({
arbitrary: "data"
});
const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpackPlugin(options));
+72 -92
View File
@@ -3,106 +3,86 @@
// Definitions by: Simon Hartcher <https://github.com/deevus>, Benjamin Lim <https://github.com/bumbleblym>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Plugin, Webpack } from "webpack";
import { Options } from "html-minifier";
import { Plugin } from 'webpack';
import { Options as HtmlMinifierOptions } from 'html-minifier';
export = HtmlWebpackPlugin;
declare class HtmlWebpackPlugin implements Plugin {
constructor(options?: HtmlWebpackPlugin.Config);
apply(thisArg: Webpack, ...args: any[]): void;
declare class HtmlWebpackPlugin extends Plugin {
constructor(options?: HtmlWebpackPlugin.Options);
}
declare namespace HtmlWebpackPlugin {
export type MinifyConfig = Options;
type MinifyOptions = HtmlMinifierOptions;
/**
* It is assumed that each [chunk] contains at least the properties "id"
* (containing the chunk id) and "parents" (array containing the ids of the
* parent chunks).
*/
export interface Chunk { // TODO: Import from webpack?
id: string;
parents: string[];
[propName: string]: any; // TODO: Narrow type
}
/**
* It is assumed that each [chunk] contains at least the properties "id"
* (containing the chunk id) and "parents" (array containing the ids of the
* parent chunks).
*
* @todo define in webpack
*/
interface Chunk {
id: string;
parents: string[];
[propName: string]: any;
}
export type ChunkComparator = (a: Chunk, b: Chunk) => number;
type ChunkComparator = (a: Chunk, b: Chunk) => number;
export interface Config {
/**
* The title to use for the generated HTML document.
*/
title?: string;
interface Options {
/** `true | false` if `true` (default) try to emit the file only if it was changed. */
cache?: boolean;
/**
* Allows to control how chunks should be sorted before they are included to the html.
* Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'`
*/
chunksSortMode?: 'none' | 'auto' | 'dependency' | ChunkComparator;
/** Allows you to add only some chunks (e.g. only the unit-test chunk) */
chunks?: string[];
/** Allows you to skip some chunks (e.g. don't add the unit-test chunk) */
excludeChunks?: string[];
/** Adds the given favicon path to the output html. */
favicon?: string;
/**
* The file to write the HTML to.
* Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`).
*/
filename?: string;
/**
* `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files.
* This is useful for cache busting.
*/
hash?: boolean;
/**
* `true | 'head' | 'body' | false`
* Inject all assets into the given template or templateContent.
* When passing true or 'body' all javascript resources will be placed at the bottom of the body element.
* 'head' will place the scripts in the head element.
*/
inject?: 'body' | 'head' | boolean;
/**
* `{...} | false` Pass a html-minifier options object to minify the output.
* https://github.com/kangax/html-minifier#options-quick-reference
*/
minify?: false | MinifyOptions;
/** `true | false` if `true` (default) errors details will be written into the html page. */
showErrors?: boolean;
/** Webpack require path to the template. Please see the docs for details. */
template?: string;
/** The title to use for the generated HTML document. */
title?: string;
/** `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false` */
xhtml?: boolean;
/**
* In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through
* to your template.
*/
[option: string]: any;
}
/**
* The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`).
*/
filename?: string;
/**
* Webpack require path to the template. Please see the docs for details.
*/
template?: string;
/**
* `true | 'head' | 'body' | false`
*
* Inject all assets into the given template or templateContent - When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element.
*/
inject?: boolean | "head" | "body";
/**
* Adds the given favicon path to the output html.
*/
favicon?: string;
/**
* `{...} | false` Pass a html-minifier options object to minify the output.
*
* https://github.com/kangax/html-minifier#options-quick-reference
*/
minify?: MinifyConfig | false;
/**
* `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting.
*/
hash?: boolean;
/**
* `true | false` if `true` (default) try to emit the file only if it was changed.
*/
cache?: boolean;
/**
* `true | false` if `true` (default) errors details will be written into the html page.
*/
showErrors?: boolean;
/**
* Allows you to add only some chunks (e.g. only the unit-test chunk)
*/
chunks?: string[];
/**
* Allows to control how chunks should be sorted before they are included to the html. Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'`
*/
chunksSortMode?: "none" | "auto" | "dependency" | ChunkComparator;
/**
* Allows you to skip some chunks (e.g. don't add the unit-test chunk)
*/
excludeChunks?: string[];
/**
* `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false`
*/
xhtml?: boolean;
/**
* In addition to the options actually used by this plugin, you can use
* this hash to pass arbitrary data through to your template.
*/
[option: string]: any;
}
/** @deprecated use MinifyOptions */
type MinifyConfig = MinifyOptions;
/** @deprecated use Options */
type Config = Options;
}

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