Merge pull request #11 from DefinitelyTyped/master

Latest changes from head
This commit is contained in:
Christopher Cortes
2017-06-12 17:34:50 +02:00
committed by GitHub
1573 changed files with 161942 additions and 34577 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ If adding a new definition:
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dslint/dt.json" }`.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`.
If removing a declaration:
- [ ] If a package was never on DefinitelyTyped, you don't need to do anything. (If you wrote a package and provided types, you don't need to register it with us.)
+10 -2
View File
@@ -12,7 +12,6 @@
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
@@ -25,19 +24,28 @@ Properties
# test folder
_infrastructure/tests/build
# IntelliJ based IDEs
.idea
*.iml
*.js.map
!*.js/
!scripts/new-package.js
!scripts/not-needed.js
!scripts/lint.js
# npm
node_modules
package-lock.json
npm-debug.log
# Sublime
.sublimets
.settings/launch.json
# Visual Studio Code
.settings/launch.json
.vs
.vscode
# yarn
yarn.lock
+7
View File
@@ -89,6 +89,13 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
* Make changes. Remember to edit tests.
* You may also want to add yourself to "Definitions by" section of the package header.
- Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `npm install -g typescript@2.0` and run `tsc`.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
+42
View File
@@ -54,6 +54,12 @@
"sourceRepoURL": "http://www.babylonjs.com/",
"asOfVersion": "2.4.1"
},
{
"libraryName": "BigInteger.js",
"typingsPackageName": "big-integer",
"sourceRepoURL": "https://github.com/peterolson/BigInteger.js",
"asOfVersion": "0.0.31"
},
{
"libraryName": "Bugsnag Browser",
"typingsPackageName": "bugsnag-js",
@@ -120,6 +126,12 @@
"sourceRepoURL": "https://github.com/bterlson/ecmarkup",
"asOfVersion": "3.4.0"
},
{
"libraryName": "electron",
"typingsPackageName": "electron",
"sourceRepoURL": "https://github.com/electron/electron",
"asOfVersion": "1.6.10"
},
{
"libraryName": "electron-builder",
"typingsPackageName": "electron-builder",
@@ -132,6 +144,12 @@
"sourceRepoURL": "https://github.com/primus/eventemitter3",
"asOfVersion": "2.0.2"
},
{
"libraryName": "express-validator",
"typingsPackageName": "express-validator",
"sourceRepoURL": "https://github.com/ctavan/express-validator",
"asOfVersion": "3.0.0"
},
{
"libraryName": "JSON-Patch",
"typingsPackageName": "fast-json-patch",
@@ -222,6 +240,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/is-upper-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "jquery.ajaxfile",
"typingsPackageName": "jquery.ajaxfile",
"sourceRepoURL": "https://github.com/fpellet/jquery.ajaxFile",
"asOfVersion": "0.2.29"
},
{
"libraryName": "JSNLog",
"typingsPackageName": "jsnlog",
@@ -354,6 +378,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/path-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "path-to-regexp",
"typingsPackageName": "path-to-regexp",
"sourceRepoURL": "https://github.com/pillarjs/path-to-regexp",
"asOfVersion": "1.7.0"
},
{
"libraryName": "pg-promise",
"typingsPackageName": "pg-promise",
@@ -396,6 +426,12 @@
"sourceRepoURL": "https://github.com/getsentry/raven-js",
"asOfVersion": "3.10.0"
},
{
"libraryName": "react-day-picker",
"typingsPackageName": "react-day-picker",
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
"asOfVersion": "5.3.0"
},
{
"libraryName": "Redux",
"typingsPackageName": "redux",
@@ -408,6 +444,12 @@
"sourceRepoURL": "https://github.com/tshelburne/redux-batched-actions",
"asOfVersion": "0.1.5"
},
{
"libraryName": "redux-devtools-extension",
"typingsPackageName": "redux-devtools-extension",
"sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension",
"asOfVersion": "2.13.2"
},
{
"libraryName": "redux-persist",
"typingsPackageName": "redux-persist",
+3 -1
View File
@@ -2643,7 +2643,9 @@ declare namespace AceAjax {
characterWidth: number;
lineHeight: number;
setScrollMargin(top:number, bottom:number, left: number, right: number): void;
screenToTextCoordinates(left: number, top: number): void;
/**
+1
View File
@@ -15,6 +15,7 @@ const aceVirtualRendererTests = {
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setScrollMargin(0,0,0,0)
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="bluebird" />
/// <reference types="node"/>
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/rschmukler/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
+17 -7
View File
@@ -1,13 +1,17 @@
// Type definitions for Alexa SDK for Node.js v1.0.3
// Type definitions for Alexa SDK for Node.js v1.1.0
// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
// Definitions by: Pete Beegle <https://github.com/petebeegle>
// Definitions by: Pete Beegle <https://github.com/petebeegle>, Huw <https://github.com/hoo29>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject;
export function CreateStateHandler(state: string, obj: any): any;
export var StateString: string;
interface AlexaObject {
type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED";
type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED";
interface AlexaObject extends Handler {
_event: any;
_context: any;
_callback: any;
@@ -74,12 +78,20 @@ interface SessionUser {
interface LaunchRequest extends IRequest { }
interface IntentRequest extends IRequest {
dialogState: DialogStates;
intent: Intent;
}
interface Intent {
interface SlotValue {
confirmationStatus: ConfirmationStatuses;
name: string;
slots: any;
value?: any;
}
interface Intent {
confirmationStatus: ConfirmationStatuses;
name: string;
slots: Record<string, SlotValue>;
}
interface SessionEndedRequest extends IRequest {
@@ -127,5 +139,3 @@ interface Image {
interface Reprompt {
outputSpeech: OutputSpeech;
}
@@ -0,0 +1,34 @@
import * as AVS from "alexa-voice-service";
const options = {
debug: true,
clientId: "",
clientSecret: "",
deviceId: "",
refreshToken: "",
};
const avsInstance = new AVS(options);
avsInstance.on(AVS.EventTypes.RECORD_START, () => {
});
avsInstance.on(AVS.EventTypes.RECORD_STOP, () => {
});
avsInstance.player.on(AVS.Player.EventTypes.PLAY, () => {
});
avsInstance.refreshToken().then((tokens) => {
}).catch((error: Error) => {
});
avsInstance.requestMic();
avsInstance.startRecording();
avsInstance.stopRecording().then((dataView: any) => { });
const dataView = new DataView(new ArrayBuffer(1));
avsInstance.sendAudio(dataView).then(({ xhr, response }: any) => { });
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for alexa-voice-service 0.0
// Project: https://github.com/miguelmota/alexa-voice-service.js
// Definitions by: Dolan Miu <https://github.com/dolanmiu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace AVS;
export = AVS;
declare namespace AVS {
enum EventTypes {
RECORD_STOP, RECORD_START, ERROR, TOKEN_INVALID, LOG, LOGIN, LOGOUT, TOKEN_SET, REFRESH_TOKEN_SET
}
interface AVSParams {
debug: boolean;
clientId: string;
clientSecret: string;
deviceId: string;
refreshToken: string;
}
interface TokenResponse {
token: string;
refreshToken: string;
}
class Player {
on(eventType: Player.EventTypes, callback?: () => void): void;
}
namespace Player {
enum EventTypes {
LOG, ERROR, PLAY, REPLAY, PAUSE, STOP, ENQUEUE, DEQUE
}
}
}
declare class AVS {
player: AVS.Player;
constructor(params: AVS.AVSParams);
on(eventType: AVS.EventTypes, callback?: () => void): void;
refreshToken(): Promise<AVS.TokenResponse>;
requestMic(): Promise<any>;
startRecording(): Promise<void>;
stopRecording(): Promise<DataView | undefined>;
sendAudio(dataView: DataView): Promise<{
xhr: any, response: {
httpVersion: string,
statusCode: string,
statusMessage: string,
method: string,
url: string,
headers: string,
body: string,
boundary: string,
multipart: string
}
}>;
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"alexa-voice-service-tests.ts"
]
}
+66 -57
View File
@@ -1,41 +1,52 @@
import algoliasearch = require('algoliasearch');
import { ClientOptions, SynonymOption, AlgoliaUserKeyOptions, SearchSynonymOptions,
import * as algoliasearch from "algoliasearch";
import { ClientOptions, SynonymOption, AlgoliaUserKeyOptions, SearchSynonymOptions, AlgoliaResponse,
AlgoliaSecuredApiOptions, AlgoliaIndexSettings, AlgoliaQueryParameters, AlgoliaIndex } from "algoliasearch";
var _clientOptions: ClientOptions = {
timeout : 12,
let _algoliaResponse: AlgoliaResponse = {
hits: [{}, {}],
page: 0,
nbHits: 12,
nbPages: 6,
hitsPerPage: 2,
processingTimeMS: 32,
query: "",
params: "",
};
let _clientOptions: ClientOptions = {
timeout: 12,
protocol: "",
httpAgent: ""
httpAgent: "",
};
var _synonymOption: SynonymOption = {
let _synonymOption: SynonymOption = {
forwardToSlaves: false,
replaceExistingSynonyms: false
replaceExistingSynonyms: false,
};
var _algoliaUserKeyOptions : AlgoliaUserKeyOptions = {
let _algoliaUserKeyOptions: AlgoliaUserKeyOptions = {
validity: 0,
maxQueriesPerIPPerHour: 0,
indexes: [""],
queryParameters: { attributesToRetrieve: ["algolia"] },
description: ""
description: "",
};
var _searchSynonymOptions : SearchSynonymOptions = {
let _searchSynonymOptions: SearchSynonymOptions = {
query: "",
page: 0,
type: "",
hitsPerPage: 0
hitsPerPage: 0,
};
var _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = {
let _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = {
filters: "",
validUntil: 0,
restrictIndices: "",
userToken: ""
userToken: "",
};
var _algoliaIndexSettings : AlgoliaIndexSettings = {
let _algoliaIndexSettings: AlgoliaIndexSettings = {
attributesToIndex: [""],
attributesforFaceting: [""],
unretrievableAttributes: [""],
@@ -43,12 +54,12 @@ var _algoliaIndexSettings : AlgoliaIndexSettings = {
ranking: [""],
customRanking: [""],
slaves: [""],
maxValuesPerFacet: '',
maxValuesPerFacet: "",
attributesToHighlight: [""],
attributesToSnippet: [""],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
highlightPreTag: "",
highlightPostTag: "",
snippetEllipsisText: "",
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
minWordSizefor1Typo: 0,
@@ -56,16 +67,16 @@ var _algoliaIndexSettings : AlgoliaIndexSettings = {
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
separatorsToIndex: '',
queryType: '',
removeWordsIfNoResults: '',
disableTypoToleranceOnAttributes: "",
separatorsToIndex: "",
queryType: "",
removeWordsIfNoResults: "",
advancedSyntax: false,
optionalWords: [""],
removeStopWords: [""],
disablePrefixOnAttributes: [""],
disableExactOnAttributes: [""],
exactOnSingleWordQuery: '',
exactOnSingleWordQuery: "",
alternativesAsExact: false,
attributeForDistinct: "",
distinct: false,
@@ -73,21 +84,21 @@ var _algoliaIndexSettings : AlgoliaIndexSettings = {
allowCompressionOfIntegerArray: false,
altCorrections: [{}],
minProximity: 0,
placeholders: ''
placeholders: "",
};
var _algoliaQueryParameters : AlgoliaQueryParameters = {
query: '',
filters: '',
let _algoliaQueryParameters: AlgoliaQueryParameters = {
query: "",
filters: "",
attributesToRetrieve: [""],
restrictSearchableAttributes: [""],
facets: '',
maxValuesPerFacet: '',
attributesToHighlight: [''],
attributesToSnippet: [''],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
facets: "",
maxValuesPerFacet: "",
attributesToHighlight: [""],
attributesToSnippet: [""],
highlightPreTag: "",
highlightPostTag: "",
snippetEllipsisText: "",
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
page: 0,
@@ -98,38 +109,36 @@ var _algoliaQueryParameters : AlgoliaQueryParameters = {
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: '',
disableTypoToleranceOnAttributes: "",
aroundLatLng: "",
aroundLatLngViaIP: "",
aroundRadius: "",
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: '',
queryType: '',
insidePolygon: '',
removeWordsIfNoResults: '',
insideBoundingBox: "",
queryType: "",
insidePolygon: "",
removeWordsIfNoResults: "",
advancedSyntax: false,
optionalWords: [''],
removeStopWords: [''],
disableExactOnAttributes: [''],
exactOnSingleWordQuery: '',
optionalWords: [""],
removeStopWords: [""],
disableExactOnAttributes: [""],
exactOnSingleWordQuery: "",
alternativesAsExact: true,
distinct: 0,
getRankingInfo: false,
numericAttributesToIndex: [''],
numericFilters: [''],
tagFilters: '',
facetFilters: '',
numericAttributesToIndex: [""],
numericFilters: [""],
tagFilters: "",
facetFilters: "",
analytics: false,
analyticsTags: [''],
analyticsTags: [""],
synonyms: true,
replaceSynonymsInHighlight: false,
minProximity: 0
minProximity: 0,
};
var index: AlgoliaIndex = algoliasearch('', '').initIndex('');
var search = index.search({query: ""});
index.search({query: ""}, function(err, res){});
let index: AlgoliaIndex = algoliasearch("", "").initIndex("");
let search = index.search({query: ""});
index.search({query: ""}, (err, res) => {});
+3 -3
View File
@@ -24,7 +24,7 @@ declare namespace algoliasearch {
* Number of pages
* https://github.com/algolia/algoliasearch-client-js#response-format
*/
nbPage: number;
nbPages: number;
/**
* Number of hits per pages
* https://github.com/algolia/algoliasearch-client-js#response-format
@@ -407,7 +407,7 @@ declare namespace algoliasearch {
* @param cb(err, res)
* https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
*/
saveSynonym(synonym: AlgoliaSynonym, option: SynonymOption, cb: (err: Error, res: any) => void): void;
saveSynonym(synonym: AlgoliaSynonym, options: SynonymOption, cb: (err: Error, res: any) => void): void;
/**
* Save a synonym object
* @param synonyms
@@ -659,7 +659,7 @@ declare namespace algoliasearch {
* return {Promise}
* https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
*/
saveSynonym(synonym: AlgoliaSynonym, option: SynonymOption): Promise<any> ;
saveSynonym(synonym: AlgoliaSynonym, options: SynonymOption): Promise<any> ;
/**
* Save a synonym object
* @param synonyms
+1 -1
View File
@@ -119,7 +119,7 @@ interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(new TestStore());
function testCallback(state:AltTestState) {
console.log(state);
+4
View File
@@ -2271,6 +2271,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
hideBulletsCount: number;
/** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */
highField: string;
/** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used.*/
id?: string;
/** Whether to include this graph when calculating min and max value of the axis.
@default true
*/
+69
View File
@@ -0,0 +1,69 @@
import * as amqp from 'amqp';
async function connect() {
const promise = new Promise<amqp.AMQPClient>((resolve, reject) => {
const client = amqp.createConnection({
url: 'amqp://admin:password@localhost:5672'
});
client.once('error', reject);
client.once('ready', resolve);
});
return promise;
}
async function start() {
try {
const client = await connect();
console.log('Connected');
const queue = client.queue('perth-now',
{
autoDelete: false,
durable: true,
}, q => {
console.log('Queue opened');
console.log('Name: %s Channel: %s', q.name, q.channel);
queue.bind('amq.fanout', '#', () => {
queue.subscribe(
{ ack: true },
(msg, _, __, ack) => {
ack.acknowledge(true);
});
});
});
const exchange = client.exchange('amq.fanout', { confirm: true });
exchange.once('open', () => {
exchange.publish(
'content',
{ message: new Date().toLocaleTimeString() },
{ deliveryMode: 2 },
(err, msg) => {
if (!err) {
return;
}
throw new Error(`Failed to publish: ${msg}`);
}
);
exchange.publish('content', { message: 'content message' }, () => {
console.log('Published');
});
});
} catch (ex) {
console.log(ex);
process.exit(1);
}
}
async function wait(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
start();
+419
View File
@@ -0,0 +1,419 @@
// Type definitions for amqp 0.2
// Project: https://github.com/postwait/node-amqp
// Definitions by: Carl Winkler <https://github.com/seikho>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as net from 'net';
import * as events from 'events';
export type Callback<T> = (value: T) => void;
export interface AMQPClient extends net.Socket {
publish(routingKey: string, body: any, options: {}, callback: (err?: boolean, msg?: string) => void): void;
disconnect(): void;
queue(queueName: string, callback?: Callback<QueueCallback>): AMQPQueue;
queue(queueName: string, options: QueueOptions, callback?: Callback<QueueCallback>): AMQPQueue;
exchange(callback?: Callback<void>): AMQPExchange;
exchange(exchangeName: string, callback?: Callback<void>): AMQPExchange;
exchange(exchangeName: string, options: ExchangeOptions, callback?: Callback<void>): AMQPExchange;
}
export interface AMQPQueue extends events.EventEmitter {
subscribe(callback: SubscribeCallback): void;
subscribe(options: SubscribeOptions, callback: SubscribeCallback): void;
unsubscribe(consumerTag: string): void;
bind(exchangeName: string, routingKey: string, callback?: Callback<AMQPQueue>): void;
bind(routingKey: string, callback?: Callback<AMQPQueue>): void;
unbind(exchangeName: string, routingKey: string): void;
unbind(routingKey: string): void;
bind_headers(exchangeName: string, routingKey: string): void;
bind_headers(routingKey: string): void;
unbind_headers(exchangeName: string, routingKey: string): void;
unbind_headers(routingKey: string): void;
shift(reject: boolean): void;
shift(reject: boolean, requeue: boolean): void;
destroy(options?: DestroyOptions): void;
}
export interface AMQPExchange extends events.EventEmitter {
on(event: 'open' | 'ack' | 'error' | 'exchangeBindOk' | 'exchangeUnbindOk', callback: Callback<void>): this;
publish(routingKey: string, message: Buffer | {}, options: ExchangePublishOptions, callback?: (err?: boolean, msg?: string) => void): void;
/**
* ifUnused default: true
*
* Deletes an exchange.
*
* If the optional boolean second argument is set, the server will only delete the exchange if it has no queue bindings.
*
* If the exchange has queue bindings the server does not delete it but raises a channel exception instead
*/
destroy(ifUnused: boolean): void;
bind(sourceExchange: string, routingKey: string, callback?: Callback<void>): void;
unbind(sourceExchange: string, routingKey: string, callback?: Callback<void>): void;
bind_headers(exchange: string, routing: string, callback?: Callback<void>): void;
}
export function createConnection(options: ConnectionOptions): AMQPClient;
export interface DeliveryInfo {
contentType: string;
consumerTag: string;
deliveryTag: Uint8Array;
exchange: string;
queue: string;
redelivered: boolean;
routingKey: string;
}
export interface Ack extends DeliveryInfo {
acknowledge(all: boolean): void;
reject(requeue: boolean): void;
}
export interface ConnectionOptions {
host?: string;
url?: string;
port?: number;
login?: string;
passowrd?: string;
connectionTimeout?: number;
authMechanism?: string;
vhost?: string;
noDelay?: boolean;
ssl?: {
enabled: boolean;
keyFile?: string;
certFile?: string;
caFile?: string;
rejectUnauthorized?: boolean;
};
/** Default: 'node-amqp' */
product?: string;
/** Default: 'node-{NODE_VERSION}' */
platform?: string;
/** Default: node-amqp/package.json version */
version?: string;
defaultExchangeName?: string;
/** Default: true */
reconnect?: boolean;
/** Default: 'linear' */
reconnectBackoffStrategy?: string;
/** Default: 120000 */
reconnectExponentialLimit?: number;
/** Default: 1000 */
reconnectBackoffTime?: number;
}
export interface QueueOptions {
/**
* Default: false
*
* If set, the server will not create the queue.
*
* The client can use this to check whether a queue exists without modifying the server state
*/
passive?: boolean;
/**
* Default: false
*
* Durable queues remain active when a server restarts.
*
* Non-durable queues (transient queues) are purged if/when a server restarts.
*
* Note that durable queues do not necessarily hold persistent messages,
* although it does not make sense to send persistent messages to a transient queue
*/
durable?: boolean;
/**
* Default: false
*
* Exclusive queues may only be consumed from by the current connection.
*
* Setting the 'exclusive' flag always implies 'autoDelete'
*/
exclusive?: boolean;
/**
* Default: true
*
* If set, the queue is deleted when all consumers have finished using it.
*
* Last consumer can be cancelled either explicitly or because its channel is closed.
*
* If there was no consumer ever on the queue, it won't be deleted
*/
autoDelete?: boolean;
/**
* Default: false
*
* If set, the queue will not be declared, this will allow a queue to be deleted if you don't know its previous options
*/
noDeclare?: boolean;
/**
* a map of additional arguments to pass in when creating a queue
*/
arguments?: { [arg: string]: any };
/**
* Default: false
*
* when true the channel will close on unsubscribe
*/
closeChannelOnUnsubscribe?: boolean;
}
export interface ExchangeOptions {
/**
* Default: 'topic'
*/
type?: 'direct' | 'fanout' | 'topic';
/**
* Default: false
*
* f set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state
*/
passive?: boolean;
/**
* Default: true
*
* If set when creating a new exchange, the exchange will be marked as durable.
*
* Durable exchanges remain active when a server restarts.
*
* Non-durable exchanges (transient exchanges) are purged if/when a server restarts
*/
durable?: boolean;
/**
* Default: true
*
* If set, the exchange is deleted when there are no longer queues bound to it
*/
autoDelete?: boolean;
/**
* Default: false
*
* If set, the exchange will not be declared,
* this will allow the exchange to be deleted if you dont know its previous options
*/
noDeclare?: boolean;
/**
* Default: false
*
* If set, the exchange will be in confirm mode, and you will get a 'ack'|'error' event emitted on a publish,
* or the callback on the publish will be called
*/
confirm?: boolean;
/**
* a map of additional arguments to pass in when creating an exchange
*/
arguments?: { [arg: string]: any };
}
export interface SubscribeOptions {
/**
* Default: false
*
* If set to true, only one subscriber is allowed at a time
*/
exclusive?: boolean;
/**
* Default: false
*
* Make it so that the AMQP server only delivers single messages at a time.
* When you want the next message, call queue.shift()
*
* When false, you will receive messages as fast as they are emitted
*/
ack?: boolean;
/**
* Default: 1
*
* Will only send you N messages before you 'ack'.
*
* Setting to zero will widen that window to 'unlimited'. If this is set, queue.shift() should not be used
*/
prefetchCount?: number;
/**
* Default: undefined
*
* Will inject the routingKey into the payload received
*/
routingKeyInPayload?: boolean;
/**
* Default: undefined
*
* Will inject the routingKey into the payload received
*/
deliveryKeyInPayload?: boolean;
}
export interface DestroyOptions {
/**
* Default: false
*
* Will only destroy the queue if it has no consumers
*/
ifUnused?: boolean;
/**
* Default: false
*
* Will ony be deleted if the queue has no messages
*/
ifEmpty?: boolean;
}
export type SubscribeCallback = (
message: any,
headers: { [key: string]: any },
deliveryInfo: DeliveryInfo,
ack: Ack
) => void;
export interface QueueCallback {
name: string;
consumerTagListeners: { [tag: string]: any };
consumerTagOptions: { [option: string]: any };
options: QueueOptions;
state: string;
channel: number;
}
export interface ExchangePublishOptions {
/**
* Default: false
*
* This flag tells the server how to react if the message cannot be routed to a queue.
*
* If this flag is set, the server will return an unroutable message with a Return method.
*
* If this flag is false, the server silently drops the message
*/
mandatory?: boolean;
/**
* Default: false
*
* This flag tells the server how to react if the message cannot be routed to a queue consumer immediately.
*
* If this flag is set, the server will return an undeliverable message with a Return method.
*
* If this flag is false, the server will queue the message, but with no guarantee that it will ever be consumed
*/
immediate?: boolean;
/**
* Default: 'application/octet-stream'
*/
contentType?: string;
/**
* Default: null
*/
contentEncoding?: string;
/**
* Default: {}
*
* Arbitrary application-specific message headers
*/
headers?: any;
/**
* 1: Non-persistent
* 2: Persistent
*/
deliveryMode?: 1 | 2;
priority?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
/**
* Application correlation identifier
*/
correlationId?: string;
/**
* Usually used to name a reply queue for a request message
*/
replyTo?: string;
/**
* Default: null
*
* Message expiration specification -- ISO date string?
*/
expiration?: string;
/**
* Default: null
*
* Application message identifier
*/
messageId?: string;
/**
* Default: null
*
* Message timestamp
*
* ISO date string?
*/
timestamp?: string;
/**
* Default: null
*
* Message type name
*/
type?: string;
/**
* Default: null
*
* Creating user id
*/
userId?: string;
/**
* Default: null
*
* Creating application id
*/
appId?: string;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"amqp-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"unified-signatures": [
"false"
]
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ export interface Channel extends events.EventEmitter {
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void;
cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | false) => void): void;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
+1 -1
View File
@@ -42,7 +42,7 @@ export interface Channel extends events.EventEmitter {
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise<Replies.Consume>;
cancel(consumerTag: string): Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): Promise<Message | boolean>;
get(queue: string, options?: Options.Get): Promise<Message | false>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
+4
View File
@@ -30,6 +30,10 @@ declare module 'angular' {
* Latency Threshold
*/
latencyThreshold?: number;
/**
* HTML element selector of parent
*/
parentSelector?: string;
}
}
+1
View File
@@ -214,6 +214,7 @@ declare module 'angular' {
contrastDefaultColor?: string;
contrastDarkColors?: string | string[];
contrastLightColors?: string | string[];
contrastStrongLightColors?: string|string[];
}
interface IThemeHues {
@@ -0,0 +1,21 @@
import * as angular from 'angular';
import * as angularTooltips from 'angular-tooltips';
angular
.module('test.angular-tooltips', [
angularTooltips
])
.config((tooltipsConfProvider: angularTooltips.TooltipsConfProvider) => {
tooltipsConfProvider.configure({
side: 'left',
showTrigger: 'click',
hideTrigger: 'click',
class: 'class',
smart: true,
closeButton: false,
size: 'small',
speed: 'slow',
tooltipTemplateUrlCache: true,
show: false
});
});
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for angular-tooltips 1.2
// Project: http://720kb.github.io/angular-tooltips
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare const AngularTooltips: '720kb.tooltips';
export = AngularTooltips;
declare namespace AngularTooltips {
interface TooltipsConfProvider {
configure(options: TooltipsConfProviderOptions): void;
}
interface TooltipsConfProviderOptions {
side?: 'left' | 'right' | 'top' | 'bottom' | 'top left' | 'top right' | 'bottom left' | 'bottom right';
showTrigger?: string;
hideTrigger?: string;
class?: string;
smart?: boolean;
closeButton?: boolean;
size?: 'small' | 'medium' | 'large';
speed?: 'slow' | 'medium' | 'fast';
tooltipTemplateUrlCache?: boolean;
show?: boolean;
}
}
+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",
"angular-tooltips-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+2 -2
View File
@@ -311,7 +311,7 @@ declare module 'angular' {
openClass?: string;
}
interface IModalProvider {
interface IModalProvider extends IServiceProvider {
/**
* Default options all modals will use.
*/
@@ -875,7 +875,7 @@ declare module 'angular' {
useContentExp?: boolean;
}
interface ITooltipProvider {
interface ITooltipProvider extends IServiceProvider {
/**
* Provide a set of defaults for certain tooltip and popover attributes.
*/
+1 -1
View File
@@ -591,7 +591,7 @@ namespace TestPromise {
assertPromiseType<TResult>(promise.catch((err) => anyOf2(tresult, reject)));
assertPromiseType<TResult>(promise.catch((err) => anyOf3(tresult, tresultPromise, reject)));
assertPromiseType<TResult>(promise.catch((err) => tresultPromise));
assertPromiseType<ng.IHttpPromiseCallbackArg<TResult>>(promise.catch((err) => tresultHttpPromise));
assertPromiseType<TResult | ng.IHttpPromiseCallbackArg<TResult>>(promise.catch((err) => tresultHttpPromise));
assertPromiseType<TResult | TOther>(promise.catch((err) => tother));
assertPromiseType<TResult | TOther>(promise.catch((err) => totherPromise));
assertPromiseType<TResult | ng.IHttpPromiseCallbackArg<TOther>>(promise.catch((err) => totherHttpPromise));
+74 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.6
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>, Caleb St-Denis <https://github.com/calebstdenis>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery" />
@@ -487,8 +487,8 @@ declare namespace angular {
$eval(expression: (scope: IScope) => any, locals?: Object): any;
$evalAsync(): void;
$evalAsync(expression: string): void;
$evalAsync(expression: (scope: IScope) => any): void;
$evalAsync(expression: string, locals?: Object): void;
$evalAsync(expression: (scope: IScope) => void, locals?: Object): void;
// Defaults to false by the implementation checking strategy
$new(isolate?: boolean, parent?: IScope): IScope;
@@ -1847,6 +1847,77 @@ declare namespace angular {
$postLink?(): void;
}
/**
* Interface for the $onInit lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnInit {
/**
* Called on each controller after all the controllers on an element have been constructed and had their bindings
* initialized (and before the pre & post linking functions for the directives on this element). This is a good
* place to put initialization code for your controller.
*/
$onInit(): void;
}
/**
* Interface for the $doCheck lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IDoCheck {
/**
* Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes.
* Any actions that you wish to take in response to the changes that you detect must be invoked from this hook;
* implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish
* to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's
* change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes,
* you must store the previous value(s) for comparison to the current values.
*/
$doCheck(): void;
}
/**
* Interface for the $onChanges lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnChanges {
/**
* Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as
* cloning the bound value to prevent accidental mutation of the outer value.
*/
$onChanges(onChangesObj: IOnChangesObject): void;
}
/**
* Interface for the $onDestroy lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IOnDestroy {
/**
* Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,
* watches and event handlers.
*/
$onDestroy(): void;
}
/**
* Interface for the $postLink lifecycle hook
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
*/
interface IPostLink {
/**
* Called after this controller's element and its children have been linked. Similar to the post-link function this
* hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain
* templateUrl directives will not have been compiled and linked since they are waiting for their template to load
* asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered
* analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather
* different in Angular 1 there is no direct mapping and care should be taken when upgrading.
*/
$postLink(): void;
}
interface IOnChangesObject {
[property: string]: IChangesObject<any>;
}
+1 -1
View File
@@ -17,4 +17,4 @@
"unified-signatures": false,
"void-return": false
}
}
}
@@ -15,6 +15,8 @@ class TestController {
storage.clearAll();
}
$onInit() {
}
}
var app = angular.module('angularLocalStorageTests', ['angularLocalStorage']);
@@ -44,7 +44,7 @@ appInsights = {
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; },
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; },
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; },
trackTrace(message: string, properties?: { [name: string]: string; }) { return null; },
trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; },
flush() { return null; },
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; },
clearAuthenticatedUserContext() { return null; },
@@ -77,6 +77,7 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null);
// trackTrace
appInsights.trackTrace("message");
appInsights.trackTrace("message", null);
appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error);
// trackDependency
appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null);
@@ -117,7 +118,18 @@ const envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(dat
context.track(envelope);
context.addTelemetryInitializer(telemetryEnvelope => false);
context.addTelemetryInitializer(envelope => false);
context.addTelemetryInitializer(envelope => { });
// a sample from: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#example
context.addTelemetryInitializer(envelope => {
let telemetryItem = envelope.data.baseData;
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) {
telemetryItem.url = "URL CENSORED";
}
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["globalProperty"] = "boo";
});
// track event
const eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
+4 -2
View File
@@ -572,6 +572,7 @@ declare module Microsoft.ApplicationInsights {
isPerfAnalyzerEnabled?: boolean;
url?: string;
isStorageUseDisabled?: boolean;
isBeaconApiDisabled?: boolean;
}
/**
@@ -611,6 +612,7 @@ declare module Microsoft.ApplicationInsights {
tags: {
[name: string]: any;
};
data: any;
}
interface ITelemetryContext {
@@ -650,7 +652,7 @@ declare module Microsoft.ApplicationInsights {
* Adds telemetry initializer to the collection. Telemetry initializers will be called one by one
* before telemetry item is pushed for sending and in the order they were added.
*/
addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any;
addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean | void): any;
/**
* Tracks telemetry object.
*/
@@ -763,7 +765,7 @@ declare module Microsoft.ApplicationInsights {
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
*/
trackTrace(message: string, properties?: { [name: string]: string }): any;
trackTrace(message: string, properties?: { [name: string]: string }, severityLevel?: AI.SeverityLevel): any;
/**
* Immediately send all queued telemetry.
*/
+20 -10
View File
@@ -1,26 +1,36 @@
import Archiver = require('archiver');
import FS = require('fs');
import * as Archiver from 'archiver';
import * as fs from 'fs';
const archiver = Archiver.create('zip');
const writeStream = FS.createWriteStream('./archiver.d.ts');
const readStream = FS.createReadStream('./archiver.d.ts');
const writeStream = fs.createWriteStream('./archiver.d.ts');
const readStream = fs.createReadStream('./archiver.d.ts');
archiver.abort();
archiver.pipe(writeStream);
archiver.append(readStream, { name: 'archiver.d.ts' });
archiver.append(readStream, {name: 'archiver.d.ts'})
.append(readStream, {name: 'archiver.d.ts'});
archiver.bulk({ mappaing: {} });
archiver.directory('./path', './someOtherPath');
archiver.directory('./path', { name: "testName"} );
archiver.directory('./path', { name: "testName" });
archiver.directory('./', "", {});
archiver.directory('./', {name: 'test'}, {});
archiver.directory('./', { name: 'test' }, {});
archiver.append(readStream, {
name: "sub/folder.xml"
});
archiver.glob("**", {
cwd: 'path/to/files',
});
archiver.glob('./path', {}, {});
archiver.file('./path', { name: 'test' });
archiver.glob('./path', {}, {});
archiver.finalize();
archiver.setFormat('zip');
archiver.setModule(() => {});
@@ -28,4 +38,4 @@ archiver.setModule(() => {});
archiver.pointer();
archiver.use(() => {});
archiver.pipe(writeStream);
archiver.finalize();
+29 -13
View File
@@ -1,51 +1,67 @@
// Type definitions for archiver 1.3
// Project: https://github.com/archiverjs/node-archiver
// Definitions by: Esri <https://github.com/archiverjs/node-archiver>
// Definitions by: Esri <https://github.com/archiverjs/node-archiver>, Dolan Miu <https://github.com/dolanmiu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/* =================== USAGE ===================
import Archiver = require('archiver);
var archiver = Archiver.create('zip');
archiver.pipe(FS.createWriteStream('xxx'));
archiver.append(FS.createReadStream('xxx'));
archiver.pipe(fs.createWriteStream('xxx'));
archiver.append(fs.createReadStream('xxx'));
archiver.finalize();
=============================================== */
/// <reference types="node" />
import * as FS from 'fs';
import * as STREAM from 'stream';
import * as fs from 'fs';
import * as stream from 'stream';
import * as express from 'express';
import * as glob from 'glob';
declare function archiver(format: string, options?: {}): archiver.Archiver;
declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver;
declare namespace archiver {
function create(format: string, options?: {}): Archiver;
type Format = 'zip' | 'tar';
function create(format: string, options?: ArchiverOptions): Archiver;
function registerFormat(format: string, module: Function): void;
interface nameInterface {
interface EntryData {
name?: string;
prefix?: string;
stats?: string;
}
interface Archiver extends STREAM.Transform {
interface Archiver extends stream.Transform {
abort(): this;
append(source: STREAM.Readable | Buffer | string, name: nameInterface): this;
append(source: stream.Readable | Buffer | string, name?: EntryData): this;
bulk(mappings: any): this;
directory(dirpath: string, destpath: nameInterface | string, data?: any | Function): this;
directory(dirpath: string, options: EntryData | string, data?: EntryData): this;
file(filepath: string, data: any): this;
glob(pattern: string, options: {}, data: any): this;
file(filename: string, data: EntryData): this;
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): this;
pipe(stream: fs.WriteStream | express.Response): void;
setFormat(format: string): this;
setModule(module: Function): this;
pointer(): number;
use(plugin: Function): this;
}
interface ArchiverOptions {
store?: boolean;
gzip?: boolean;
gzipOptions?: {
level: number,
};
}
}
export = archiver;
@@ -0,0 +1,25 @@
import { Tracker, TrackerStream, TrackerGroup } from "are-we-there-yet";
let simple = new Tracker("simple");
simple.addListener("change", (name, completed, tracker) => {
console.log(`name: ${name}, completed: ${completed}`);
});
simple.addWork(10);
simple.completeWork(1);
console.log(simple.completed() < 1);
let group = new TrackerGroup("group");
group.addUnit(simple);
let subgroup = group.newGroup("subgroup");
console.log(group.completed());
let stream = new TrackerStream("stream", 100, { encoding: "utf8" });
subgroup.addUnit(stream);
stream.addListener("change", (name, completed, tracker) => {
console.log(`name: ${name}, completed: ${completed}`);
});
simple.finish();
console.log(group.debug());
+90
View File
@@ -0,0 +1,90 @@
// Type definitions for are-we-there-yet 1.1
// Project: https://github.com/iarna/are-we-there-yet
// Definitions by: Brian J Brennan <https://github.com/brianloveswords>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { EventEmitter } from "events";
import { Transform, TransformOptions } from "stream";
export type TrackerObject = Tracker | TrackerGroup | TrackerStream;
export type TrackerEventListener = (name: string, completed: number, tracker: TrackerObject) => void;
export type GenericEventListener = (...args: any[]) => void;
export class TrackerBase extends EventEmitter {
constructor(name?: string);
addListener(event: "change", listener: TrackerEventListener): this;
addListener(event: string, listener: GenericEventListener): this;
on(event: "change", listener: TrackerEventListener): this;
on(event: string, listener: GenericEventListener): this;
once(event: "change", listener: TrackerEventListener): this;
once(event: string, listener: GenericEventListener): this;
prependListener(event: "change", listener: TrackerEventListener): this;
prependListener(event: string, listener: GenericEventListener): this;
prependOnceListener(event: "change", listener: TrackerEventListener): this;
prependOnceListener(event: string, listener: GenericEventListener): this;
removeListener(event: "change", listener: TrackerEventListener): this;
removeListener(event: string, listener: GenericEventListener): this;
}
export class Tracker extends TrackerBase {
constructor(name?: string, todo?: number);
addWork(work: number): void;
completeWork(completed: number): void;
completed(): number;
finish(): void;
}
export class TrackerGroup extends TrackerBase {
constructor(name?: string);
addUnit(tracker: TrackerBase, weight?: number): TrackerObject;
completed(): number;
debug(): string;
finish(): void;
newGroup(name?: string, weight?: number): TrackerGroup;
newItem(name?: string, todo?: number, weight?: number): Tracker;
newStream(name?: string, todo?: number, weight?: number): TrackerStream;
}
export class TrackerStream extends Transform {
constructor(name?: string, size?: number, options?: TransformOptions);
addWork(work: number): void;
completed(): number;
addListener(event: "change", listener: TrackerEventListener): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListener(event: "readable" | "end" | "close", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: string, listener: GenericEventListener): this;
on(event: "change", listener: TrackerEventListener): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "readable" | "end" | "close", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: string, listener: GenericEventListener): this;
once(event: "change", listener: TrackerEventListener): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "readable" | "end" | "close", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: string, listener: GenericEventListener): this;
prependListener(event: "change", listener: TrackerEventListener): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "readable" | "end" | "close", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: string, listener: GenericEventListener): this;
prependOnceListener(event: "change", listener: TrackerEventListener): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "readable" | "end" | "close", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: string, listener: GenericEventListener): this;
removeListener(event: "change", listener: TrackerEventListener): this;
removeListener(event: "data", listener: (chunk: Buffer | string) => void): this;
removeListener(event: "readable" | "end" | "close", listener: () => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: string, listener: GenericEventListener): this;
}
@@ -17,6 +17,6 @@
},
"files": [
"index.d.ts",
"redux-devtools-extension-tests.ts"
"are-we-there-yet-tests.ts"
]
}
+76 -9
View File
@@ -12,7 +12,64 @@ webAuth.authorize({
redirectUri: 'https://example.com/auth/callback'
});
webAuth.parseHash(window.location.hash, (err, authResult) => {
webAuth.parseHash((err, authResult) => {
if (err) {
return console.log(err);
}
// The contents of authResult depend on which authentication parameters were used.
// It can include the following:
// authResult.accessToken - access token for the API specified by `audience`
// authResult.expiresIn - string with the access token's expiration time in seconds
// authResult.idToken - ID token JWT containing user profile information
webAuth.client.userInfo(authResult.accessToken, (err, user) => {
// Now you have the user's information
});
});
webAuth.parseHash((err, authResult) => {
if (err) {
return console.log(err);
}
// The contents of authResult depend on which authentication parameters were used.
// It can include the following:
// authResult.accessToken - access token for the API specified by `audience`
// authResult.expiresIn - string with the access token's expiration time in seconds
// authResult.idToken - ID token JWT containing user profile information
webAuth.client.userInfo(authResult.accessToken, (err, user) => {
// Now you have the user's information
});
});
webAuth.parseHash(
{
nonce: 'asfd',
hash: '#access_token=VjubIMBmpgQ2W2&id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlF6RTROMFpCTTBWRFF6RTJSVVUwTnpJMVF6WTFNelE0UVRrMU16QXdNRUk0UkRneE56RTRSZyJ9.eyJpc3MiOiJodHRwczovL3dwdGVzdC5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NTVkNDhjNTdkNWIwYWQwMjIzYzQwOGQ3IiwiYXVkIjoiZ1lTTmxVNFlDNFYxWVBkcXE4elBRY3VwNnJKdzFNYnQiLCJleHAiOjE0ODI5NjkwMzEsImlhdCI6MTQ4MjkzMzAzMSwibm9uY2UiOiJhc2ZkIn0.PPoh-pITcZ8qbF5l5rMZwXiwk5efbESuqZ0IfMUcamB6jdgLwTxq-HpOT_x5q6-sO1PBHchpSo1WHeDYMlRrOFd9bh741sUuBuXdPQZ3Zb0i2sNOAC2RFB1E11mZn7uNvVPGdPTg-Y5xppz30GSXoOJLbeBszfrVDCmPhpHKGGMPL1N6HV-3EEF77L34YNAi2JQ-b70nFK_dnYmmv0cYTGUxtGTHkl64UEDLi3u7bV-kbGky3iOOCzXKzDDY6BBKpCRTc2KlbrkO2A2PuDn27WVv1QCNEFHvJN7HxiDDzXOsaUmjrQ3sfrHhzD7S9BcCRkekRfD9g95SKD5J0Fj8NA&token_type=Bearer&state=theState&refresh_token=kajshdgfkasdjhgfas&scope=foo'
},
(err, authResult) => {
if (err) {
return console.log(err);
}
// The contents of authResult depend on which authentication parameters were used.
// It can include the following:
// authResult.accessToken - access token for the API specified by `audience`
// authResult.expiresIn - string with the access token's expiration time in seconds
// authResult.idToken - ID token JWT containing user profile information
webAuth.client.userInfo(authResult.accessToken, (err, user) => {
// Now you have the user's information
});
});
webAuth.parseHash(
{
nonce: 'asfd'
},
(err, authResult) => {
if (err) {
return console.log(err);
}
@@ -29,14 +86,21 @@ webAuth.parseHash(window.location.hash, (err, authResult) => {
});
webAuth.renewAuth({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback',
}, function (err, authResult) {
// Renewed tokens or error
});
// this will use postMessage to comunicate between the silent callback
// and the SPA. When false the SDK will attempt to parse the url hash
// should ignore the url hash and no extra behaviour is needed.
usePostMessage: true
webAuth.renewAuth({
nonce: '123',
state: '456'
}, function (err, authResult) {
// Renewed tokens or error
});
webAuth.renewAuth({
nonce: '123',
state: '456',
postMessageDataType: 'auth0:silent-authentication'
}, function (err, authResult) {
// Renewed tokens or error
});
@@ -90,6 +154,9 @@ webAuth.popup.signupAndLogin({}, (err, data) => {
// do something with data
});
webAuth.login({username: 'bar', password: 'foo'}, (err, data) => {});
webAuth.crossOriginAuthenticationCallback();
let authentication = new auth0.Authentication({
domain: 'me.auth0.com',
@@ -150,7 +217,7 @@ authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password
authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {});
authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {});
authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {});
authentication.passwordless.verify({ connection: 'bla', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {});
authentication.loginWithResourceOwner({
username: 'the username',
+234 -91
View File
@@ -1,4 +1,4 @@
// Type definitions for Auth0.js 8.3
// Type definitions for Auth0.js 8.6
// Project: https://github.com/auth0/auth0.js
// Definitions by: Adrian Chia <https://github.com/adrianchia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -15,7 +15,6 @@ export class Authentication {
/**
* Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction
*
* @method buildAuthorizeUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
buildAuthorizeUrl(options: any): string;
@@ -23,34 +22,32 @@ export class Authentication {
/**
* Builds and returns the Logout url in order to initialize a new authN/authZ transaction
*
* @method buildLogoutUrl
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
*/
buildLogoutUrl(options?: any): string;
buildLogoutUrl(options?: LogoutOptions): string;
/**
* Makes a call to the `oauth/token` endpoint with `password` grant type
*
* @method loginWithDefaultDirectory
* @param {Object} options: https://auth0.com/docs/api-auth/grant/password
* @param {DefaultDirectoryLoginOptions} options: https://auth0.com/docs/api-auth/grant/password
* @param {Function} callback
*/
loginWithDefaultDirectory(options: any, callback: Auth0Callback<any>): void;
loginWithDefaultDirectory(options: DefaultDirectoryLoginOptions, callback: Auth0Callback<any>): void;
/**
* Makes a call to the `/ro` endpoint
* @param {any} options
* @param {ResourceOwnerLoginOptions} options
* @param {Function} callback
* @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead.
*/
loginWithResourceOwner(options: any, callback: Auth0Callback<any>): void;
loginWithResourceOwner(options: ResourceOwnerLoginOptions, callback: Auth0Callback<any>): void;
/**
* Makes a call to the `oauth/token` endpoint with `password-realm` grant type
* @param {any} options
* @param {DefaultLoginOptions} options
* @param {Function} callback
*/
login(options: any, callback: Auth0Callback<any>): void;
login(options: DefaultLoginOptions, callback: Auth0Callback<any>): void;
/**
* Makes a call to the `oauth/token` endpoint
@@ -62,7 +59,6 @@ export class Authentication {
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Function} callback
*/
getSSOData(callback?: Auth0Callback<any>): void;
@@ -70,7 +66,6 @@ export class Authentication {
/**
* Makes a call to the `/ssodata` endpoint
*
* @method getSSOData
* @param {Boolean} withActiveDirectories
* @param {Function} callback
*/
@@ -79,25 +74,22 @@ export class Authentication {
/**
* Makes a call to the `/userinfo` endpoint and returns the user profile
*
* @method userInfo
* @param {String} accessToken
* @param {Function} callback
*/
userInfo(token: string, callback: Auth0Callback<Auth0UserProfile>): void;
userInfo(accessToken: string, callback: Auth0Callback<Auth0UserProfile>): void;
/**
* Makes a call to the `/delegation` endpoint
*
* @method delegation
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation
* @param {DelegationOptions} options: https://auth0.com/docs/api/authentication#!#post--delegation
* @param {Function} callback
*/
delegation(options: any, callback: Auth0Callback<Auth0DelegationToken>): any;
delegation(options: DelegationOptions, callback: Auth0Callback<Auth0DelegationToken>): any;
/**
* Fetches the user country based on the ip.
*
* @method getUserCountry
* @param {Function} callback
*/
getUserCountry(callback: Auth0Callback<{ countryCode: string }>): void;
@@ -109,16 +101,14 @@ export class PasswordlessAuthentication {
/**
* Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction
*
* @method buildVerifyUrl
* @param {Object} options
* @param {PasswordlessVerifyOptions} options
* @param {Function} callback
*/
buildVerifyUrl(options: any): string;
buildVerifyUrl(options: PasswordlessVerifyOptions): string;
/**
* Initializes a new passwordless authN/authZ transaction
*
* @method start
* @param {Object} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Function} callback
*/
@@ -127,11 +117,10 @@ export class PasswordlessAuthentication {
/**
* Verifies the passwordless TOTP and returns an error if any.
*
* @method buildVerifyUrl
* @param {Object} options
* @param {PasswordlessVerifyOptions} options
* @param {Function} callback
*/
verify(options: any, callback: Auth0Callback<any>): void;
verify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
}
export class DBConnection {
@@ -140,17 +129,15 @@ export class DBConnection {
/**
* Signup a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {DbSignUpOptions} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} calback
*/
signup(options: any, callback: Auth0Callback<any>): void;
signup(options: DbSignUpOptions, callback: Auth0Callback<any>): void;
/**
* Initializes the change password flow
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {ChangePasswordOptions} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: ChangePasswordOptions, callback: Auth0Callback<any>): void;
@@ -162,7 +149,6 @@ export class Management {
/**
* Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id
*
* @method getUser
* @param {String} userId
* @param {Function} callback
*/
@@ -172,7 +158,6 @@ export class Management {
* Updates the user metdata. It will patch the user metdata with the attributes sent.
* https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
*
* @method patchUserMetadata
* @param {String} userId
* @param {Object} userMetadata
* @param {Function} callback
@@ -182,7 +167,6 @@ export class Management {
/**
* Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities
*
* @method linkUser
* @param {String} userId
* @param {String} secondaryUserToken
* @param {Function} callback
@@ -195,14 +179,14 @@ export class WebAuth {
client: Authentication;
popup: Popup;
redirect: Redirect;
crossOriginAuthentication: CrossOriginAuthentication;
/**
* Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
* @param {AuthorizeOptions} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
*/
authorize(options: any): void;
authorize(options: AuthorizeOptions): void;
/**
* Parse the url hash and extract the returned tokens depending on the transaction.
@@ -211,82 +195,99 @@ export class WebAuth {
* by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be
* accepted.
*
* @method parseHash
* @param {Object} options:
* @param {String} options._idTokenVerification [OPTIONAL] Default: true
* @param {String} options.state [OPTIONAL] to verify the response
* @param {String} options.nonce [OPTIONAL] to verify the id_token
* @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash
* @param {ParseHashOptions} options
* @param {Function} callback: any(err, token_payload)
*/
parseHash(options: any, callback: Auth0Callback<Auth0DecodedHash>): void;
parseHash(callback: Auth0Callback<Auth0DecodedHash>): void;
/**
* Parse the url hash and extract the returned tokens depending on the transaction.
*
* Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed
* by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be
* accepted.
*
* @param {ParseHashOptions} options
* @param {Function} callback: any(err, token_payload)
*/
parseHash(options: ParseHashOptions, callback: Auth0Callback<Auth0DecodedHash>): void;
/**
* Decodes the id_token and verifies the nonce.
*
* @method validateToken
* @param {String} token
* @param {String} state
* @param {String} nonce
* @param {Function} callback: function(err, {payload, transaction})
*/
validateToken(token: string, state: string, nonce: string, callback: Auth0Callback<any>): void;
validateToken(token: string, nonce: string, callback: Auth0Callback<any>): void;
/**
* Executes a silent authentication transaction under the hood in order to fetch a new token.
* Executes a silent authentication transaction under the hood in order to fetch a new tokens for the current session.
* This method requires that all Auth is performed with {@link authorize}
* Watch out! If you're not using the hosted login page to do social logins, you have to use your own [social connection keys](https://manage.auth0.com/#/connections/social). If you use Auth0's dev keys, you'll always get `login_required` as an error when calling this method.
*
* @method renewAuth
* @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint
* @param {RenewAuthOptions} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint
* @param {Function} callback
*/
renewAuth(options: any, callback: Auth0Callback<any>): void;
renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;
/**
* Initialices a change password transaction
*
* @method changePassword
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {ChangePasswordOptions} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password
* @param {Function} callback
*/
changePassword(options: any, callback: Auth0Callback<any>): void;
changePassword(options: ChangePasswordOptions, callback: Auth0Callback<any>): void;
/**
* Signs up a new user
*
* @method signup
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {DbSignUpOptions} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signup(options: any, callback: Auth0Callback<any>): void;
signup(options: DbSignUpOptions, callback: Auth0Callback<any>): void;
/**
* Signs up a new user, automatically logs the user in after the signup and returns the user token.
* The login will be done using /oauth/token with password-realm grant type.
*
* @method signupAndAuthorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {DbSignUpOptions} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
*/
signupAndAuthorize(options: any, callback: Auth0Callback<any>): void;
signupAndAuthorize(options: DbSignUpOptions, callback: Auth0Callback<any>): void;
/**
* Redirects to the auth0 logout page
* Logs in the user with username and password using the cross origin authentication (/co/authenticate) flow. You can use either `username` or `email` to identify the user, but `username` will take precedence over `email`.
* This only works when 3rd party cookies are enabled in the browser. After the /co/authenticate call, you'll have to use the {@link parseHash} function at the `redirectUri` specified in the constructor.
*
* @method logout
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout
* @param {CrossOriginLoginOptions} options options used in the {@link authorize} call after the login_ticket is acquired
* @param {crossOriginLoginCallback} cb Callback function called only when an authentication error, like invalid username or password, occurs. For other types of errors, there will be a redirect to the `redirectUri`.
*/
logout(options: any): void;
login(options: CrossOriginLoginOptions, callback: Auth0Callback<any>): void;
/**
* Runs the callback code for the cross origin authentication call. This method is meant to be called by the cross origin authentication callback url.
*
*/
crossOriginAuthenticationCallback(): void;
/**
* Redirects to the auth0 logout endpoint
*
* If you want to navigate the user to a specific URL after the logout, set that URL at the returnTo parameter. The URL should be included in any the appropriate Allowed Logout URLs list:
*
* - If the client_id parameter is included, the returnTo URL must be listed in the Allowed Logout URLs set at the client level (see Setting Allowed Logout URLs at the App Level).
* - If the client_id parameter is NOT included, the returnTo URL must be listed in the Allowed Logout URLs set at the account level (see Setting Allowed Logout URLs at the Account Level).
*
* @param {LogoutOptions} options
* @see {@link https://auth0.com/docs/api/authentication#logout}
*/
logout(options: LogoutOptions): void;
/**
* Initialices a passwordless authentication transaction
*
* @method passwordlessStart
* @param {Object} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Object} options.send: `link` or `code`
* @param {Object} options.phoneNumber: send should be code and email not set
* @param {Object} options.email: phoneNumber should be ignored
* @param {Object} options.connection
* @param {Object} options.authParams
* @param {PasswordlessStartOptions} options: https://auth0.com/docs/api/authentication#passwordless
* @param {Function} callback
*/
passwordlessStart(options: PasswordlessStartOptions, callback: Auth0Callback<any>): void;
@@ -295,27 +296,28 @@ export class WebAuth {
* Verifies the passwordless TOTP and redirects to finish the passwordless transaction
*
* @method passwordlessVerify
* @param {Object} options:
* @param {Object} options.type: `sms` or `email`
* @param {Object} options.phoneNumber: only if type = sms
* @param {Object} options.email: only if type = email
* @param {Object} options.connection: the connection name
* @param {Object} options.verificationCode: the TOTP code
* @param {PasswordlessVerifyOptions} options:
* @param {Function} callback
*/
passwordlessVerify(options: any, callback: Auth0Callback<any>): void;
passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
}
export class Redirect {
constructor(client: any, options: any);
/**
* Initializes the legacy Lock login flow in a popup
* Performs authentication with username/email and password with a database connection
*
* This method is not compatible with API Auth so if you need to fetch API tokens with audience
* you should use {@link authorize} or {@link login}.
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
* @param {String} [options.redirectUri] url that the Auth0 will redirect after Auth with the Authorization Response
* @param {String} [options.responseType] type of the response used. It can be any of the values `code` and `token`
* @param {String} [options.responseMode] how the AuthN response is encoded and redirected back to the client. Supported values are `query` and `fragment`
* @param {String} [options.scope] scopes to be requested during AuthN. e.g. `openid email`
* @param {credentialsCallback} cb
*/
loginWithCredentials(options: any, callback: Auth0Callback<any>): void;
@@ -323,8 +325,11 @@ export class Redirect {
* Signs up a new user and automatically logs the user in after the signup.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
* @param {Object} options
* @param {String} options.email user email address
* @param {String} options.password user password
* @param {String} options.connection name of the connection where the user will be created
* @param {credentialsCallback} cb
*/
signupAndLogin(options: any, callback: Auth0Callback<any>): void;
}
@@ -348,21 +353,51 @@ export class Popup {
preload(options: any): any;
/**
* Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction
* Handles the popup logic for the callback page.
*
* @method callback
* @param {Object} options
* @param {String} options.hash the url hash. If not provided it will extract from window.location.hash
* @param {String} [options.state] value originally sent in `state` parameter to {@link authorize} to mitigate XSRF
* @param {String} [options.nonce] value originally sent in `nonce` parameter to {@link authorize} to prevent replay attacks
* @param {String} [options._idTokenVerification] makes parseHash perform or skip `id_token` verification. We **strongly** recommend validating the `id_token` yourself if you disable the verification.
* @see {@link parseHash}
*/
callback(options: any): void;
/**
* Shows inside a new window the hosted login page (`/authorize`) in order to start a new authN/authZ transaction and post its result using `postMessage`.
*
* @method authorize
* @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db
* @param {Function} callback
* @param {Object} options
* @param {String} [options.domain] your Auth0 domain
* @param {String} [options.clientID] your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard
* @param {String} options.redirectUri url that the Auth0 will redirect after Auth with the Authorization Response
* @param {String} options.responseType type of the response used by OAuth 2.0 flow. It can be any space separated list of the values `code`, `token`, `id_token`. {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0}
* @param {String} [options.responseMode] how the Auth response is encoded and redirected back to the client. Supported values are `query`, `fragment` and `form_post`. {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes}
* @param {String} [options.state] value used to mitigate XSRF attacks. {@link https://auth0.com/docs/protocols/oauth2/oauth-state}
* @param {String} [options.nonce] value used to mitigate replay attacks when using Implicit Grant. {@link https://auth0.com/docs/api-auth/tutorials/nonce}
* @param {String} [options.scope] scopes to be requested during Auth. e.g. `openid email`
* @param {String} [options.audience] identifier of the resource server who will consume the access token issued after Auth
* @param {Boolean} [options.owp] determines if Auth0 should render the relay page or not and the caller is responsible of handling the response.
* @param {authorizeCallback} cb
* @see {@link https://auth0.com/docs/api/authentication#authorize-client}
*/
authorize(options: any, callback: Auth0Callback<any>): void;
/**
* Initializes the legacy Lock login flow in a popup
* Performs authentication with username/email and password with a database connection inside a new window
*
* This method is not compatible with API Auth so if you need to fetch API tokens with audience
* you should use {@link authorize} or {@link login}.
*
* @method loginWithCredentials
* @param {Object} options
* @param {Function} callback
* @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead.
* @param {String} [options.redirectUri] url that the Auth0 will redirect after Auth with the Authorization Response
* @param {String} [options.responseType] type of the response used. It can be any of the values `code` and `token`
* @param {String} [options.responseMode] how the AuthN response is encoded and redirected back to the client. Supported values are `query` and `fragment`
* @param {String} [options.scope] scopes to be requested during AuthN. e.g. `openid email`
* @param {credentialsCallback} cb
*/
loginWithCredentials(options: any, callback: Auth0Callback<any>): void;
@@ -383,13 +418,38 @@ export class Popup {
/**
* Signs up a new user and automatically logs the user in after the signup.
*
* This method is not compatible with API Auth so if you need to fetch API tokens with audience
* you should use {@link authorize} or {@link signupAndAuthorize}.
*
* @method signupAndLogin
* @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup
* @param {Function} callback
* @param {Object} options
* @param {String} options.email user email address
* @param {String} options.password user password
* @param {String} options.connection name of the connection where the user will be created
* @param {credentialsCallback} cb
*/
signupAndLogin(options: any, callback: Auth0Callback<any>): void;
}
export class CrossOriginAuthentication {
constructor(webAuth: any, options: any);
/**
* Logs in the user with username and password using the cross origin authentication (/co/authenticate) flow. You can use either `username` or `email` to identify the user, but `username` will take precedence over `email`.
* This only works when 3rd party cookies are enabled in the browser. After the /co/authenticate call, you'll have to use the {@link parseHash} function at the `redirectUri` specified in the constructor.
*
* @param {CrossOriginLoginOptions} options options used in the {@link authorize} call after the login_ticket is acquired
* @param {crossOriginLoginCallback} cb Callback function called only when an authentication error, like invalid username or password, occurs. For other types of errors, there will be a redirect to the `redirectUri`.
*/
login(options: CrossOriginLoginOptions, callback: Auth0Callback<any>): void;
/**
* Runs the callback code for the cross origin authentication call. This method is meant to be called by the cross origin authentication callback url.
*
*/
callback(): void;
}
type Auth0Callback<T> = (error: null | Auth0Error, result: T) => void;
interface ManagementOptions {
@@ -472,6 +532,7 @@ interface PasswordlessVerifyOptions {
verificationCode: string;
phoneNumber?: string;
email?: string;
send?: string;
}
interface Auth0UserProfile {
@@ -514,3 +575,85 @@ interface Auth0Identity {
provider: string;
user_id: string;
}
interface LoginOptions {
username: string;
password: string;
scope?: string;
}
interface DefaultLoginOptions extends LoginOptions {
audience?: string;
realm: string;
}
interface DefaultDirectoryLoginOptions extends LoginOptions {
audience?: string;
}
interface ResourceOwnerLoginOptions extends LoginOptions {
connection: string;
device?: string;
}
interface CrossOriginLoginOptions {
username?: string;
email?: string;
password: string;
realm?: string;
}
interface LogoutOptions {
clientID?: string;
returnTo?: string;
federated?: boolean;
}
interface DelegationOptions {
client_id?: string;
grant_type: string;
id_token?: string;
refresh_token?: string;
target?: string;
scope?: string;
api_type?: string;
}
interface DbSignUpOptions {
email: string;
password: string;
connection: string;
scope?: string;
}
interface ParseHashOptions {
hash?: string;
state?: string;
nonce?: string;
_idTokenVerification?: boolean;
}
interface RenewAuthOptions {
domain?: string;
clientID?: string;
redirectUri?: string;
responseType?: string;
responseMode?: string;
state?: string;
nonce?: string;
scope?: string;
audience?: string;
postMessageDataType?: string;
}
interface AuthorizeOptions {
domain?: string;
clientID?: string;
redirectUri: string;
responseType: string;
responseMode?: string;
state?: string;
nonce?: string;
scope?: string;
audience?: string;
}
+35 -2
View File
@@ -61,11 +61,22 @@ lock.on("authenticated", function(authResult : any) {
});
});
// test theme
var themeOptions : Auth0LockConstructorOptions = {
theme: {
authButtons: {
fooProvider: {
displayName: 'foo'
},
barProvider: {
displayName: 'foo',
primaryColor: '#FF0000',
foregroundColor: '#00FF00',
icon: 'http://baz.com/icon.png'
}
},
labeledSubmitButton: false,
logo: "https://example.com/assets/logo.png",
primaryColor: "green"
}
@@ -73,6 +84,14 @@ var themeOptions : Auth0LockConstructorOptions = {
new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions);
// test empty theme
var themeOptionsEmpty : Auth0LockConstructorOptions = {
theme: { }
};
new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions);
// test authentication
var authOptions : Auth0LockConstructorOptions = {
@@ -170,7 +189,7 @@ var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = {
cb(null, prefill);
}
}]
}
};
new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks);
@@ -198,3 +217,17 @@ var avatarOptions : Auth0LockConstructorOptions = {
};
new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions);
var authResult : AuthResult = {
accessToken: 'fake_access_token',
idToken: 'fake_id_token',
idTokenPayload: {
aud: "EaQzyHt1Dy57l-r5iHcMeT-lh1fFZntg",
exp: 1494393724,
iat: 1494357724,
iss: "https://www.foo.com",
sub: "auth0|aksjfkladsf"
},
refreshToken: undefined,
state: "923jf092j3.FFSDJFDSKLDF"
};
+30 -3
View File
@@ -1,6 +1,7 @@
// Type definitions for auth0-lock 10.10
// Type definitions for auth0-lock 10.16
// Project: http://auth0.com
// Definitions by: Brian Caruso <https://github.com/carusology>
// Dan Caddigan <https://github.com/goldcaddy77>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js" />
@@ -40,7 +41,19 @@ interface Auth0LockAvatarOptions {
displayName: (email: string, callback: Auth0LockAvatarDisplayNameCallback) => void;
}
interface Auth0LockThemeButton {
displayName: string;
primaryColor?: string;
foregroundColor?: string;
icon?: string;
}
interface Auth0LockThemeButtonOptions {
[provider: string]: Auth0LockThemeButton;
}
interface Auth0LockThemeOptions {
authButtons?: Auth0LockThemeButtonOptions;
labeledSubmitButton?: boolean;
logo?: string;
primaryColor?: string;
}
@@ -121,6 +134,20 @@ interface Auth0LockShowOptions {
rememberLastLogin?: boolean;
}
interface AuthResult {
accessToken: string;
idToken: string;
idTokenPayload: {
aud: string;
exp: number;
iat: number;
iss: string;
sub: string;
};
refreshToken?: string;
state: string;
}
interface Auth0LockStatic {
new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic;
@@ -128,14 +155,14 @@ interface Auth0LockStatic {
getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
// https://github.com/auth0/lock#resumeauthhash-callback
resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: any) => void): void;
resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void;
show(options?: Auth0LockShowOptions): void;
hide(): void;
logout(query: any): void;
on(event: "show" | "hide", callback: () => void): void;
on(event: "unrecoverable_error" | "authorization_error", callback: (error: auth0.Auth0Error) => void): void;
on(event: "authenticated", callback: (authResult: any) => void): void;
on(event: "authenticated", callback: (authResult: AuthResult) => void): void;
on(event: string, callback: (...args: any[]) => void): void;
}
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "dtslint/dt.json",
"rules": {
"only-arrow-functions": false,
"no-misused-new": false,
"no-single-declare-module": false,
"prefer-method-signature": false,
"object-literal-shorthand": false,
"typedef-whitespace": false,
"no-var": false
}
}
+8 -2
View File
@@ -1,6 +1,6 @@
// Type definitions for AutobahnJS v0.9.7
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl/>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>
// Definitions by: Elad Zelingher <https://github.com/darkl/>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
@@ -167,8 +167,14 @@ declare namespace autobahn {
interface IPublishOptions {
acknowledge?: boolean;
exclude?: number[];
exclude_authid?: string[];
exclude_authrole?: string[];
eligible?: number[];
disclose_me?: Boolean;
eligible_authid?: string[];
eligible_authrole?: string[];
retain?: boolean;
disclose_me?: boolean;
exclude_me?: boolean;
}
interface ISubscribeOptions {
+50 -1
View File
@@ -60,7 +60,7 @@ var S3CreateEvent: AWSLambda.S3CreateEvent = {
}
]
};
var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent;
/* API Gateway Event */
str = apiGwEvt.body;
@@ -164,6 +164,55 @@ authResponse = {
policyDocument: policyDocument
};
// CognitoUserPoolEvent
num = cognitoUserPoolEvent.version;
cognitoUserPoolEvent.triggerSource === "PreSignUp_SignUp";
cognitoUserPoolEvent.triggerSource === "PostConfirmation_ConfirmSignUp";
cognitoUserPoolEvent.triggerSource === "PreAuthentication_Authentication";
cognitoUserPoolEvent.triggerSource === "PostAuthentication_Authentication";
cognitoUserPoolEvent.triggerSource === "CustomMessage_SignUp";
cognitoUserPoolEvent.triggerSource === "CustomMessage_AdminCreateUser";
cognitoUserPoolEvent.triggerSource === "CustomMessage_ResendCode";
cognitoUserPoolEvent.triggerSource === "CustomMessage_ForgotPassword";
cognitoUserPoolEvent.triggerSource === "CustomMessage_UpdateUserAttribute";
cognitoUserPoolEvent.triggerSource === "CustomMessage_VerifyUserAttribute";
cognitoUserPoolEvent.triggerSource === "CustomMessage_Authentication";
cognitoUserPoolEvent.triggerSource === "DefineAuthChallenge_Authentication";
cognitoUserPoolEvent.triggerSource === "CreateAuthChallenge_Authentication";
cognitoUserPoolEvent.triggerSource === "VerifyAuthChallengeResponse_Authentication";
str = cognitoUserPoolEvent.region;
str = cognitoUserPoolEvent.userPoolId;
str = cognitoUserPoolEvent.userName;
str = cognitoUserPoolEvent.callerContext.awsSdkVersion;
str = cognitoUserPoolEvent.callerContext.clientId;
str = cognitoUserPoolEvent.request.userAttributes["email"];
str = cognitoUserPoolEvent.request.validationData["k1"];
str = cognitoUserPoolEvent.request.codeParameter;
str = cognitoUserPoolEvent.request.usernameParameter;
b = cognitoUserPoolEvent.request.newDeviceUsed;
cognitoUserPoolEvent.request.session[0].challengeName === "CUSTOM_CHALLENGE";
cognitoUserPoolEvent.request.session[0].challengeName === "PASSWORD_VERIFIER";
cognitoUserPoolEvent.request.session[0].challengeName === "SMS_MFA";
cognitoUserPoolEvent.request.session[0].challengeName === "DEVICE_SRP_AUTH";
cognitoUserPoolEvent.request.session[0].challengeName === "DEVICE_PASSWORD_VERIFIER";
cognitoUserPoolEvent.request.session[0].challengeName === "ADMIN_NO_SRP_AUTH";
b = cognitoUserPoolEvent.request.session[0].challengeResult;
str = cognitoUserPoolEvent.request.session[0].challengeMetaData;
str = cognitoUserPoolEvent.request.challengeName;
str = cognitoUserPoolEvent.request.privateChallengeParameters["answer"];
str = cognitoUserPoolEvent.request.challengeAnswer["answer"];
b = cognitoUserPoolEvent.response.answerCorrect;
str = cognitoUserPoolEvent.response.smsMessage;
str = cognitoUserPoolEvent.response.emailMessage;
str = cognitoUserPoolEvent.response.emailSubject;
str = cognitoUserPoolEvent.response.challengeName;
b = cognitoUserPoolEvent.response.issueTokens;
b = cognitoUserPoolEvent.response.failAuthentication;
str = cognitoUserPoolEvent.response.publicChallengeParameters["captchaUrl"];
str = cognitoUserPoolEvent.response.privateChallengeParameters["answer"];
str = cognitoUserPoolEvent.response.challengeMetaData;
b = cognitoUserPoolEvent.response.answerCorrect;
/* Context */
b = context.callbackWaitsForEmptyEventLoop;
str = context.functionName;
+45 -1
View File
@@ -1,6 +1,6 @@
// 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>, Rich Buggy <https://github.com/buggy>, Simon Ramsay <https://github.com/nexus-uw>
// 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>, Simon Ramsay <https://github.com/nexus-uw>, Yoriki Yamaguchi <https://github.com/y13i>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// API Gateway "event"
@@ -124,6 +124,50 @@ interface S3CreateEvent {
];
}
/**
* Cognito User Pool event
* http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
*/
interface CognitoUserPoolEvent {
version: number;
triggerSource: "PreSignUp_SignUp" | "PostConfirmation_ConfirmSignUp" | "PreAuthentication_Authentication" | "PostAuthentication_Authentication" | "CustomMessage_SignUp" | "CustomMessage_AdminCreateUser" | "CustomMessage_ResendCode" | "CustomMessage_ForgotPassword" | "CustomMessage_UpdateUserAttribute" | "CustomMessage_VerifyUserAttribute" | "CustomMessage_Authentication" | "DefineAuthChallenge_Authentication" | "CreateAuthChallenge_Authentication" | "VerifyAuthChallengeResponse_Authentication";
region: string;
userPoolId: string;
userName?: string;
callerContext: {
awsSdkVersion: string;
clientId: string;
};
request: {
userAttributes: {[key: string]: string};
validationData?: {[key: string]: string};
codeParameter?: string;
usernameParameter?: string;
newDeviceUsed?: boolean;
session?: {
challengeName: "CUSTOM_CHALLENGE" | "PASSWORD_VERIFIER" | "SMS_MFA" | "DEVICE_SRP_AUTH" | "DEVICE_PASSWORD_VERIFIER" | "ADMIN_NO_SRP_AUTH";
challengeResult: boolean;
challengeMetaData?: string;
}[];
challengeName?: string;
privateChallengeParameters?: {[key: string]: string};
challengeAnswer?: {[key: string]: string};
};
response: {
autoConfirmUser?: boolean;
smsMessage?: string;
emailMessage?: string;
emailSubject?: string;
challengeName?: string;
issueTokens?: boolean;
failAuthentication?: boolean;
publicChallengeParameters?: {[key: string]: string};
privateChallengeParameters?: {[key: string]: string};
challengeMetaData?: string;
answerCorrect?: boolean;
};
}
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
interface Context {
@@ -120,3 +120,15 @@ const BindingKindTest: Visitor = {
// kind === 'anythingElse';
},
};
// https://github.com/babel/babel/blob/d33d02359474296402b1577ef53f20d94e9085c4/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/exec/scope-bindings.js#L15-L25
const vScope: Visitor = {
Scope: {
enter(path) {
console.log(`Entering scope: ${path.node.type}`);
},
exit(path) {
console.log(`Exiting scope: ${path.node.type}`);
}
}
};
+1
View File
@@ -305,6 +305,7 @@ export interface Visitor extends VisitNodeObject<Node> {
FlowBaseAnnotation?: VisitNode<t.FlowBaseAnnotation>;
FlowDeclaration?: VisitNode<t.FlowDeclaration>;
JSX?: VisitNode<t.JSX>;
Scope?: VisitNode<t.Scopable>;
}
export type VisitNode<T> = VisitNodeFunction<T> | VisitNodeObject<T>;
+5
View File
@@ -14,6 +14,9 @@ traverse(ast, {
if (t.isIdentifier(node, { name: "n" })) {
node.name = "x";
}
if (t.isFunctionExpression(node)) {
node.params = [t.identifier('param')];
}
}
});
@@ -24,3 +27,5 @@ if (t.isBinaryExpression(ast)) {
}
t.assertBinaryExpression(ast);
t.assertBinaryExpression(ast, { operator: "*" });
var exp: t.Expression = t.nullLiteral();
+19 -19
View File
@@ -1,6 +1,6 @@
// Type definitions for babel-types v6.7
// Project: https://github.com/babel/babel/tree/master/packages/babel-types
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Definitions by: Troy Gerwien <https://github.com/yortus>, Sam Baxter <https://github.com/baxtersa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface Comment {
@@ -88,7 +88,7 @@ export interface CallExpression extends Node {
export interface CatchClause extends Node {
type: "CatchClause";
param: Pattern;
param: Identifier;
body: BlockStatement;
}
@@ -148,7 +148,7 @@ export interface ForStatement extends Node {
export interface FunctionDeclaration extends Node {
type: "FunctionDeclaration";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -159,7 +159,7 @@ export interface FunctionDeclaration extends Node {
export interface FunctionExpression extends Node {
type: "FunctionExpression";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -252,7 +252,7 @@ export interface ObjectMethod extends Node {
value: Expression;
decorators?: Decorator[];
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -353,20 +353,20 @@ export interface WithStatement extends Node {
export interface AssignmentPattern extends Node {
type: "AssignmentPattern";
left: Pattern;
left: Identifier;
right: Expression;
}
export interface ArrayPattern extends Node {
type: "ArrayPattern";
elements: Array<Pattern>;
elements: Array<Expression>;
typeAnnotation?: TypeAnnotation;
}
export interface ArrowFunctionExpression extends Node {
type: "ArrowFunctionExpression";
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement | Expression;
generator: boolean;
async: boolean;
@@ -472,7 +472,7 @@ export interface ClassMethod extends Node {
static: boolean;
decorators?: Decorator[];
id: Identifier;
params: Pattern[];
params: Array<LVal>;
body: BlockStatement;
generator: boolean;
async: boolean;
@@ -870,7 +870,7 @@ export interface SpreadProperty extends Node {
argument: Expression;
}
export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression;
export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression;
export type Binary = BinaryExpression | LogicalExpression;
export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod;
export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod;
@@ -886,11 +886,11 @@ export type For = ForInStatement | ForStatement | ForOfStatement;
export type ForXStatement = ForInStatement | ForOfStatement;
export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod;
export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod;
export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression;
export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression;
export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias;
export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern;
export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral;
export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement;
export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral;
export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement;
export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty;
export type Method = ObjectMethod | ClassMethod;
export type ObjectMember = ObjectMethod | ObjectProperty;
@@ -925,8 +925,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen
export function file(program?: Program, comments?: Comment[], tokens?: any[]): File;
export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement;
export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement;
export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration;
export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression;
export function functionDeclaration(id?: Identifier, params?: Array<LVal>, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration;
export function functionExpression(id?: Identifier, params?: Array<LVal>, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression;
export function identifier(name?: string): Identifier;
export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement;
export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement;
@@ -940,7 +940,7 @@ export function memberExpression(object?: Expression | Super, property?: Express
export function newExpression(callee?: Expression | Super, _arguments?: Array<Expression | SpreadElement>): NewExpression;
export function program(body?: Array<Statement | ModuleDeclaration>, directives?: Directive[]): Program;
export function objectExpression(properties?: Array<ObjectProperty | ObjectMethod | SpreadProperty>): ObjectExpression;
export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod;
export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array<LVal>, body?: BlockStatement, computed?: boolean): ObjectMethod;
export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty;
export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement;
export function returnStatement(argument?: Expression): ReturnStatement;
@@ -957,8 +957,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar
export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement;
export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement;
export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern;
export function arrayPattern(elements?: Array<Pattern>, typeAnnotation?: TypeAnnotation): ArrayPattern;
export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression;
export function arrayPattern(elements?: Array<Expression>, typeAnnotation?: TypeAnnotation): ArrayPattern;
export function arrowFunctionExpression(params?: Array<LVal>, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression;
export function classBody(body?: Array<ClassMethod | ClassProperty>): ClassBody;
export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration;
export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression;
@@ -972,7 +972,7 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi
export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier;
export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier;
export function metaProperty(meta?: string, property?: string): MetaProperty;
export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod;
export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array<LVal>, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod;
export function objectPattern(properties?: Array<AssignmentProperty | RestProperty>, typeAnnotation?: TypeAnnotation): ObjectPattern;
export function spreadElement(argument?: Expression): SpreadElement;
export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression;
+4 -3
View File
@@ -5,10 +5,11 @@
/// <reference types="babel-types" />
import * as t from 'babel-types';
type Node = t.Node;
import { File, Expression } from 'babel-types';
export function parse(code: string, opts?: BabylonOptions): Node;
export function parse(code: string, opts?: BabylonOptions): File;
export function parseExpression(input: string, options?: BabylonOptions): Expression;
export interface BabylonOptions {
/**
@@ -292,6 +292,14 @@ function RegionTests() {
}
function ViewTests() {
const v = new MyView(new MyModel());
const isDestroyed: boolean = v.isDestroyed();
const isRendered: boolean = v.isRendered();
const isAttached: boolean = v.isAttached();
const vv: Marionette.View<Backbone.Model> = v.delegateEntityEvents();
}
function CollectionViewTests() {
var cv = new MyCollectionView();
cv.collection.add(new MyModel());
+4 -1
View File
@@ -856,7 +856,10 @@ declare namespace Marionette {
/**
* Internal properties extended in Marionette.View.
*/
isDestroyed: boolean;
isDestroyed(): boolean;
isRendered(): boolean;
isAttached(): boolean;
delegateEntityEvents(): View<TModel>;
supportsRenderLifecycle: boolean;
supportsDestroyLifecycle: boolean;
@@ -107,60 +107,48 @@ namespace Paging {
testCollection.getFirstPage(options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getFirstPage({silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getFirstPage({url: true});
testCollection.getFirstPage({silent: false});
testCollection.getFirstPage({url: 'zombocom'});
result = testCollection.getLastPage();
testCollection.getLastPage(options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getLastPage({silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getLastPage({url: true});
testCollection.getLastPage({silent: true});
testCollection.getLastPage({url: 'chickensnack'});
result = testCollection.getNextPage();
testCollection.getNextPage(options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getNextPage({silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getNextPage({url: true});
testCollection.getNextPage({silent: false});
testCollection.getNextPage({url: 'hampsterdance'});
result = testCollection.getPage(1);
testCollection.getPage("1", options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getPage(1, {silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getPage(1, {url: true});
testCollection.getPage(1, {silent: true});
testCollection.getPage(1, {url: 'badcandy'});
result = testCollection.getPageByOffset(1);
testCollection.getPageByOffset(1, options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getPageByOffset(1, {silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getPageByOffset(1, {url: true});
testCollection.getPageByOffset(1, {silent: false});
testCollection.getPageByOffset(1, {url: 'oldmanmurray'});
result = testCollection.getPreviousPage();
testCollection.getPreviousPage(options);
// 'silent's type is boolean. (structural subtyping)
testCollection.getPreviousPage({silent: 'aa'});
// 'url's type is string. (structural subtyping)
testCollection.getPreviousPage({url: true});
testCollection.getPreviousPage({silent: false});
testCollection.getPreviousPage({url: 'uncyclopedia'});
var hasPage:boolean = testCollection.hasNextPage();
@@ -231,7 +219,7 @@ namespace Setting {
var result2:TestCollection
= testCollection.setSorting('id', 1, options);
= testCollection.setSorting('id', 1, { full: true});
result1 = testCollection.switchMode(
'server',
+5
View File
@@ -190,6 +190,11 @@ function CommonMethodsInEventStreamsAndProperties() {
console.log(sum); // returns [-1, 2, 8] in an order
});
}
{
var src = Bacon.fromArray([1, 2, 3]);
src.doLog('element value');
}
}
function EventStream() {
+9 -7
View File
@@ -1,6 +1,6 @@
// Type definitions for Bacon.js 0.7.0
// Project: https://baconjs.github.io/
// Definitions by: Alexander Matsievsky <https://github.com/alexander-matsievsky>
// Definitions by: Alexander Matsievsky <https://github.com/alexander-matsievsky>, Joonas Javanainen <https://github.com/gekkio>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery" />
@@ -69,7 +69,7 @@ declare namespace Bacon {
/**
* @function
* @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream.
* @param {Promise<A>|JQueryXHR} promise
* @param {PromiseLike<A>|JQueryXHR} promise
* @param {boolean} [abort]
* @returns {EventStream<E, A>}
* @example
@@ -78,7 +78,7 @@ declare namespace Bacon {
* Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true);
* Bacon.fromPromise(Promise.resolve(1), false);
*/
function fromPromise<E, A>(promise:Promise<A>|JQueryXHR, abort?:boolean):EventStream<E, A>;
function fromPromise<E, A>(promise:PromiseLike<A>|JQueryXHR, abort?:boolean):EventStream<E, A>;
/**
* @callback Bacon.fromPromise~eventTransformer
@@ -88,7 +88,7 @@ declare namespace Bacon {
/**
* @function Bacon.fromPromise
* @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`.
* @param {Promise<A>|JQueryXHR} promise
* @param {PromiseLike<A>|JQueryXHR} promise
* @param {boolean} abort
* @param {Bacon.fromPromise~eventTransformer} eventTransformer
* @returns {EventStream<E, B>}
@@ -100,7 +100,7 @@ declare namespace Bacon {
* return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()];
* });
*/
function fromPromise<E, A, B>(promise:Promise<A>|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial<B>|Next<B>|End<B>|Error<E>)[]):EventStream<E, B>;
function fromPromise<E, A, B>(promise:PromiseLike<A>|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial<B>|Next<B>|End<B>|Error<E>)[]):EventStream<E, B>;
/**
* @function
@@ -1026,9 +1026,10 @@ declare namespace Bacon {
/**
* @method EventStream#doLog
* @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does.
* @param {string} [label]
* @returns {EventStream<E, A>}
*/
doLog():EventStream<E, A>;
doLog(label?:string):EventStream<E, A>;
/**
* @method
@@ -1613,9 +1614,10 @@ declare namespace Bacon {
/**
* @method Property#doLog
* @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does.
* @param {string} [label]
* @returns {Property<E, A>}
*/
doLog():Property<E, A>;
doLog(label?:string):Property<E, A>;
/**
* @method
+10 -10
View File
@@ -3,7 +3,7 @@
// Definitions by: Michael Mrowetz <https://github.com/micmro>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface FittingContext {
export interface FittingContext {
/** The input defined in the fitting definition
* (string, number, object, array)
*/
@@ -17,9 +17,9 @@ interface FittingContext {
* Fitting types has pre-defined fittings `system` and `user`
* but can be any any string for custom types like `swagger` or `node-machine`
*/
type FittingType = "system" | "user" | string;
export type FittingType = "system" | "user" | string;
interface FittingDef {
export interface FittingDef {
/**
* If type is omitted (as it must be for in-line usage), Bagpipes will
* first check the user fittings then the system fittings for the name and
@@ -46,8 +46,8 @@ interface FittingDef {
*
* Will be called called when the `Pipe` it is contained it gets 'played'
*/
type Fitting = (
context: FittingContext,
export type Fitting = (
context: FittingContext,
next: {(err: Error | null | undefined, res?: any): void}) => void;
/**
@@ -58,18 +58,18 @@ type Fitting = (
*
* @param {Object} fittingDef Fitting Definition
*/
type FittingFactory = (fittingDef: FittingDef, bagpipes: any) => Fitting;
export type FittingFactory = (fittingDef: FittingDef, bagpipes: any) => Fitting;
/**
* Hashmap of `fittingType`s (the name of a fitting) and the
* `FittingFactory` functions used to create them
*/
interface FittingTypesMap {
export interface FittingTypesMap {
[fittingType: string]: FittingFactory;
}
/** The Pipe Definition */
type PipeDef = any[] | string | FittingDef;
export type PipeDef = any[] | string | FittingDef;
/** Hashmap of Pipe Definitons */
export interface PipeDefMap {
@@ -143,10 +143,10 @@ export function create(pipesDefs: PipeDefMap, conf?: Config): Bagpipes;
// Types for imports from `pipeworks` module
type Affinity = "hoist" | "sink";
export type Affinity = "hoist" | "sink";
/** PipeDef used in `pipeworks` module */
interface PipeworksOptions {
export interface PipeworksOptions {
/**
* Adds to the pre and post queues, respectively.
* Ensures a pipe gets fitted before or after the main execution pipeline.
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"callable-types": false
}
}
+10 -2
View File
@@ -1,4 +1,12 @@
import {IncomingMessage} from 'http';
import auth = require('basic-auth');
auth(null);
const loginData = auth(undefined! as IncomingMessage);
if (loginData) {
const {name, pass} = loginData;
}
const parsed = auth.parse('Basic QmFzaWM6QXV0aA==');
if (parsed) {
const {name, pass} = parsed;
}
+9 -3
View File
@@ -1,19 +1,25 @@
// Type definitions for basic-auth
// Type definitions for basic-auth 1.1
// Project: https://github.com/jshttp/basic-auth
// Definitions by: Clément Bourgeois <https://github.com/moonpyk>
// Definitions by: Clément Bourgeois <https://github.com/moonpyk>, Vesa Poikajärvi <https://github.com/vesse>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as http from 'http';
declare function auth(req: http.IncomingMessage): auth.BasicAuthResult;
// See https://github.com/jshttp/basic-auth/blob/v1.1.0/index.js#L49
declare function auth(req: http.IncomingMessage): auth.BasicAuthResult | undefined;
declare namespace auth {
interface BasicAuthResult {
name: string;
pass: string;
}
/**
* Parse basic auth to object.
*/
function parse(authorizationHeader: string): auth.BasicAuthResult | undefined;
}
export = auth;
+1 -1
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
-118
View File
@@ -1,118 +0,0 @@
// constructor tests
var noArgument = bigInt(),
numberArgument = bigInt( 93 ),
stringArgument = bigInt( "75643564363473453456342378564387956906736546456235345" ),
baseArgumentInt = bigInt( "101010", 2 ),
baseArgumentStr = bigInt( "101010", "2" ),
baseArgumentBi = bigInt( "101010", bigInt( 2 ) ),
bigIntArgument = bigInt( noArgument );
// method tests
var x = bigInt(),
isBigInteger: BigInteger,
isNumber: number,
isBoolean: boolean,
isString: string,
isDivmod: {
quotient: BigInteger;
remainder: BigInteger;
};
isBigInteger = x.abs();
isBigInteger = x.add( 0 );
isBigInteger = x.add( x );
isBigInteger = x.add( "100" );
isNumber = x.compare( 0 );
isNumber = x.compare( x );
isNumber = x.compare( "100" );
isNumber = x.compareAbs( 0 );
isNumber = x.compareAbs( x );
isNumber = x.compareAbs( "100" );
isBigInteger = x.divide( 0 );
isBigInteger = x.divide( x );
isBigInteger = x.divide( "100" );
isDivmod = x.divmod( 0 );
isDivmod = x.divmod( x );
isDivmod = x.divmod( "100" );
isBoolean = x.equals( 0 );
isBoolean = x.equals( x );
isBoolean = x.equals( "100" );
isBoolean = x.greater( 0 );
isBoolean = x.greater( x );
isBoolean = x.greater( "100" );
isBoolean = x.greaterOrEquals( 0 );
isBoolean = x.greaterOrEquals( x );
isBoolean = x.greaterOrEquals( "100" );
isBoolean = x.isEven();
isBoolean = x.isNegative();
isBoolean = x.isOdd();
isBoolean = x.isPositive();
isBoolean = x.lesser( 0 );
isBoolean = x.lesser( x );
isBoolean = x.lesser( "100" );
isBoolean = x.lesserOrEquals( 0 );
isBoolean = x.lesserOrEquals( x );
isBoolean = x.lesserOrEquals( "100" );
isBigInteger = x.minus( 0 );
isBigInteger = x.minus( x );
isBigInteger = x.minus( "100" );
isBigInteger = x.mod( 0 );
isBigInteger = x.mod( x );
isBigInteger = x.mod( "100" );
isBigInteger = x.multiply( 0 );
isBigInteger = x.multiply( x );
isBigInteger = x.multiply( "100" );
isBigInteger = x.next();
isBoolean = x.notEquals( 0 );
isBoolean = x.notEquals( x );
isBoolean = x.notEquals( "100" );
isBigInteger = x.over( 0 );
isBigInteger = x.over( x );
isBigInteger = x.over( "100" );
isBigInteger = x.plus( 0 );
isBigInteger = x.plus( x );
isBigInteger = x.plus( "100" );
isBigInteger = x.pow( 0 );
isBigInteger = x.pow( x );
isBigInteger = x.pow( "100" );
isBigInteger = x.prev();
isBigInteger = x.subtract( 0 );
isBigInteger = x.subtract( x );
isBigInteger = x.subtract( "100" );
isBigInteger = x.times( 0 );
isBigInteger = x.times( x );
isBigInteger = x.times( "100" );
isNumber = x.toJSNumber();
isString = x.toString();
isString = x.toString(36);
isNumber = x.valueOf();
-226
View File
@@ -1,226 +0,0 @@
// Type definitions for BigInteger.js
// Project: https://github.com/peterolson/BigInteger.js
// Definitions by: Ingo Bürk <https://github.com/Airblader>, Roel van Uden <https://github.com/Deathspike>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface BigInteger {
/** Returns the absolute value of a bigInt. */
abs(): BigInteger;
/** Performs addition */
add( number: number ): BigInteger;
/** Performs addition */
add( number: BigInteger ): BigInteger;
/** Performs addition */
add( number: string ): BigInteger;
/** Alias for the add method. */
plus( number: number ): BigInteger;
/** Alias for the add method. */
plus( number: BigInteger ): BigInteger;
/** Alias for the add method. */
plus( number: string ): BigInteger;
/** Alias for the subtract method. */
minus( number: number ): BigInteger;
/** Alias for the subtract method. */
minus( number: BigInteger ): BigInteger;
/** Alias for the subtract method. */
minus( number: string ): BigInteger;
/** Performs subtraction. */
subtract( number: number ): BigInteger;
/** Performs subtraction. */
subtract( number: BigInteger ): BigInteger;
/** Performs subtraction. */
subtract( number: string ): BigInteger;
/** Performs multiplication. */
multiply( number: number ): BigInteger;
/** Performs multiplication. */
multiply( number: BigInteger ): BigInteger;
/** Performs multiplication. */
multiply( number: string ): BigInteger;
/** Alias for the multiply method. */
times( number: number ): BigInteger;
/** Alias for the multiply method. */
times( number: BigInteger ): BigInteger;
/** Alias for the multiply method. */
times( number: string ): BigInteger;
/** Performs integer division, disregarding the remainder. */
divide( number: number ): BigInteger;
/** Performs integer division, disregarding the remainder. */
divide( number: BigInteger ): BigInteger;
/** Performs integer division, disregarding the remainder. */
divide( number: string ): BigInteger;
/** Alias for the divide method. */
over( number: number ): BigInteger;
/** Alias for the divide method. */
over( number: BigInteger ): BigInteger;
/** Alias for the divide method. */
over( number: string ): BigInteger;
/** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */
pow( number: number ): BigInteger;
/** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */
pow( number: BigInteger ): BigInteger;
/** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */
pow( number: string ): BigInteger;
/** Adds one to the number. */
next(): BigInteger;
/** Subtracts one from the number. */
prev(): BigInteger;
/** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */
mod( number: number ): BigInteger;
/** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */
mod( number: BigInteger ): BigInteger;
/** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */
mod( number: string ): BigInteger;
/** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */
divmod( number: number ): { quotient: BigInteger; remainder: BigInteger };
/** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */
divmod( number: BigInteger ): { quotient: BigInteger; remainder: BigInteger };
/** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */
divmod( number: string ): { quotient: BigInteger; remainder: BigInteger };
/** Checks if the first number is greater than the second. */
greater( number: number ): boolean;
/** Checks if the first number is greater than the second. */
greater( number: BigInteger ): boolean;
/** Checks if the first number is greater than the second. */
greater( number: string ): boolean;
/** Checks if the first number is greater than or equal to the second. */
greaterOrEquals( number: number ): boolean;
/** Checks if the first number is greater than or equal to the second. */
greaterOrEquals( number: BigInteger ): boolean;
/** Checks if the first number is greater than or equal to the second. */
greaterOrEquals( number: string ): boolean;
/** Checks if the first number is lesser than the second. */
lesser( number: number ): boolean;
/** Checks if the first number is lesser than the second. */
lesser( number: BigInteger ): boolean;
/** Checks if the first number is lesser than the second. */
lesser( number: string ): boolean;
/** Checks if the first number is less than or equal to the second. */
lesserOrEquals( number: number ): boolean;
/** Checks if the first number is less than or equal to the second. */
lesserOrEquals( number: BigInteger ): boolean;
/** Checks if the first number is less than or equal to the second. */
lesserOrEquals( number: string ): boolean;
/** Returns true if the number is even, false otherwise. */
isEven(): boolean;
/** Returns true if the number is odd, false otherwise. */
isOdd(): boolean;
/** Return true if the number is positive, false otherwise. Returns true for 0 and false for -0. */
isPositive(): boolean;
/** Returns true if the number is negative, false otherwise. Returns false for 0 and true for -0. */
isNegative(): boolean;
/**
* Performs a comparison between two numbers. If the numbers are equal, it returns 0.
* If the first number is greater, it returns 1. If the first number is lesser, it returns -1.
*/
compare( number: number ): number;
/**
* Performs a comparison between two numbers. If the numbers are equal, it returns 0.
* If the first number is greater, it returns 1. If the first number is lesser, it returns -1.
*/
compare( number: BigInteger ): number;
/**
* Performs a comparison between two numbers. If the numbers are equal, it returns 0.
* If the first number is greater, it returns 1. If the first number is lesser, it returns -1.
*/
compare( number: string ): number;
/** Performs a comparison between the absolute value of two numbers. */
compareAbs( number: number ): number;
/** Performs a comparison between the absolute value of two numbers. */
compareAbs( number: BigInteger ): number;
/** Performs a comparison between the absolute value of two numbers. */
compareAbs( number: string ): number;
/** Checks if two numbers are equal. */
equals( number: number ): boolean;
/** Checks if two numbers are equal. */
equals( number: BigInteger ): boolean;
/** Checks if two numbers are equal. */
equals( number: string ): boolean;
/** Checks if two numbers are not equal. */
notEquals( number: number ): boolean;
/** Checks if two numbers are not equal. */
notEquals( number: BigInteger ): boolean;
/** Checks if two numbers are not equal. */
notEquals( number: string ): boolean;
/** Performs the bitwise AND operation. */
and( number: number ): BigInteger;
/** Performs the bitwise AND operation. */
and( number: BigInteger ): BigInteger;
/** Performs the bitwise AND operation. */
and( number: string ): BigInteger;
/** Performs the bitwise NOT operation. */
not(): BigInteger;
/** Performs the bitwise OR operation. */
or( number: number ): BigInteger;
/** Performs the bitwise OR operation. */
or( number: BigInteger ): BigInteger;
/** Performs the bitwise OR operation. */
or( number: string ): BigInteger;
/** Performs the bitwise XOR operation. */
xor( number: number ): BigInteger;
/** Performs the bitwise XOR operation. */
xor( number: BigInteger ): BigInteger;
/** Performs the bitwise XOR operation. */
xor( number: string ): BigInteger;
/** Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range. */
toJSNumber(): number;
/** Converts a bigInt to a string. */
toString( radix?: number ): string;
/** Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion. */
valueOf(): number;
}
interface BigIntegerStatic {
/** Equivalent to bigInt(1) */
one: BigInteger;
/** Equivalent to bigInt(0) */
zero: BigInteger;
/** Equivalent to bigInt(-1) */
minusOne: BigInteger;
/** Equivalent to bigInt(0) */
(): BigInteger;
/** Parse a Javascript number into a bigInt */
( number: number ): BigInteger;
/** Parse a string into a bigInt */
( string: string, base?: string | number | BigInteger): BigInteger;
/** no-op */
( bigInt: BigInteger ): BigInteger;
}
declare var bigInt: BigIntegerStatic;
declare module "big-integer" {
export = bigInt;
}
+56
View File
@@ -0,0 +1,56 @@
import * as Bleno from 'bleno';
export class EchoCharacteristic extends Bleno.Characteristic {
_value: any;
_updateValueCallback: any;
constructor() {
super({
uuid: 'ec0e',
properties: ['read', 'write', 'notify'],
value: null
});
this._value = new ArrayBuffer(0);
this._updateValueCallback = null;
}
onReadRequest(offset: number, callback: any) {
callback(Bleno.Characteristic.RESULT_SUCCESS, this._value);
}
onWriteRequest(data: any, offset: number, withoutResponse: boolean, callback: any) {
this._value = data;
if (this._updateValueCallback) {
this._updateValueCallback(this._value);
}
callback(Bleno.Characteristic.RESULT_SUCCESS);
}
onSubscribe(maxValueSize: number, updateValueCallback: any) {
this._updateValueCallback = updateValueCallback;
}
onUnsubscribefunction() {
this._updateValueCallback = null;
}
}
Bleno.on('stateChange', (state: string) => {
if (state === 'poweredOn') {
Bleno.startAdvertising('echo', ['ec00'], () => {});
} else {
Bleno.stopAdvertising(() => {});
}
});
let characteristic = new EchoCharacteristic();
Bleno.on('advertisingStart', (error: string) => {
if (!error) {
Bleno.setServices(
[new Bleno.PrimaryService({uuid: 'ec00', characteristics: [ characteristic ] })],
() => {}
);
}
});
+128
View File
@@ -0,0 +1,128 @@
// Type definitions for bleno 0.4
// Project: https://github.com/sandeepmistry/bleno
// Definitions by: Manuel Francisco Naranjo <naranjo.manuel@gmail.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class Characteristic {
uuid: any;
properties: any;
secure: any;
value: any;
descriptors: any;
constructor(options: any);
onIndicate(): void;
onNotify(): void;
onReadRequest(offset: any, callback: any): void;
onSubscribe(maxValueSize: any, updateValueCallback: any): void;
onUnsubscribe(): void;
onWriteRequest(data: any, offset: any, withoutResponse: any, callback: any): void;
toString(): any;
static RESULT_ATTR_NOT_LONG: number;
static RESULT_INVALID_ATTRIBUTE_LENGTH: number;
static RESULT_INVALID_OFFSET: number;
static RESULT_SUCCESS: number;
static RESULT_UNLIKELY_ERROR: number;
}
export class Descriptor {
uuid: any;
value: any;
constructor(options: any);
toString(): any;
}
export class PrimaryService {
uuid: any;
characteristics: any;
constructor(options: any);
toString(): any;
}
export const address: string;
export const domain: any;
export const mtu: number;
export const platform: string;
export const rssi: number;
export const state: string;
export function addListener(type: any, listener: any): any;
export function disconnect(): void;
export function emit(type: any, ...args: any[]): any;
export function eventNames(): any;
export function getMaxListeners(): any;
export function listenerCount(type: any): any;
export function listeners(type: any): any;
export function on(type: any, listener: any): any;
export function onAccept(clientAddress: any): void;
export function onAddressChange(address: any): void;
export function onAdvertisingStart(error: any): void;
export function onAdvertisingStop(): void;
export function onDisconnect(clientAddress: any): void;
export function onMtuChange(mtu: any): void;
export function onPlatform(platform: any): void;
export function onRssiUpdate(rssi: any): void;
export function onServicesSet(error: any): void;
export function onStateChange(state: any): void;
export function once(type: any, listener: any): any;
export function prependListener(type: any, listener: any): any;
export function prependOnceListener(type: any, listener: any): any;
export function removeAllListeners(type: any, ...args: any[]): any;
export function removeListener(type: any, listener: any): any;
export function setMaxListeners(n: any): any;
export function setServices(services: any, callback: any): void;
export function startAdvertising(name: any, serviceUuids: any, callback: any): void;
export function startAdvertisingIBeacon(uuid: any, major: any, minor: any, measuredPower: any, callback: any): void;
export function startAdvertisingWithEIRData(advertisementData: any, scanData: any, callback: any): void;
export function stopAdvertising(callback: any): void;
export function updateRssi(callback: any): void;
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bleno-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+17
View File
@@ -0,0 +1,17 @@
import * as blobUtil from 'blob-util';
const testBlob = new Blob(['abcd']);
blobUtil.base64StringToBlob('abcd'); // $ExpectType Promise<Blob>
blobUtil.createObjectURL(testBlob); // $ExpectType string
blobUtil.imgSrcToBlob('test.jpg'); // $ExpectType Promise<Blob>
blobUtil.createBlob(['abcd']); // $ExpectType Blob
blobUtil.arrayBufferToBlob(new ArrayBuffer(0)); // $ExpectType Promise<Blob>
blobUtil.binaryStringToBlob('0101'); // $ExpectType Promise<Blob>
blobUtil.blobToArrayBuffer(testBlob); // $ExpectType Promise<ArrayBuffer>
blobUtil.blobToBase64String(testBlob); // $ExpectType Promise<string>
blobUtil.blobToBinaryString(testBlob); // $ExpectType Promise<string>
blobUtil.canvasToBlob(new HTMLCanvasElement()); // $ExpectType Promise<Blob>
blobUtil.dataURLToBlob('data:abcd'); // $ExpectType Promise<Blob>
blobUtil.imgSrcToDataURL('test.jpg'); // $ExpectType Promise<string>
blobUtil.revokeObjectURL('blob:example'); // $ExpectType void
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for blob-util 1.2
// Project: https://github.com/nolanlawson/blob-util#readme
// Definitions by: Max Battcher <https://github.com/WorldMaker>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function createBlob(parts: any[], options?: { type: string }): Blob;
export function createObjectURL(blob: Blob): string;
export function revokeObjectURL(url: string): void;
export function blobToBinaryString(blob: Blob): Promise<string>;
export function binaryStringToBlob(binary: string, type?: string): Promise<Blob>;
export function blobToBase64String(blob: Blob): Promise<string>;
export function base64StringToBlob(base64: string, type?: string): Promise<Blob>;
export function dataURLToBlob(dataURL: string): Promise<Blob>;
export function imgSrcToDataURL(src: string, type?: string, crossOrigin?: string): Promise<string>;
export function canvasToBlob(canvas: HTMLCanvasElement, type?: string): Promise<Blob>;
export function imgSrcToBlob(src: string, type?: string, crossOrigin?: string): Promise<Blob>;
export function arrayBufferToBlob(arrayBuff: ArrayBuffer, type?: string): Promise<Blob>;
export function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer>;
+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",
"blob-util-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+16
View File
@@ -361,6 +361,22 @@ fooProm = fooProm.catch(CustomError, reason => {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{
class CustomError1 extends Error {}
class CustomError2 extends Error {}
class CustomError3 extends Error {}
class CustomError4 extends Error {}
class CustomError5 extends Error {}
fooProm = fooProm.catch(CustomError1, error => {});
fooProm = fooProm.catch(CustomError1, CustomError2, error => {});
fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, error => {});
fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, error => {});
fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, CustomError5, error => {});
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.error((reason: any) => {
return bar;
});
+220 -24
View File
@@ -65,24 +65,133 @@ declare class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R
* This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*
* TODO: disallow non-objects
*/
catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
catch<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4 | E5) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
caught<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4 | E5) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
catch<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
caught<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
catch<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
caught<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
catch<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
caught<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
catch<E extends Error>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
caught<E extends Error>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
catch<E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
caught<E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
catch<U, E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
caught<U, E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
catch<E extends Error, U>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
caught<E extends Error, U>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
catch<E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
caught<E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
catch<U, E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
caught<U, E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>): Bluebird<R>;
catch<U>(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
caught<U>(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U | R>;
catch<E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
onReject: (error: E1) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
caught<E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
onReject: (error: E1) => R | Bluebird.Thenable<R> | void | Bluebird.Thenable<void>,
): Bluebird<R>;
catch<U, E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
onReject: (error: E1) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
caught<U, E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
onReject: (error: E1) => U | Bluebird.Thenable<U>,
): Bluebird<U | R>;
/**
* Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
@@ -116,11 +225,40 @@ declare class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R
/**
* Like `.catch()` but rethrows the error
* TODO: disallow non-objects
*/
tapCatch<U>(onReject: (error?: any) => U | Bluebird.Thenable<U> | void | Bluebird.Thenable<void>): Bluebird<R>;
tapCatch<U, E extends Error>(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable<U> | void | Bluebird.Thenable<void>): Bluebird<R>;
tapCatch<U>(predicate: (error?: any) => boolean, onReject: (error?: any) => U | Bluebird.Thenable<U> | void | Bluebird.Thenable<void>): Bluebird<R>;
tapCatch<U>(onReject: (error?: any) => U | Bluebird.Thenable<U>): Bluebird<R>;
tapCatch<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable<U>,
): Bluebird<R>;
tapCatch<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable<U>,
): Bluebird<R>;
tapCatch<U, E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable<U>,
): Bluebird<R>;
tapCatch<U, E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
onReject: (error: E1 | E2) => U | Bluebird.Thenable<U>,
): Bluebird<R>;
tapCatch<U, E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
onReject: (error: E1) => U | Bluebird.Thenable<U>,
): Bluebird<R>;
/**
* Same as calling `Promise.delay(ms, this)`.
@@ -228,8 +366,8 @@ declare class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(): Bluebird<any>;
thenReturn(): Bluebird<any>;
return(): Bluebird<void>;
thenReturn(): Bluebird<void>;
return<U>(value: U): Bluebird<U>;
thenReturn<U>(value: U): Bluebird<U>;
@@ -258,11 +396,40 @@ declare class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()`
* TODO: disallow non-objects
*/
catchReturn<U>(value: U): Bluebird<U>;
catchReturn<U>(predicate: (error: any) => boolean, value: U): Bluebird<U | R>;
catchReturn<E extends Error, U>(ErrorClass: new (...args: any[]) => E, value: U): Bluebird<U | R>;
catchReturn<U>(predicate: Object, value: U): Bluebird<U | R>;
catchReturn<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
value: U,
): Bluebird<U>;
catchReturn<U, E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
value: U,
): Bluebird<U>;
catchReturn<U, E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
value: U,
): Bluebird<U>;
catchReturn<U, E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
value: U,
): Bluebird<U>;
catchReturn<U, E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
value: U,
): Bluebird<U>;
/**
* Convenience method for:
@@ -273,11 +440,40 @@ declare class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R
* });
* </code>
* Same limitations apply as with `.catchReturn()`.
* TODO: disallow non-objects
*/
catchThrow(reason: Error): Bluebird<R>;
catchThrow(predicate: (error: any) => boolean, reason: Error): Bluebird<R>;
catchThrow<E extends Error, U>(ErrorClass: new (...args: any[]) => E, reason: Error): Bluebird<R>;
catchThrow(predicate: Object, reason: Error): Bluebird<R>;
catchThrow<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error, E5 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object,
reason: Error,
): Bluebird<R>;
catchThrow<E1 extends Error, E2 extends Error, E3 extends Error, E4 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object,
reason: Error,
): Bluebird<R>;
catchThrow<E1 extends Error, E2 extends Error, E3 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object,
reason: Error,
): Bluebird<R>;
catchThrow<E1 extends Error, E2 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object,
reason: Error,
): Bluebird<R>;
catchThrow<E1 extends Error>(
filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object,
reason: Error,
): Bluebird<R>;
/**
* Convert to String.
+14 -11
View File
@@ -1,20 +1,23 @@
import * as bonjour from 'bonjour';
var bonjourOptions: bonjour.BonjourOptions;
var bonjourInstance: bonjour.Bonjour;
let bonjourOptions: bonjour.BonjourOptions;
let bonjourInstance: bonjour.Bonjour;
var serviceOptions: bonjour.ServiceOptions;
var service: bonjour.Service;
let serviceOptions: bonjour.ServiceOptions;
let service: bonjour.Service;
var browserOptions: bonjour.BrowserOptions;
var browser: bonjour.Browser;
let browserOptions: bonjour.BrowserOptions;
let browser: bonjour.Browser;
bonjourOptions = { interface: '192.168.1.1', port: 5353 };
bonjourInstance = new bonjour.Bonjour(bonjourOptions);
bonjourOptions = {};
bonjourInstance = bonjour(bonjourOptions);
serviceOptions = { name: 'My Web Server', type: 'http', port: 3000 };
// Publish a dummy server under name 'My Website' type http port 3000
serviceOptions = { name: 'My Website', type: 'http', port: 3000 };
service = bonjourInstance.publish(serviceOptions);
browserOptions = { protocol: 'tcp', type: 'http' };
browser = bonjour.find(browserOptions);
// Look for the server
browser = bonjourInstance.findOne(browserOptions, (srv: bonjour.Service) => {
// You can test here if the found server (srv) name is 'My Website'
});
+79 -64
View File
@@ -1,68 +1,83 @@
// Type definitions for bonjour v3.5.0
// Type definitions for bonjour 3.5
// Project: https://github.com/watson/bonjour
// Definitions by: Quentin Lampin <https://github.com/quentin-ol/>
// Definitions by: Quentin Lampin <https://github.com/quentin-ol/>, Nicolas Voigt <https://github.com/octo-sniffle>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface BonjourOptions {
multicast?: boolean;
interface?: string;
port?: number;
ip?: string;
ttl?: number;
loopback?: boolean;
reuseAddr?: boolean;
/// <reference types="node" />
declare function bonjour(opts?: bonjour.BonjourOptions): bonjour.Bonjour;
export = bonjour;
declare namespace bonjour {
/**
* Start a browser
*
* The browser listens for services by querying for PTR records of a given
* type, protocol and domain, e.g. _http._tcp.local.
*
* If no type is given, a wild card search is performed.
*
* An internal list of online services is kept which starts out empty. When
* ever a new service is discovered, it's added to the list and an "up" event
* is emitted with that service. When it's discovered that the service is no
* longer available, it is removed from the list and a "down" event is emitted
* with that service.
*/
interface Browser extends NodeJS.EventEmitter {
services: Service[];
start(): void;
update(): void;
stop(): void;
on(event: 'up' | 'down', listener: (service: Service) => void): this;
once(event: 'up' | 'down', listener: (service: Service) => void): this;
removeListener(event: 'up' | 'down', listener: (service: Service) => void): this;
removeAllListeners(event: 'up' | 'down'): this;
}
interface BrowserOptions {
type?: string;
subtypes?: string[];
protocol?: string;
txt?: Object;
}
interface ServiceOptions {
name: string;
host?: string;
port: number;
type: string;
subtypes?: string[];
protocol?: 'udp'|'tcp';
txt?: Object;
}
interface Service extends NodeJS.EventEmitter {
name: string;
type: string;
subtypes: string[];
protocol: string;
host: string;
port: number;
fqdn: string;
txt: Object;
published: boolean;
stop(cb: () => any): void;
start(): void;
}
interface BonjourOptions {
multicast?: boolean;
interface?: string;
port?: number;
ip?: string;
ttl?: number;
loopback?: boolean;
reuseAddr?: boolean;
}
interface Bonjour {
(opts?: BonjourOptions): Bonjour;
publish(options: ServiceOptions): Service;
unpublishAll(cb?: () => void): void;
find(options: BrowserOptions, onUp?: (service: Service) => void): Browser;
findOne(options: BrowserOptions, cb?: (service: Service) => void): Browser;
destroy(): void;
}
}
export interface BrowserOptions {
type?: string;
subtypes?: string[];
protocol?: string;
txt?: Object;
}
export interface ServiceOptions {
name: string;
host?: string;
port: number;
type: string;
subtypes?: string[];
protocol?: 'udp'|'tcp';
txt?: Object;
}
export interface Service {
name: string;
type: string;
subtypes: string[];
protocol: string;
host: string;
port: number;
fqdn: string;
rawTxt: Object;
txt: Object;
published: boolean;
stop: (cb: ()=>any) => void;
start: () => void;
}
export class Bonjour {
constructor(opts: BonjourOptions);
publish(options: ServiceOptions):Service;
unpublishAll(cb: ()=>any): void;
find(options:BrowserOptions, onUp: ()=>any): Browser;
findOne(options:any, cb: (service: Service)=>any): Browser;
destroy():void;
}
export class Browser {
services: Service[];
start():void;
update():void;
stop():void;
}
export function find(options: BrowserOptions, onUp?: ()=>any): Browser;
export function findOne(options: BrowserOptions): Browser;
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"ban-types": false
}
}
+30 -1
View File
@@ -481,6 +481,15 @@ new Book({'ISBN-13': '9780440180296'})
/* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */
{
(new User).fetchAll({
columns: ['id', 'name'],
withRelated: ['posts.tags']
}).then((user: any) => {
console.log(user);
})
}
/* model.format(), see http://bookshelfjs.org/#Model-instance-format */
/* model.get(), see http://bookshelfjs.org/#Model-instance-get */
@@ -637,6 +646,16 @@ customer.on('fetching', (model, columns) => {
/* model.once(), see http://bookshelfjs.org/#Model-instance-once */
/* model.orderBy(), see http://bookshelfjs.org/#Model-instance-orderBy */
{
(new User)
.orderBy('name', 'ASC')
.fetchAll()
.then((users: Bookshelf.Collection<User>) => {
console.log(users)
});
}
/* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */
// Example of a "parse" to convert snake_case to camelCase, using `underscore.string`
@@ -1096,6 +1115,16 @@ ships.on('fetched', (collection, response) => {
/* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */
/* collection.orderBy(), see http://bookshelfjs.org/#Collection-instance-orderBy */
{
User.collection()
.orderBy('-name')
.fetch()
.then((users: Bookshelf.Collection<User>) => {
console.log(users);
})
}
/* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */
/* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */
@@ -1376,4 +1405,4 @@ new User({name: 'John'}).fetchAll({require: true})
new Country({id: 1}).capital().fetch().then(model => {
// ...
});
}
}
+9 -5
View File
@@ -1,6 +1,6 @@
// Type definitions for bookshelfjs v0.8.2
// Type definitions for bookshelfjs v0.9.3
// Project: http://bookshelfjs.org/
// Definitions by: Andrew Schurman <http://github.com/arcticwaters>
// Definitions by: Andrew Schurman <http://github.com/arcticwaters>, Vesa Poikajärvi <https://github.com/vesse>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -23,6 +23,8 @@ interface Bookshelf extends Bookshelf.Events<any> {
declare function Bookshelf(knex: knex): Bookshelf;
declare namespace Bookshelf {
type SortOrder = 'ASC'|'asc'|'DESC'|'desc';
abstract class Events<T> {
on(event?: string, callback?: EventFunction<T>, context?: any): void;
off(event?: string): void;
@@ -38,7 +40,8 @@ declare namespace Bookshelf {
tableName?: string;
}
abstract class ModelBase<T extends Model<any>> extends Events<T | Collection<T>> implements IModelBase {
interface ModelBase<T extends Model<any>> extends IModelBase { }
abstract class ModelBase<T extends Model<any>> extends Events<T | Collection<T>> {
/** If overriding, must use a getter instead of a plain property. */
idAttribute: string;
@@ -105,6 +108,7 @@ declare namespace Bookshelf {
morphOne<R extends Model<any>>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R;
morphTo(name: string, columnNames?: string[], ...target: typeof Model[]): T;
morphTo(name: string, ...target: typeof Model[]): T;
orderBy(column: string, order?: SortOrder): T;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query(): Knex.QueryBuilder;
@@ -242,6 +246,7 @@ declare namespace Bookshelf {
detach(options?: SyncOptions): BlueBird<any>;
fetchOne(options?: CollectionFetchOneOptions): BlueBird<T>;
load(relations: string | string[], options?: SyncOptions): BlueBird<Collection<T>>;
orderBy(column: string, order?: SortOrder): T;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query(): Knex.QueryBuilder;
@@ -278,8 +283,7 @@ declare namespace Bookshelf {
[index: string]: (query: Knex.QueryBuilder) => Knex.QueryBuilder;
}
interface FetchAllOptions extends SyncOptions {
require?: boolean;
interface FetchAllOptions extends FetchOptions {
}
interface SaveOptions extends SyncOptions {
+172 -35
View File
@@ -1,44 +1,154 @@
import Boom = require('boom');
import * as Hapi from 'hapi';
var bo = Boom.wrap(new Error('test'), 400, 'some message');
var a: string = bo.output.headers['some header'];
// 4xx and data type
Boom.create(500, 'Internal server error', { timestamp: Date.now() });
const badRequestError = Boom.badRequest('message', {some: 'data'});
badRequestError.data.some;
const badRequestError2: Boom.BoomError = Boom.badImplementation('message');
Boom.badRequest('message', {some: 'data'});
Boom.unauthorized('message', <string | string[]> 'scheme', {some: 'data'});
Boom.unauthorized(null, <string | string[]> 'scheme', 'data');
Boom.paymentRequired('message', {some: 'data'});
Boom.forbidden('message', {some: 'data'});
Boom.notFound('message', {some: 'data'});
Boom.methodNotAllowed('message', {some: 'data'});
Boom.notAcceptable('message', {some: 'data'});
Boom.proxyAuthRequired('message', {some: 'data'});
Boom.clientTimeout('message', {some: 'data'});
Boom.conflict('message', {some: 'data'});
Boom.resourceGone('message', {some: 'data'});
Boom.lengthRequired('message', {some: 'data'});
Boom.preconditionFailed('message', {some: 'data'});
Boom.entityTooLarge('message', {some: 'data'});
Boom.uriTooLong('message', {some: 'data'});
Boom.unsupportedMediaType('message', {some: 'data'});
Boom.rangeNotSatisfiable('message', {some: 'data'});
Boom.expectationFailed('message', {some: 'data'});
Boom.teapot('message', {some: 'data'});
Boom.badData('message', {some: 'data'});
Boom.locked('message', {some: 'data'});
Boom.preconditionRequired('message', {some: 'data'});
Boom.tooManyRequests('message', {some: 'data'});
Boom.illegal('message', {some: 'data'});
const unauthorizedError1 = Boom.unauthorized('message', 'scheme', {some: 'attribute'});
unauthorizedError1.output.payload.attributes === { some: 'attribute', error: 'message' };
unauthorizedError1.output.headers === { 'WWW-Authenticate': 'scheme some="attribute", error="message"' };
Boom.badImplementation('message', {some: 'data'});
Boom.notImplemented('message', {some: 'data'});
Boom.badGateway('message', {some: 'data'});
Boom.serverUnavailable('message', {some: 'data'});
Boom.gatewayTimeout('message', {some: 'data'});
const unauthorizedError2 = Boom.unauthorized('message', ['scheme']);
unauthorizedError2.output.payload.attributes === undefined;
unauthorizedError2.output.headers === { 'WWW-Authenticate': 'scheme' };
Boom.unauthorized() as Error;
const unauthorizedError3 = Boom.unauthorized(null, 'scheme', 'attribute');
unauthorizedError3.output.payload.attributes === 'attribute';
unauthorizedError3.output.headers === { 'WWW-Authenticate': 'scheme attribute' };
const unauthorizedError4 = Boom.unauthorized(null, 'scheme', {some: 'attribute'});
unauthorizedError4.output.payload.attributes === { some: 'attribute' };
unauthorizedError4.output.headers === { 'WWW-Authenticate': 'scheme some="attribute"' };
const paymentRequiredError = Boom.paymentRequired('message', {some: 'data'});
paymentRequiredError.data.some;
const paymentRequiredError2: Boom.BoomError = Boom.paymentRequired('message');
const forbiddenError = Boom.forbidden('message', {some: 'data'});
forbiddenError.data.some;
const forbiddenError2: Boom.BoomError = Boom.forbidden('message');
const notFoundError = Boom.notFound('message', {some: 'data'});
notFoundError.data.some;
const notFoundError2: Boom.BoomError = Boom.notFound('message');
const methodNotAllowedError = Boom.methodNotAllowed('message', {some: 'data'});
methodNotAllowedError.data.some;
const methodNotAllowedError2: Boom.BoomError = Boom.methodNotAllowed('message');
const notAcceptableError = Boom.notAcceptable('message', {some: 'data'});
notAcceptableError.data.some;
const notAcceptableError2: Boom.BoomError = Boom.notAcceptable('message');
const proxyAuthRequiredError = Boom.proxyAuthRequired('message', {some: 'data'});
proxyAuthRequiredError.data.some;
const proxyAuthRequiredError2: Boom.BoomError = Boom.proxyAuthRequired('message');
const clientTimeoutError = Boom.clientTimeout('message', {some: 'data'});
clientTimeoutError.data.some;
const clientTimeoutError2: Boom.BoomError = Boom.clientTimeout('message');
const conflictError = Boom.conflict('message', {some: 'data'});
conflictError.data.some;
const resourceGoneError = Boom.resourceGone('message', {some: 'data'});
resourceGoneError.data.some;
const resourceGoneError2: Boom.BoomError = Boom.resourceGone('message');
const lengthRequiredError = Boom.lengthRequired('message', {some: 'data'});
lengthRequiredError.data.some;
const lengthRequiredError2: Boom.BoomError = Boom.lengthRequired('message');
const preconditionFailedError = Boom.preconditionFailed('message', {some: 'data'});
preconditionFailedError.data.some;
const preconditionFailedError2: Boom.BoomError = Boom.preconditionFailed('message');
const entityTooLargeError = Boom.entityTooLarge('message', {some: 'data'});
entityTooLargeError.data.some;
const entityTooLargeError2: Boom.BoomError = Boom.lengthRequired('message');
const uriTooLongError = Boom.uriTooLong('message', {some: 'data'});
uriTooLongError.data.some;
const uriTooLongError2: Boom.BoomError = Boom.uriTooLong('message');
const unsupportedMediaTypeError = Boom.unsupportedMediaType('message', {some: 'data'});
unsupportedMediaTypeError.data.some;
const unsupportedMediaTypeError2: Boom.BoomError = Boom.unsupportedMediaType('message');
const rangeNotSatisfiableError = Boom.rangeNotSatisfiable('message', {some: 'data'});
rangeNotSatisfiableError.data.some;
const rangeNotSatisfiableError2: Boom.BoomError = Boom.rangeNotSatisfiable('message');
const expectationFailedError = Boom.expectationFailed('message', {some: 'data'});
expectationFailedError.data.some;
const expectationFailedError2: Boom.BoomError = Boom.expectationFailed('message');
const teapotError = Boom.teapot('message', {some: 'data'});
teapotError.data.some;
const teapotError2: Boom.BoomError = Boom.teapot('message');
const badDataError = Boom.badData('message', {some: 'data'});
badDataError.data.some;
const badDataError2: Boom.BoomError = Boom.badData('message');
const lockedError = Boom.locked('message', {some: 'data'});
lockedError.data.some;
const lockedError2: Boom.BoomError = Boom.locked('message');
const preconditionRequiredError = Boom.preconditionRequired('message', {some: 'data'});
preconditionRequiredError.data.some;
const preconditionRequiredError2: Boom.BoomError = Boom.preconditionRequired('message');
const tooManyRequestsError = Boom.tooManyRequests('message', {some: 'data'});
tooManyRequestsError.data.some;
const tooManyRequestsError2: Boom.BoomError = Boom.tooManyRequests('message');
const illegalError = Boom.illegal('message', {some: 'data'});
illegalError.data.some;
const illegalError2: Boom.BoomError = Boom.illegal('message');
// 5xx and data type
const badImplementationError = Boom.badImplementation('message', {some: 'data'});
badImplementationError.data.some;
const badImplementationError2: Boom.BoomError = Boom.badImplementation('message');
const internalError = Boom.internal('message', {some: 'data'});
internalError.data.some;
const internalError2: Boom.BoomError = Boom.internal('message');
const notImplementedError = Boom.notImplemented('message', {some: 'data'});
notImplementedError.data.some;
const notImplementedError2: Boom.BoomError = Boom.notImplemented('message');
const badGatewayError = Boom.badGateway('message', {some: 'data'});
badGatewayError.data.some;
const badGatewayError2: Boom.BoomError = Boom.badGateway('message');
const serverUnavailableError = Boom.serverUnavailable('message', {some: 'data'});
serverUnavailableError.data.some;
const serverUnavailableError2: Boom.BoomError = Boom.serverUnavailable('message');
const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'});
gatewayTimeoutError.data.some;
const gatewayTimeoutError2: Boom.BoomError = Boom.gatewayTimeout('message');
// wrap and create
const wrappedError = Boom.wrap(new Error('test'), 400, 'some message');
const error1 = Boom.create(500, 'Internal server error', { timestamp: Date.now() });
error1.data.timestamp;
const error2: Boom.BoomError = Boom.create(500, 'Internal server error');
// type widen asserting
const unauthorizedError = Boom.unauthorized() as Error;
// status code and reformat
const error = Boom.badRequest('Cannot feed after midnight');
error.output.statusCode = 499; // Assign a custom error code
@@ -53,3 +163,30 @@ interface CustomPayload extends Boom.Payload {
}
(error.output.payload as CustomPayload).custom = 'abc_123';
/**
* Test assignment of custom error data:
*/
const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: 'Custom1', isCustom: true } as CustomData1);
const errorWithNoExplicitDataType: Boom.BoomError = errorWithData; // can assign to error without explicit data type
const errorWithExplicitType: Boom.BoomError<CustomData> = errorWithData; // can assign to union data type
const errorWithConcreteCustomData: Boom.BoomError<CustomData1> = errorWithData; // can assign to concrete data type
// assignment to CustomData2 would not be possible
// const errorWithConcreteCustomData2: Boom.BoomError<CustomData2> = errorWithData;
// Some complex error data types for testing purposes:
interface CustomDataBase {
isCustom: true;
}
interface CustomData1 extends CustomDataBase {
customType: 'Custom1';
custom1: string;
}
interface CustomData2 extends CustomDataBase {
customType: 'Custom2';
custom2: string;
}
type CustomData = CustomData1 | CustomData2;
+53 -35
View File
@@ -2,8 +2,7 @@
// Project: http://github.com/hapijs/boom
// Definitions by: Igor Rogatty <http://github.com/rogatty>, AJP <http://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
// TypeScript Version: 2.3
export = Boom;
@@ -13,7 +12,7 @@ declare namespace Boom {
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties:
* @see {@link https://github.com/hapijs/boom#boom}
*/
export interface BoomError extends Error {
export interface BoomError<Data = any> extends Error {
/** isBoom - if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** isServer - convenience bool indicating status code >= 500. */
@@ -26,6 +25,8 @@ declare namespace Boom {
reformat: () => string;
/** "If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object." mentioned in @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */
isMissing?: boolean;
/** https://github.com/hapijs/boom#createstatuscode-message-data and https://github.com/hapijs/boom/blob/v4.3.0/lib/index.js#L99 */
data: Data;
}
export interface Output {
@@ -36,6 +37,7 @@ declare namespace Boom {
/** payload - the formatted object used as the response payload (stringified). Can be directly manipulated but any changes will be lost if reformat() is called. Any content allowed and by default includes the following content: */
payload: Payload;
}
export interface Payload {
/** statusCode - the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
@@ -43,6 +45,11 @@ declare namespace Boom {
error: string;
/** message - the error message derived from error.message. */
message: string;
/**
* "Every key/value pair will be included ... in the response payload under the attributes key."
* [see docs](https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes)
*/
attributes?: any;
// Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload
// [anyContent: string]: any;
}
@@ -54,7 +61,7 @@ declare namespace Boom {
* @param message optional message string. If the error already has a message, it adds the message as a prefix. Defaults to no message.
* @see {@link https://github.com/hapijs/boom#wraperror-statuscode-message}
*/
export function wrap(error: Error, statusCode?: number, message?: string): BoomError;
export function wrap(error: Error, statusCode?: number, message?: string): BoomError<null>;
/**
* Generates an Error object with the boom decorations
@@ -63,7 +70,7 @@ declare namespace Boom {
* @param data additional error data set to error.data property.
* @see {@link https://github.com/hapijs/boom#createstatuscode-message-data}
*/
export function create(statusCode: number, message?: string, data?: any): BoomError;
export function create<Data = null>(statusCode: number, message?: string, data?: Data): BoomError<Data>;
// 4xx
/**
@@ -72,7 +79,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data}
*/
export function badRequest(message?: string, data?: any): BoomError;
export function badRequest<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 401 Unauthorized error
@@ -83,8 +90,10 @@ declare namespace Boom {
* @param attributes an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when scheme is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the attributes key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. null and undefined will be replaced with an empty string. If attributes is set, message will be used as the 'error' segment of the 'WWW-Authenticate' header. If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object.
* @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes}
*/
export function unauthorized(message?: string, scheme?: string | string[], attributes?: {[index: string]: string}): BoomError;
export function unauthorized(message?: null, scheme?: string | string[], attributes?: string): BoomError;
export function unauthorized(message?: string, scheme?: string, attributes?: {[index: string]: string}): BoomError<null>;
export function unauthorized(message?: string, scheme?: string[]): BoomError<null>;
export function unauthorized(message?: null, scheme?: string, attributes?: {[index: string]: string} | string): BoomError<null>;
export function unauthorized(message?: null, scheme?: string[]): BoomError<null>;
/**
* Returns a 402 Payment Required error
@@ -92,7 +101,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data}
*/
export function paymentRequired(message?: string, data?: any): BoomError;
export function paymentRequired<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 403 Forbidden error
@@ -100,7 +109,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data}
*/
export function forbidden(message?: string, data?: any): BoomError;
export function forbidden<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 404 Not Found error
@@ -108,7 +117,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data}
*/
export function notFound(message?: string, data?: any): BoomError;
export function notFound<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 405 Method Not Allowed error
@@ -117,7 +126,7 @@ declare namespace Boom {
* @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header.
* @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow}
*/
export function methodNotAllowed(message?: string, data?: any, allow?: string | string[]): BoomError;
export function methodNotAllowed<Data = null>(message?: string, data?: Data, allow?: string | string[]): BoomError<Data>;
/**
* Returns a 406 Not Acceptable error
@@ -125,7 +134,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data}
*/
export function notAcceptable(message?: string, data?: any): BoomError;
export function notAcceptable<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 407 Proxy Authentication Required error
@@ -133,7 +142,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data}
*/
export function proxyAuthRequired(message?: string, data?: any): BoomError;
export function proxyAuthRequired<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 408 Request Time-out error
@@ -141,7 +150,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data}
*/
export function clientTimeout(message?: string, data?: any): BoomError;
export function clientTimeout<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 409 Conflict error
@@ -149,7 +158,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomconflictmessage-data}
*/
export function conflict(message?: string, data?: any): BoomError;
export function conflict<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 410 Gone error
@@ -157,7 +166,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data}
*/
export function resourceGone(message?: string, data?: any): BoomError;
export function resourceGone<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 411 Length Required error
@@ -165,7 +174,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data}
*/
export function lengthRequired(message?: string, data?: any): BoomError;
export function lengthRequired<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 412 Precondition Failed error
@@ -173,7 +182,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data}
*/
export function preconditionFailed(message?: string, data?: any): BoomError;
export function preconditionFailed<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 413 Request Entity Too Large error
@@ -181,7 +190,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data}
*/
export function entityTooLarge(message?: string, data?: any): BoomError;
export function entityTooLarge<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 414 Request-URI Too Large error
@@ -189,7 +198,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data}
*/
export function uriTooLong(message?: string, data?: any): BoomError;
export function uriTooLong<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 415 Unsupported Media Type error
@@ -197,7 +206,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data}
*/
export function unsupportedMediaType(message?: string, data?: any): BoomError;
export function unsupportedMediaType<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 416 Requested Range Not Satisfiable error
@@ -205,7 +214,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data}
*/
export function rangeNotSatisfiable(message?: string, data?: any): BoomError;
export function rangeNotSatisfiable<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 417 Expectation Failed error
@@ -213,7 +222,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data}
*/
export function expectationFailed(message?: string, data?: any): BoomError;
export function expectationFailed<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 418 I'm a Teapot error
@@ -221,7 +230,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomteapotmessage-data}
*/
export function teapot(message?: string, data?: any): BoomError;
export function teapot<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 422 Unprocessable Entity error
@@ -229,7 +238,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombaddatamessage-data}
*/
export function badData(message?: string, data?: any): BoomError;
export function badData<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 423 Locked error
@@ -237,7 +246,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlockedmessage-data}
*/
export function locked(message?: string, data?: any): BoomError;
export function locked<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 428 Precondition Required error
@@ -245,7 +254,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data}
*/
export function preconditionRequired(message?: string, data?: any): BoomError;
export function preconditionRequired<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 429 Too Many Requests error
@@ -253,7 +262,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data}
*/
export function tooManyRequests(message?: string, data?: any): BoomError;
export function tooManyRequests<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 451 Unavailable For Legal Reasons error
@@ -261,7 +270,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomillegalmessage-data}
*/
export function illegal(message?: string, data?: any): BoomError;
export function illegal<Data = null>(message?: string, data?: Data): BoomError<Data>;
// 5xx
/**
@@ -271,7 +280,16 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal}
*/
export function badImplementation(message?: string, data?: any): BoomError;
export function badImplementation<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 500 Internal Server Error error
* Only 500 errors will hide your message from the end user. Your message is recorded in the server log.
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal}
*/
export function internal<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 501 Not Implemented error with your error message to the user
@@ -279,7 +297,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data}
*/
export function notImplemented(message?: string, data?: any): BoomError;
export function notImplemented<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 502 Bad Gateway error with your error message to the user
@@ -287,7 +305,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data}
*/
export function badGateway(message?: string, data?: any): BoomError;
export function badGateway<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 503 Service Unavailable error with your error message to the user
@@ -295,7 +313,7 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data}
*/
export function serverUnavailable(message?: string, data?: any): BoomError;
export function serverUnavailable<Data = null>(message?: string, data?: Data): BoomError<Data>;
/**
* Returns a 504 Gateway Time-out error with your error message to the user
@@ -303,5 +321,5 @@ declare namespace Boom {
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data}
*/
export function gatewayTimeout(message?: string, data?: any): BoomError;
export function gatewayTimeout<Data = null>(message?: string, data?: Data): BoomError<Data>;
}
+1 -1
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
+36 -8
View File
@@ -17,25 +17,28 @@
interface DatepickerOptions {
format?: string | DatepickerCustomFormatOptions;
weekStart?: number;
startDate?: any;
endDate?: any;
startDate?: Date|string;
endDate?: Date|string;
autoclose?: boolean;
startView?: number;
todayBtn?: any;
todayBtn?: boolean|"linked";
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
beforeShowDay?: (date: any) => any;
beforeShowDay?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowDayResponse;
beforeShowYear?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
beforeShowDecade?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
beforeShowCentury?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
calendarWeeks?: boolean;
clearBtn?: boolean;
daysOfWeekDisabled?: number[];
forceParse?: boolean;
inputs?: any[];
minViewMode?: any;
multidate?: any;
minViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium";
multidate?: boolean|number;
multidateSeparator?: string;
orientation?: string;
assumeNearbyYear?: any;
orientation?: "auto"|"left top"|"left bottom"|"right top"|"right bottom";
assumeNearbyYear?: boolean|number;
viewMode?: string;
templates?: any;
zIndexOffset?: number;
@@ -43,6 +46,28 @@ interface DatepickerOptions {
immediateUpdates?: boolean;
title?: string;
container?: string;
datesDisabled?:string|string[];
daysOfWeekHighlighted?:string|number[];
defaultViewDate?:Date|string|DatepickerViewDate;
updateViewDate?:boolean;
}
interface DatepickerViewDate {
year:number;
/** Month starting with 0 */
month:number;
/** Day of the month starting with 1 */
day:number;
}
interface DatepickerBeforeShowResponse {
enabled?:boolean;
classes?: string;
tooltip?: string;
}
interface DatepickerBeforeShowDayResponse extends DatepickerBeforeShowResponse {
content?: string;
}
interface DatepickerCustomFormatOptions {
@@ -52,7 +77,10 @@ interface DatepickerCustomFormatOptions {
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
dates: Date[];
format(ix?:number): string;
format(format?: string): string;
format(ix?:number, format?: string): string;
}
interface JQuery {
+21 -21
View File
@@ -337,16 +337,16 @@ export interface DatetimepickerOptions {
/** Shows the week of the year to the left of first day of the week.
* @default: false
*/
calendarWeeks?: boolean;
calendarWeeks?: boolean;
/** Using a Bootstraps collapse to switch between date/time pickers.
* @default: true
*/
collapse?: boolean;
collapse?: boolean;
/** Disables the section of days of the week, e.g. weekends.
* Accepts: array of numbers from 0-6
* @default: false
*/
daysOfWeekDisabled?: number[] | boolean;
daysOfWeekDisabled?: number[] | boolean;
/** Changes the heading of the datepicker when in "days" view.
* @default: "MMMM YYYY"
*/
@@ -358,14 +358,14 @@ export interface DatetimepickerOptions {
/** Sets the picker default date/time. Overrides useCurrent
* @default: false
*/
defaultDate?: boolean | moment.Moment | Date | string;
defaultDate?: boolean | moment.Moment | Date | string;
/** Disables selection of dates in the array, e.g. holidays
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true.
* eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true }
* https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499
*/
disabledDates?: boolean | Array<moment.Moment | Date | string> | any;
disabledDates?: boolean | Array<moment.Moment | Date | string> | any;
/** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true.
@@ -384,7 +384,7 @@ export interface DatetimepickerOptions {
* eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true }
* https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499
*/
enabledDates?: boolean | Array<moment.Moment | Date | string> | any;
enabledDates?: boolean | Array<moment.Moment | Date | string> | any;
/** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days
* @default: false
* IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true.
@@ -403,17 +403,17 @@ export interface DatetimepickerOptions {
/** See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker.
* @default: false
*/
format?: boolean | string | moment.MomentBuiltinFormat;
format?: boolean | string | moment.MomentBuiltinFormat;
/** Change the default icons for the pickers functions. */
icons?: Icons;
icons?: Icons;
/** Allow date picker show event to fire even when the associated input element has the readonly="readonly"property.
* @default: false
*/
ignoreReadonly?: boolean;
ignoreReadonly?: boolean;
/** Will display the picker inline without the need of a input field. This will also hide borders and shadows.
* @default: false
*/
inline?: boolean;
inline?: boolean;
/** Allows for custom events to fire on keyboard press.
* eg: keybinds: {
* up: (widget) => console.log(widget),
@@ -433,17 +433,17 @@ export interface DatetimepickerOptions {
/** See momentjs for valid locales. You must include moment-with-locales.js or a local js file.
* @default: moment.locale()
*/
locale?: string;
locale?: string;
/** Prevents date/time selections after this date.
* maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected.
* @default: false
*/
maxDate?: boolean | moment.Moment | Date | string;
maxDate?: boolean | moment.Moment | Date | string;
/** Prevents date/time selections before this date.
* minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected.
* @default: false
*/
minDate?: boolean | moment.Moment | Date | string;
minDate?: boolean | moment.Moment | Date | string;
/** Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago".
* {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate}
*/
@@ -452,7 +452,7 @@ export interface DatetimepickerOptions {
* Clicking the "Clear" button will set the calendar to null.
* @default: false
*/
showClear?: boolean;
showClear?: boolean;
/** Show the "Close" button in the icon toolbar.
* Clicking the "Close" button will call hide()
* @default: false
@@ -462,11 +462,11 @@ export interface DatetimepickerOptions {
* Clicking the "Today" button will set the calendar view and set the date to now.
* @default: false
*/
showTodayButton?: boolean;
showTodayButton?: boolean;
/** Shows the picker side by side when using the time and date together.
* @default: false
*/
sideBySide?: boolean;
sideBySide?: boolean;
/** Number of minutes the up/down arrow's will move the minutes value in the time picker
* @default: 1
*/
@@ -479,17 +479,17 @@ export interface DatetimepickerOptions {
/** Changes the placement of the icon toolbar.
* @default: "default"
*/
toolbarPlacement?: "default" | "top" | "bottom";
toolbarPlacement?: "default" | "top" | "bottom";
/** This will change the tooltips over each icon to a custom string */
tooltips?: Tooltips;
/** On show, will set the picker to the current date/time
* @default: true
*/
useCurrent?: boolean;
useCurrent?: boolean;
/** Defines if moment should use strict date parsing when considering a date to be valid
* @default: false
*/
useStrict?: boolean;
useStrict?: boolean;
/** This will change the viewDate without changing or setting the selected date.
* @default: false
*/
@@ -498,7 +498,7 @@ export interface DatetimepickerOptions {
* Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY
* @default: "days"
*/
viewMode?: "decades" | "years" | "months" | "days";
viewMode?: "decades" | "years" | "months" | "days";
/** On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative"
* @default: null
*/
@@ -520,7 +520,7 @@ export interface Icons {
/** default: "glyphicon glyphicon-screenshot" */
previous?: string;
/** default: "glyphicon glyphicon-chevron-right" */
time?: string;
time?: string;
/** default: "glyphicon glyphicon-chevron-down" */
today?: string;
/** default: "glyphicon glyphicon-chevron-up" */
+5
View File
@@ -7,6 +7,11 @@ function test_dataType() {
var typ = breeze.DataType.DateTime;
var nm = typ.getName();
var dv = typ.defaultValue;
var isDate = typ.isDate;
var isFloat = typ.isFloat;
var isInteger = typ.isInteger;
var isNumeric = typ.isNumeric;
var qjod = typ.quoteJsonOData;
var symbs = breeze.DataType.getSymbols();
var x = typ.parentEnum === <breeze.core.IEnum> breeze.DataType;
var isFalse = breeze.DataType.contains(breeze.DataType.Double);
+36 -26
View File
@@ -16,7 +16,7 @@
// Updated Jul 15 2016 - Added methods to JsonResultsAdapter - Steve Schmitt
// Updated Sep 23 2016 - Added core methods
// Updated March 5 2017 - Eliminate promises.IPromise<T> and replace with Promise<T>
// Updated Apr 28 2017 - Fixed DataType
declare namespace breeze.core {
export interface ErrorCallback {
@@ -266,9 +266,33 @@ declare namespace breeze {
export class DataTypeSymbol extends breeze.core.EnumSymbol {
defaultValue: any;
isNumeric: boolean;
isDate: boolean;
isDate?: boolean;
isFloat?: boolean;
isInteger?: boolean;
isNumeric?: boolean;
quoteJsonOData?: boolean;
validatorCtor: (context: any) => Validator;
/** Function to convert a value from string to this DataType. Note that this will be called each time a property is changed, so make it fast. */
parse?: (val: any, sourceTypeName?: string) => any;
/** Function to format this DataType for OData queries. */
fmtOData: (val: any) => any;
/** Optional function to get the next value for key generation, if this datatype is used as a key. Uses an internal table of previous values. */
getNext?: () => any;
/** Optional function to normalize a data value for comparison, if its value cannot be used directly. Note that this will be called each time a property is changed, so make it fast. */
normalize?: (val: any) => any;
/** Optional function to get the next value when the datatype is used as a concurrency property. */
getConcurrencyValue?: (val: any) => any;
/** Optional function to convert a raw (server) value from string to this DataType. */
parseRawValue?: (val: any) => any;
}
export interface DataType extends breeze.core.IEnum {
Binary: DataTypeSymbol;
Boolean: DataTypeSymbol;
@@ -285,30 +309,16 @@ declare namespace breeze {
String: DataTypeSymbol;
Time: DataTypeSymbol;
Undefined: DataTypeSymbol;
toDataType(typeName: string): DataTypeSymbol;
constants: { nextNumber: number, nextNumberIncrement: number, stringPrefix: string };
fromEdmDataType(typeName: string): DataTypeSymbol;
fromValue(val: any): DataTypeSymbol;
getComparableFn(dataType: DataTypeSymbol): (value: any) => any;
parseDateAsUTC(source: any): Date;
parseDateFromServer(date: any): Date;
defaultValue: any;
isNumeric: boolean;
isInteger: boolean;
/** Function to convert a value from string to this DataType. Note that this will be called each time a property is changed, so make it fast. */
parse: (val: any, sourceTypeName: string) => any;
/** Function to format this DataType for OData queries. */
fmtOData: (val: any) => any;
/** Optional function to get the next value for key generation, if this datatype is used as a key. Uses an internal table of previous values. */
getNext?: () => any;
/** Optional function to normalize a data value for comparison, if its value cannot be used directly. Note that this will be called each time a property is changed, so make it fast. */
normalize?: (val: any) => any;
/** Optional function to get the next value when the datatype is used as a concurrency property. */
getConcurrencyValue?: (val: any) => any;
/** Optional function to convert a raw (server) value from string to this DataType. */
parseRawValue?: (val: any) => any;
parseRawValue(val: any, dataType?: DataTypeSymbol): any;
parseTimeFromServer(source: any): string;
}
export var DataType: DataType;
+7
View File
@@ -1,6 +1,7 @@
// Type definitions for browser-sync
// Project: http://www.browsersync.io/
// Definitions by: Asana <https://asana.com>, Joe Skeen <http://github.com/joeskeen>
// Thomas "Thasmo" Deinhamer <https://thasmo.com/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="chokidar"/>
@@ -134,6 +135,12 @@ declare namespace browserSync {
* Default: default
*/
browser?: string | string[];
/**
* Add HTTP access control (CORS) headers to assets served by Browsersync.
* Default: false
* Note: requires at least version 2.16.0
*/
cors?: boolean;
/**
* Requires an internet connection - useful for services such as Typekit as it allows you to configure
* domains such as *.xip.io in your kit settings
+12
View File
@@ -1,6 +1,7 @@
import browserify = require("browserify");
import fs = require("fs");
import stream = require('stream');
import insertGlobals = require("insert-module-globals");
var bNoArg = browserify();
@@ -47,4 +48,15 @@ var record_pipeline = b.pipeline.get('record');
b.bundle().pipe(process.stdout);
var argv = { igv: "__filename,__dirname" };
var insertGlobalVars: insertGlobals.VarsOption = {};
var wantedGlobalVars = argv.igv.split(',');
Object.keys(insertGlobals.vars).forEach((x) => {
if (wantedGlobalVars.indexOf(x) === -1) {
insertGlobalVars[x] = undefined;
}
});
var b = browserify('./browser/main.js', {
insertGlobalVars: insertGlobalVars
});
+5 -3
View File
@@ -1,10 +1,12 @@
// Type definitions for Browserify v12.0.1
// Type definitions for Browserify 12.0
// Project: http://browserify.org/
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>, John Vilk <https://github.com/jvilk>
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>, John Vilk <https://github.com/jvilk>, Leonard Thieu <https://github.com/leonard-thieu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import insertGlobals = require('insert-module-globals');
declare var browserify: browserify.BrowserifyConstructor;
export = browserify;
@@ -74,7 +76,7 @@ interface Options {
// The global export will be sanitized and camel cased.
standalone?: string;
// will be passed to insert-module-globals as the opts.vars parameter.
insertGlobalVars?: {[globalName: string]: (file: string, basedir: string) => any};
insertGlobalVars?: insertGlobals.VarsOption;
// defaults to 'require' in expose mode but you can use another name.
externalRequireName?: string;
}
+1 -1
View File
@@ -8,5 +8,5 @@ declare class PostBuffer extends BufferStream {
/** set a callback to get all post data from a http server request */
onEnd(callback: (data: any) => void): void;
/** pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe */
pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream;
pipe(stream: NodeJS.WritableStream, options?: { end?: boolean }): NodeJS.ReadableStream;
}
@@ -0,0 +1,9 @@
import { createAdapter } from "bunyan-winston-adapter";
import { Logger, LoggerInstance, transports } from "winston";
const logger = new Logger();
const mapping = {
trace: 'silly'
};
const adapterA = createAdapter(logger);
const adapterB = createAdapter(logger, mapping);
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for bunyan-winston-adapter 0.2
// Project: https://github.com/gluwer/bunyan-winston-adapter
// Definitions by: Steve Hipwell <https://github.com/stevehipwell>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as bunyan from "bunyan";
import { LoggerInstance } from "winston";
export function createAdapter(logger: LoggerInstance, mapping?: any): bunyan;
@@ -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",
"bunyan-winston-adapter-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+17 -19
View File
@@ -1,16 +1,15 @@
import Logger = require('bunyan');
var ringBufferOptions: Logger.RingBufferOptions = {
let ringBufferOptions: Logger.RingBufferOptions = {
limit: 100
};
var ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions);
let ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions);
ringBuffer.write("hello");
ringBuffer.end();
ringBuffer.destroy();
ringBuffer.destroySoon();
var level: number;
let level: number;
level = Logger.resolveLevel("trace");
level = Logger.resolveLevel("debug");
level = Logger.resolveLevel("info");
@@ -24,7 +23,7 @@ level = Logger.resolveLevel(Logger.WARN);
level = Logger.resolveLevel(Logger.ERROR);
level = Logger.resolveLevel(Logger.FATAL);
var options: Logger.LoggerOptions = {
let options: Logger.LoggerOptions = {
name: 'test-logger',
serializers: Logger.stdSerializers,
streams: [{
@@ -54,13 +53,13 @@ var options: Logger.LoggerOptions = {
}]
};
var log = Logger.createLogger(options);
let log = Logger.createLogger(options);
var customSerializer = function(anything: any) {
return { obj: anything};
let customSerializer = (anything: any) => {
return { obj: anything };
};
log.addSerializers({anything: customSerializer});
log.addSerializers({ anything: customSerializer });
log.addSerializers(Logger.stdSerializers);
log.addSerializers(
{
@@ -70,9 +69,9 @@ log.addSerializers(
}
);
var child = log.child({name: 'child'});
let child = log.child({ name: 'child' });
child.reopenFileStreams();
log.addStream({path: '/dev/null'});
log.addStream({ path: '/dev/null' });
child.level(Logger.DEBUG);
child.level('debug');
child.levels(0, Logger.ERROR);
@@ -80,9 +79,9 @@ child.levels(0, 'error');
child.levels('stream1', Logger.FATAL);
child.levels('stream1', 'fatal');
var buffer = new Buffer(0);
var error = new Error('');
var object = {
let buffer = new Buffer(0);
let error = new Error('');
let object = {
test: 123
};
@@ -117,12 +116,11 @@ log.fatal(error);
log.fatal(object);
log.fatal('Hello, %s', 'world!');
var recursive: any = {
let recursive: any = {
hello: 'world',
whats: {
huh: recursive
}
}
whats: {}
};
recursive.whats['huh'] = recursive;
JSON.stringify(recursive, Logger.safeCycles());
+117 -124
View File
@@ -1,4 +1,4 @@
// Type definitions for node-bunyan
// Type definitions for bunyan 1.8
// Project: https://github.com/trentm/node-bunyan
// Definitions by: Alex Mikhalev <https://github.com/amikhalev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -10,21 +10,24 @@ import { EventEmitter } from 'events';
declare class Logger extends EventEmitter {
constructor(options: Logger.LoggerOptions);
addStream(stream: Logger.Stream): void;
addSerializers(serializers: Logger.Serializers | Logger.StdSerializers): void;
child(options: Logger.LoggerOptions, simple?: boolean): Logger;
child(obj: Object, simple?: boolean): Logger;
addSerializers(serializers: Logger.Serializers): void;
child(options: Object, simple?: boolean): Logger;
reopenFileStreams(): void;
level(): string | number;
level(value: number | string): void;
levels(name: number | string, value: number | string): void;
level(): number;
level(value: Logger.LogLevel): void;
levels(): number[];
levels(name: number | string): number;
levels(name: number | string, value: Logger.LogLevel): void;
fields: any;
src: boolean;
/* tslint:disable:unified-signatures */
/**
* Returns a boolean: is the `trace` level enabled?
*
*
* This is equivalent to `log.isTraceEnabled()` or `log.isEnabledFor(TRACE)` in log4j.
*/
trace(): boolean;
@@ -35,27 +38,25 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
trace(error: Error, format?: any, ...params: any[]): void;
trace(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
trace(format: string | number, ...params: any[]): void;
trace(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
trace(obj: Object, format?: any, ...params: any[]): void;
trace(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
trace(format: any, ...params: any[]): void;
/**
* Returns a boolean: is the `debug` level enabled?
*
*
* This is equivalent to `log.isDebugEnabled()` or `log.isEnabledFor(DEBUG)` in log4j.
*/
debug(): boolean;
@@ -66,27 +67,25 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
debug(error: Error, format?: any, ...params: any[]): void;
debug(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
debug(format: string | number, ...params: any[]): void;
debug(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
debug(obj: Object, format?: any, ...params: any[]): void;
debug(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
debug(format: any, ...params: any[]): void;
/**
* Returns a boolean: is the `info` level enabled?
*
*
* This is equivalent to `log.isInfoEnabled()` or `log.isEnabledFor(INFO)` in log4j.
*/
info(): boolean;
@@ -97,27 +96,25 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
info(error: Error, format?: any, ...params: any[]): void;
info(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
info(format: string | number, ...params: any[]): void;
info(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
info(obj: Object, format?: any, ...params: any[]): void;
info(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
info(format: any, ...params: any[]): void;
/**
* Returns a boolean: is the `warn` level enabled?
*
*
* This is equivalent to `log.isWarnEnabled()` or `log.isEnabledFor(WARN)` in log4j.
*/
warn(): boolean;
@@ -128,27 +125,25 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
warn(error: Error, format?: any, ...params: any[]): void;
warn(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
warn(format: string | number, ...params: any[]): void;
warn(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
warn(obj: Object, format?: any, ...params: any[]): void;
warn(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
warn(format: any, ...params: any[]): void;
/**
* Returns a boolean: is the `error` level enabled?
*
*
* This is equivalent to `log.isErrorEnabled()` or `log.isEnabledFor(ERROR)` in log4j.
*/
error(): boolean;
@@ -159,27 +154,25 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
error(error: Error, format?: any, ...params: any[]): void;
error(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
error(format: string | number, ...params: any[]): void;
error(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
error(obj: Object, format?: any, ...params: any[]): void;
error(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
error(format: any, ...params: any[]): void;
/**
* Returns a boolean: is the `fatal` level enabled?
*
*
* This is equivalent to `log.isFatalEnabled()` or `log.isEnabledFor(FATAL)` in log4j.
*/
fatal(): boolean;
@@ -190,90 +183,90 @@ declare class Logger extends EventEmitter {
* (including the stack) and sets `msg` to the exception
* message or you can specify the `msg`.
*/
fatal(error: Error, format?: any, ...params: any[]): void;
fatal(buffer: Buffer, format?: any, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
fatal(format: string | number, ...params: any[]): void;
fatal(error: Error, ...params: any[]): void;
/**
* The first field can optionally be a "fields" object, which
* is merged into the log record.
*
*
* To pass in an Error *and* other fields, use the `err`
* field name for the Error instance.
*/
fatal(obj: Object, format?: any, ...params: any[]): void;
fatal(obj: Object, ...params: any[]): void;
/**
* Uses `util.format` for msg formatting.
*/
fatal(format: any, ...params: any[]): void;
/* tslint:enable:unified-signatures */
}
declare namespace Logger {
const TRACE: number;
const DEBUG: number;
const INFO: number;
const WARN: number;
const ERROR: number;
const FATAL: number;
const TRACE: number;
const DEBUG: number;
const INFO: number;
const WARN: number;
const ERROR: number;
const FATAL: number;
const stdSerializers: StdSerializers;
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number;
function createLogger(options: LoggerOptions): Logger;
const stdSerializers: StdSerializers;
function safeCycles(): (key: string, value: any) => any;
function createLogger(options: LoggerOptions): Logger;
function resolveLevel(value: number | string): number;
function safeCycles(): (key: string, value: any) => any;
interface Stream {
type?: string;
level?: number | string;
path?: string;
stream?: NodeJS.WritableStream | Stream;
closeOnExit?: boolean;
period?: string;
count?: number;
}
function resolveLevel(value: LogLevel): number;
interface LoggerOptions {
name: string;
streams?: Stream[];
level?: string | number;
stream?: NodeJS.WritableStream;
serializers?: Serializers | StdSerializers;
src?: boolean;
[custom: string]: any;
}
interface Stream {
type?: string;
level?: LogLevel;
path?: string;
stream?: NodeJS.WritableStream | Stream;
closeOnExit?: boolean;
period?: string;
count?: number;
}
interface Serializer {
(input:any): any;
}
interface LoggerOptions {
name: string;
streams?: Stream[];
level?: LogLevel;
stream?: NodeJS.WritableStream;
serializers?: Serializers;
src?: boolean;
[custom: string]: any;
}
interface Serializers {
[key: string]: Serializer
}
type Serializer = (input: any) => any;
interface StdSerializers {
err: Serializer;
res: Serializer;
req: Serializer;
}
interface Serializers {
[key: string]: Serializer;
}
interface RingBufferOptions {
limit?: number;
}
interface StdSerializers extends Serializers {
err: Serializer;
res: Serializer;
req: Serializer;
}
class RingBuffer extends EventEmitter {
constructor(options: RingBufferOptions);
interface RingBufferOptions {
limit?: number;
}
writable: boolean;
records: any[];
class RingBuffer extends EventEmitter implements NodeJS.WritableStream {
constructor(options: RingBufferOptions);
write(record: any): void;
end(record?: any): void;
destroy(): void;
destroySoon(): void;
}
writable: boolean;
records: any[];
write(record: any): boolean;
end(record?: any): void;
destroy(): void;
destroySoon(): void;
}
}
export = Logger;

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