Merge branch 'master' of github.com:DefinitelyTyped/DefinitelyTyped into chrome-updates

This commit is contained in:
Nikolai Ommundsen
2018-08-24 11:12:59 +02:00
458 changed files with 24917 additions and 15469 deletions
+3 -3
View File
@@ -1567,7 +1567,7 @@
/types/hapi/v12/ @jasonswearingen
/types/hapi/v15/ @jasonswearingen
/types/hapi/v16/ @jasonswearingen @AJamesPhillips
/types/hapi/ @BorntraegerMarc @rafaelsouzaf @jhsimms @SimonSchick
/types/hapi/ @rafaelsouzaf @jhsimms @SimonSchick
/types/hapi-auth-basic/ @AJamesPhillips @saboya
/types/hapi-auth-jwt2/v7/ @warrenseymour
/types/hapi-auth-jwt2/ @warrenseymour @SimonSchick
@@ -3576,8 +3576,8 @@
/types/react-native-vector-icons/ @iRoachie @timwangdev
/types/react-native-version-number/ @VincentLanglet
/types/react-native-video/ @huhuanming
/types/react-navigation/v1/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @robertohuertasm @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi
/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @robertohuertasm @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi @magrinj @TizioFittizio @stigi
/types/react-navigation/v1/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi
/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi @magrinj @TizioFittizio @stigi
/types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar
/types/react-notification-system-redux/ @LKay
/types/react-notify-toast/ @klaascuvelier
+12 -6
View File
@@ -156,12 +156,6 @@
"sourceRepoURL": "https://github.com/brianloveswords/base64url",
"asOfVersion": "2.0.0"
},
{
"libraryName": "better-scroll",
"typingsPackageName": "better-scroll",
"sourceRepoURL": "https://github.com/ustbhuangyi/better-scroll",
"asOfVersion": "1.5.0"
},
{
"libraryName": "BigInteger.js",
"typingsPackageName": "big-integer",
@@ -570,6 +564,12 @@
"sourceRepoURL": "https://github.com/acdlite/flux-standard-action",
"asOfVersion": "1.1.0"
},
{
"libraryName": "fork-ts-checker-webpack-plugin",
"typingsPackageName": "fork-ts-checker-webpack-plugin",
"sourceRepoURL": "https://github.com/Realytics/fork-ts-checker-webpack-plugin",
"asOfVersion": "0.4.5"
},
{
"libraryName": "Foundation Sites",
"typingsPackageName": "foundation-sites",
@@ -1530,6 +1530,12 @@
"sourceRepoURL": "https://github.com/samchon/tstl",
"asOfVersion": "1.5.7"
},
{
"libraryName": "typed.js",
"typingsPackageName": "typed.js",
"sourceRepoURL": "https://github.com/mattboldt/typed.js",
"asOfVersion": "2.0.9"
},
{
"libraryName": "TypeScript",
"typingsPackageName": "typescript",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"private": true,
"name": "definitely-typed",
"version": "0.0.2",
"version": "0.0.3",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped",
"repository": {
"type": "git",
+8
View File
@@ -1776,6 +1776,14 @@ declare namespace algoliasearch {
facets?: {
[facetName: string]: { [facetValue: string]: number };
};
facets_stats?: {
[facetName: string]: {
avg: number,
max: number,
min: number,
sum: number,
};
};
}
interface MultiResponse {
+9
View File
@@ -4,6 +4,7 @@
// Haroen Viaene <https://github.com/haroenv>
// Aurélien Hervé <https://github.com/aherve>
// Samuel Vaillant <https://github.com/samouss>
// Claas Brüggemann <https://github.com/ClaasBrueggemann>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -570,6 +571,14 @@ declare namespace algoliasearch {
facets?: {
[facetName: string]: { [facetValue: string]: number };
};
facets_stats?: {
[facetName: string]: {
avg: number,
max: number,
min: number,
sum: number,
};
};
}
interface MultiResponse {
+14
View File
@@ -311,8 +311,10 @@ namespace TestQ {
}
const abcObject: AbcObject = null;
const abcObjectPromise: angular.IPromise<AbcObject> = null;
const abcObjectPromiseLike: PromiseLike<AbcObject> = null;
const efObject: EfObject = null;
const efObjectPromise: angular.IPromise<EfObject> = null;
const efObjectPromiseLike: PromiseLike<EfObject> = null;
const ghObject: GhObject = null;
const ghObjectPromise: angular.IPromise<GhObject> = null;
@@ -404,6 +406,7 @@ namespace TestQ {
result = $q.when<AbcObject>(abcObject);
result = $q.when<AbcObject>(abcObjectPromise);
result = $q.when<AbcObject>(abcObjectPromiseLike);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObject);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObject, (any) => any);
@@ -416,10 +419,21 @@ namespace TestQ {
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObjectPromise);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObjectPromise, (any) => any);
result = $q.when<AbcObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject, (any) => ghObject);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject, (any) => ghObject);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject, (any) => ghObject, (any) => any);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject, (any) => ghObjectPromise);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromiseLike, (result: EfObject) => abcObject, (any) => ghObjectPromise, (any) => any);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromise);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromise, (any) => any);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromise, (any) => any, (any) => any);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromiseLike);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromiseLike, (any) => any);
result = $q.when<AbcObject, EfObject>(efObject, (result: EfObject) => abcObjectPromiseLike, (any) => any, (any) => any);
result = $q.when<AbcObject, EfObject>(efObjectPromise, (result: EfObject) => abcObjectPromise);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObject);
resultOther = $q.when<AbcObject, GhObject, EfObject>(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObject, (any) => any);
+7 -7
View File
@@ -1137,12 +1137,12 @@ declare namespace angular {
*
* @param value Value or a promise
*/
resolve<T>(value: IPromise<T>|T): IPromise<T>;
resolve<T>(value: PromiseLike<T>|T): IPromise<T>;
/**
* @deprecated Since TS 2.4, inference is stricter and no longer produces the desired type when T1 !== T2.
* To use resolve with two different types, pass a union type to the single-type-argument overload.
*/
resolve<T1, T2>(value: IPromise<T1>|T2): IPromise<T1|T2>;
resolve<T1, T2>(value: PromiseLike<T1>|T2): IPromise<T1|T2>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*/
@@ -1152,11 +1152,11 @@ declare namespace angular {
*
* @param value Value or a promise
*/
when<T>(value: IPromise<T>|T): IPromise<T>;
when<T1, T2>(value: IPromise<T1>|T2): IPromise<T1|T2>;
when<TResult, T>(value: IPromise<T>|T, successCallback: (promiseValue: T) => IPromise<TResult>|TResult): IPromise<TResult>;
when<TResult, T>(value: T, successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise<TResult>;
when<TResult, TResult2, T>(value: IPromise<T>, successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback: (reason: any) => TResult2 | IPromise<TResult2>, notifyCallback?: (state: any) => any): IPromise<TResult | TResult2>;
when<T>(value: PromiseLike<T>|T): IPromise<T>;
when<T1, T2>(value: PromiseLike<T1>|T2): IPromise<T1|T2>;
when<TResult, T>(value: PromiseLike<T>|T, successCallback: (promiseValue: T) => PromiseLike<TResult>|TResult): IPromise<TResult>;
when<TResult, T>(value: T, successCallback: (promiseValue: T) => PromiseLike<TResult>|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise<TResult>;
when<TResult, TResult2, T>(value: PromiseLike<T>, successCallback: (promiseValue: T) => PromiseLike<TResult>|TResult, errorCallback: (reason: any) => TResult2 | PromiseLike<TResult2>, notifyCallback?: (state: any) => any): IPromise<TResult | TResult2>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*/
@@ -17,17 +17,24 @@ const config: Microsoft.ApplicationInsights.IConfig = {
autoTrackPageVisitTime: true,
disableExceptionTracking: false,
disableAjaxTracking: false,
disableFetchTracking: true,
overridePageViewDuration: false,
maxAjaxCallsPerView: -1,
disableDataLossAnalysis: true,
disableCorrelationHeaders: true,
correlationHeaderExcludedDomains: [],
disableFlushOnBeforeUnload: false,
enableSessionStorageBuffer: false,
cookieDomain: "",
isCookieUseDisabled: true,
isRetryDisabled: true,
isPerfAnalyzerEnabled: true,
isStorageUseDisabled: true
url: "url",
isStorageUseDisabled: true,
isBeaconApiDisabled: false,
sdkExtension: "sdkExtension",
isBrowserLinkTrackingEnabled: false,
appId: "appId",
enableCorsCorrelation: false
};
appInsights = {
@@ -175,3 +182,8 @@ const traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", nu
const traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
const traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);
// UtilHelpers
let Util: typeof Microsoft.ApplicationInsights.UtilHelpers;
Util.newId();
+15 -1
View File
@@ -1,6 +1,7 @@
// Type definitions for ApplicationInsights-JS 1.0
// Project: https://github.com/Microsoft/ApplicationInsights-JS
// Definitions by: Kamil Szostak <https://github.com/kamilszostak>
// Mark Wolff <https://github.com/markwolff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module AI {
@@ -560,19 +561,24 @@ declare module Microsoft.ApplicationInsights {
samplingPercentage?: number;
autoTrackPageVisitTime?: boolean;
disableAjaxTracking?: boolean;
disableFetchTracking?: boolean;
overridePageViewDuration?: boolean;
maxAjaxCallsPerView?: number;
disableDataLossAnalysis?: boolean;
disableCorrelationHeaders?: boolean;
correlationHeaderExcludedDomains?: string[];
disableFlushOnBeforeUnload?: boolean;
enableSessionStorageBuffer?: boolean;
isCookieUseDisabled?: boolean;
cookieDomain?: string;
isRetryDisabled?: boolean;
isPerfAnalyzerEnabled?: boolean;
url?: string;
isStorageUseDisabled?: boolean;
isBeaconApiDisabled?: boolean;
sdkExtension?: string;
isBrowserLinkTrackingEnabled?: boolean;
appId?: string;
enableCorsCorrelation?: boolean;
}
/**
@@ -793,10 +799,18 @@ declare module Microsoft.ApplicationInsights {
*/
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any;
}
class UtilHelpers {
/**
* Generate a random ID string
*/
static newId(): string;
}
}
declare module 'applicationinsights-js' {
const AppInsights: Microsoft.ApplicationInsights.IAppInsights;
const Util: typeof Microsoft.ApplicationInsights.UtilHelpers;
}
declare var appInsights: Microsoft.ApplicationInsights.IAppInsights;
+1
View File
@@ -762,6 +762,7 @@ export interface AuthorizeOptions {
audience?: string;
language?: string;
prompt?: string;
mode?: "login" | "signUp";
}
export interface CheckSessionOptions extends AuthorizeOptions {
+1
View File
@@ -90,6 +90,7 @@ const themeOptions : Auth0LockConstructorOptions = {
icon: 'http://baz.com/icon.png'
}
},
hideMainScreenTitle: false,
labeledSubmitButton: false,
logo: "https://example.com/assets/logo.png",
primaryColor: "green"
+2
View File
@@ -3,6 +3,7 @@
// Definitions by: Brian Caruso <https://github.com/carusology>
// Dan Caddigan <https://github.com/goldcaddy77>
// Larry Faudree <https://github.com/lfaudreejr>
// Will Caulfield <https://github.com/willcaul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js" />
@@ -75,6 +76,7 @@ interface Auth0LockThemeButtonOptions {
interface Auth0LockThemeOptions {
authButtons?: Auth0LockThemeButtonOptions;
hideMainScreenTitle?: boolean;
labeledSubmitButton?: boolean;
logo?: string;
primaryColor?: string;
+131
View File
@@ -0,0 +1,131 @@
import Queue = require('better-queue');
interface TestTask {
taskId: string;
taskPayload: any;
}
interface TestResult {
some: string;
}
new Queue((task) => {
const test = task.anything;
console.log(task);
});
new Queue((task: TestTask[]) => {
const test = task[0].taskId;
console.log(task);
});
new Queue<TestTask>((task: TestTask, cb) => {
const id = task.taskId;
cb(null, 'result');
cb();
}, {});
new Queue<TestTask, TestResult>({
process(task: TestTask, cb) {
const id = task.taskId;
cb(null, { some: 'prop' });
},
filter(task, cb) {
const id = task.taskId;
cb(null, task);
},
merge(oldTask, newTask, cb) {
const oldId = oldTask.taskId;
const newId = newTask.taskId;
cb(null, newTask);
},
priority(task, cb) {
const id = task.taskId;
cb(null, 10);
},
precondition(cb) {
cb(null, true);
},
afterProcessDelay: 1000,
autoResume: true,
batchDelay: 123,
batchDelayTimeout: 123,
batchSize: 123,
cancelIfRunning: true,
concurrent: 123,
failTaskOnProcessException: true,
filo: true,
id: 'taskId',
maxRetries: 1,
maxTimeout: 1,
retryDelay: 1,
storeMaxRetries: 1,
storeRetryTimeout: 1,
preconditionRetryTimeout: 1,
store: 'test'
});
new Queue<TestTask, TestResult>({
process(task: TestTask[], cb) {
const firstId = task[0].taskId;
cb(null, { some: 'prop' });
}
});
new Queue<TestTask, TestResult>(() => { }, {
id(task, cb) {
const id = task.taskId;
cb(null, 'taskId');
}
});
new Queue<TestTask, TestResult>(() => { }, {
store: {
type: 'test'
}
});
const q = new Queue<TestTask, TestResult>(() => {});
const testTask = {taskId: '', taskPayload: ''};
q.push(testTask);
q.push(testTask, (error, result) => {});
q.cancel('id', () => {});
class TestStore implements Queue.Store<TestTask> {
connect(cb: (error: any, length: number) => void) {
cb(null, 1);
}
getTask(taskId: any, cb: (error: any, task: TestTask) => void) {
cb(null, { taskId: '', taskPayload: '' });
}
deleteTask(taskId: any, cb: () => void) {
cb();
}
putTask(taskId: any, task: TestTask, priority: number, cb: (error: any) => void) {
cb(null);
}
takeFirstN(n: number, cb: (error: any, lockId: string) => void) {
cb(null, '');
}
takeLastN(n: number, cb: (error: any, lockId: string) => void) {
cb(null, '');
}
getLock(lockId: string, cb: (error: any, tasks: { [taskId: string]: TestTask }) => void) {
cb(null, {
id: { taskId: 'id', taskPayload: 'payload' }
});
}
releaseLock(lockId: string, cb: (error: any) => void) {
cb(null);
}
}
+136
View File
@@ -0,0 +1,136 @@
// Type definitions for better-queue 3.8
// Project: https://github.com/diamondio/better-queue
// Definitions by: Ostap Nagovitsyn <https://github.com/maozedong>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/* =================== USAGE ===================
import * as Queue from "better-queue";
var queue = new Queue(...);
=============================================== */
/// <reference types="node" />
declare class BetterQueue<T = any, K = any> extends NodeJS.EventEmitter {
constructor(options: BetterQueue.QueueOptions<T, K>);
constructor(process: BetterQueue.ProcessFunction<T, K>, options?: Partial<BetterQueue.QueueOptions<T, K>>);
push(task: T, cb?: (err: any, result: K) => void): BetterQueue.Ticket;
cancel(taskId: any, cb?: () => void): void;
pause(): void;
resume(): void;
destroy(cb: () => void): void;
use(store: BetterQueue.Store<T>): void;
getStats(): BetterQueue.QueueStats;
resetStats(): void;
on(event: 'task_finish', listener: (taskId: any, result: K) => void): this;
on(event: 'task_failed', listener: (taskId: any, errorMessage: string) => void): this;
on(event: 'task_progress', listener: (taskId: any, completed: number, total: number) => void): this;
on(event: BetterQueue.QueueEvent, listener: (...args: any[]) => void): this;
}
declare namespace BetterQueue {
interface QueueOptions<T, K> {
process: ProcessFunction<T, K>;
filter?(task: T, cb: (error: any, task: T) => void): void;
merge?(oldTask: T, newTask: T, cb: (error: any, mergedTask: T) => void): void;
priority?(task: T, cb: (error: any, priority: number) => void): void;
precondition?(cb: (error: any, passOrFail: boolean) => void): void;
id?: keyof T | ((task: T, cb: (error: any, id: keyof T) => void) => void);
cancelIfRunning?: boolean;
autoResume?: boolean;
failTaskOnProcessException?: boolean;
filo?: boolean;
batchSize?: number;
batchDelay?: number;
batchDelayTimeout?: number;
concurrent?: number;
maxTimeout?: number;
afterProcessDelay?: number;
maxRetries?: number;
retryDelay?: number;
storeMaxRetries?: number;
storeRetryTimeout?: number;
preconditionRetryTimeout?: number;
store?: string | StoreOptions | Store<T>;
}
// TODO reflect task types somehow (task: T | T[])
type ProcessFunction<T, K> = (task: any, cb: ProcessFunctionCb<K>) => void;
type ProcessFunctionCb<K> = (error?: any, result?: K) => void;
type QueueEvent =
'task_queued'
| 'task_accepted'
| 'task_started'
| 'task_finish'
| 'task_failed'
| 'task_progress'
| 'batch_finish'
| 'batch_failed'
| 'batch_progress'
| 'error';
type TicketEvent =
'accept'
| 'queued'
| 'started'
| 'progress'
| 'finish'
| 'failed'
| 'error';
interface Store<T> {
connect(cb: (error: any, length: number) => void): void;
getTask(taskId: any, cb: (error: any, task: T) => void): void;
deleteTask(taskId: any, cb: () => void): void;
putTask(taskId: any, task: T, priority: number, cb: (error: any) => void): void;
takeFirstN(n: number, cb: (error: any, lockId: string) => void): void;
takeLastN(n: number, cb: (error: any, lockId: string) => void): void;
getLock(lockId: string, cb: (error: any, tasks: { [taskId: string]: T }) => void): void;
releaseLock(lockId: string, cb: (error: any) => void): void;
}
interface StoreOptions {
type: string;
// store-specific options
[key: string]: any;
}
class Ticket extends NodeJS.EventEmitter {
on(event: TicketEvent, listener: (...args: any[]) => void): this;
}
interface TickerProgress {
eta: string;
pct: number;
complete: number;
total: number;
message: string;
}
interface QueueStats {
total: number;
average: number;
successRate: number;
peak: number;
}
}
export = BetterQueue;
@@ -18,6 +18,6 @@
},
"files": [
"index.d.ts",
"fork-ts-checker-webpack-plugin-tests.ts"
"better-queue-tests.ts"
]
}
@@ -0,0 +1,68 @@
import BScroll from 'better-scroll';
const BScroll1 = new BScroll('#wrapper');
const BScroll2 = new BScroll('#wrapper', { scrollX: false, scrollY: false });
const BScroll3 = new BScroll('#wrapper', {
snap: true,
wheel: false,
scrollbar: false,
pullDownRefresh: false,
});
const BScroll4 = new BScroll('#wrapper', {
wheel: {
selectedIndex: 0,
},
});
const BScroll6 = new BScroll('#wrapper', {
snap: {
loop: false,
el: document.querySelector('div-test') as Element,
threshold: 0.1,
stepX: 100,
stepY: 100,
listenFlick: true,
},
});
const BScroll7 = new BScroll('#wrapper', {
scrollbar: {
fade: true,
},
});
const BScroll8 = new BScroll('#wrapper', {
pullDownRefresh: {
threshold: 50,
stop: 20,
},
});
BScroll1.refresh();
BScroll1.scrollTo(0, 100);
BScroll1.scrollTo(0, 100, 200);
BScroll1.scrollToElement('selectedElement');
BScroll1.scrollToElement('selectedElement', 250);
BScroll1.scrollToElement(document.getElementById('selectedElement') as HTMLElement);
BScroll1.scrollToElement(document.getElementById('selectedElement') as HTMLElement, 250);
BScroll2.on('scrollStart', () => { console.log('scroll started'); });
const BScroll9 = new BScroll(document.getElementById('wrapper') as HTMLElement);
const BScroll10 = new BScroll(document.getElementById('wrapper') as HTMLElement, { freeScroll: true });
const BScroll11 = new BScroll(document.getElementById('wrapper') as HTMLElement, {
preventDefaultException: {
tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/,
},
});
const BScroll12 = new BScroll(document.getElementById('wrapper') as HTMLElement, {
preventDefaultException: {
className: /(^|\s)test(\s|$)/,
},
});
const BScroll13 = new BScroll(document.getElementById('wrapper') as HTMLElement, {
swipeBounceTime: 1000,
});
const BScroll14 = new BScroll('#wrapper', { disableMouse: true, disableTouch: false });
+238
View File
@@ -0,0 +1,238 @@
// Type definitions for better-scroll 1.12
// Project: https://github.com/ustbhuangyi/better-scroll
// Definitions by: cloudstone <https://github.com/stoneChen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export interface WheelOption {
selectedIndex: number;
rotate: number;
adjustTime: number;
wheelWrapperClass: string;
wheelItemClass: string;
}
export interface PageOption {
x: number;
y: number;
pageX: number;
pageY: number;
}
export interface SlideOption {
loop: boolean;
el: Element;
threshold: number;
stepX: number;
stepY: number;
speed: number;
listenFlick: boolean;
}
export interface ScrollBarOption {
fade: boolean;
}
export interface PullDownOption {
threshold: number;
stop: number;
}
export interface PullUpOption {
threshold: number;
}
export interface BounceObjectOption {
top?: boolean;
bottom?: boolean;
left?: boolean;
right?: boolean;
}
export interface EaseOption {
swipe?: {
style: string;
fn: (t: number) => number;
};
swipeBounce?: {
style: string;
fn: (t: number) => number;
};
bounce?: {
style: string;
fn: (t: number) => number;
};
}
export interface BsOption {
startX: number;
startY: number;
scrollX: boolean;
scrollY: boolean;
freeScroll: boolean;
directionLockThreshold: number;
eventPassthrough: string | boolean;
click: boolean;
tap: boolean;
bounce: boolean | BounceObjectOption;
bounceTime: number;
momentum: boolean;
momentumLimitTime: number;
momentumLimitDistance: number;
swipeTime: number;
swipeBounceTime: number;
deceleration: number;
flickLimitTime: number;
flickLimitDistance: number;
resizePolling: number;
probeType: number;
preventDefault: boolean;
preventDefaultException: object;
HWCompositing: boolean;
useTransition: boolean;
useTransform: boolean;
bindToWrapper: boolean;
disableMouse: boolean;
disableTouch: boolean;
observeDOM: boolean;
autoBlur: boolean;
stopPropagation: boolean;
/**
* for picker
* wheel: {
* selectedIndex: 0,
* rotate: 25,
* adjustTime: 400
* }
*/
wheel: Partial<WheelOption> | boolean;
/**
* for slide
* snap: {
* loop: boolean,
* el: domEl,
* threshold: 0.1,
* stepX: 100,
* stepY: 100,
* listenFlick: true
* }
*/
snap: Partial<SlideOption> | boolean;
/**
* for scrollbar
* scrollbar: {
* fade: true
* }
*/
scrollbar: Partial<ScrollBarOption> | boolean;
/**
* for pull down and refresh
* pullDownRefresh: {
* threshold: 50,
* stop: 20
* }
*/
pullDownRefresh: Partial<PullDownOption> | boolean;
/**
* for pull up and load
* pullUpLoad: {
* threshold: 50
* }
*/
pullUpLoad: Partial<PullUpOption> | boolean;
}
export interface Position {
x: number;
y: number;
}
export default class BScroll {
constructor(element: Element | string, options?: Partial<BsOption>);
x: number;
y: number;
maxScrollX: number;
maxScrollY: number;
movingDirectionX: number;
movingDirectionY: number;
directionX: number;
directionY: number;
enabled: boolean;
isInTransition: boolean;
isAnimating: boolean;
options: BsOption;
refresh(): void;
enable(): void;
disable(): void;
scrollBy(x: number, y: number, time?: number, easing?: object): void;
scrollTo(x: number, y: number, time?: number, easing?: object): void;
scrollToElement(el: HTMLElement | string, time?: number, offsetX?: number | boolean, offsetY?: number | boolean, easing?: object): void;
stop(): void;
destroy(): void;
goToPage(x: number, y: number, time?: number, easing?: object): void;
next(time?: number, easing?: object): void;
prev(time?: number, easing?: object): void;
getCurrentPage(): PageOption;
wheelTo(index: number): void;
getSelectedIndex(): number;
finishPullDown(): void;
finishPullUp(): void;
on(
type:
'beforeScrollStart' |
'scrollStart' |
'scrollCancel' |
'beforeScrollStart' |
'flick' |
'refresh' |
'destroy' |
'pullingDown' |
'pullingUp',
fn: () => any
): void;
on(
type:
'scroll' |
'scrollEnd' |
'touchEnd',
fn: (pos: Position) => any
): void;
off(
type:
'beforeScrollStart' |
'scrollStart' |
'scroll' |
'scrollCancel' |
'beforeScrollStart' |
'scrollEnd' |
'touchEnd' |
'flick' |
'refresh' |
'destroy' |
'pullingDown' |
'pullingUp',
fn: (...args: any[]) => void
): void;
trigger(type: string): void;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"better-scroll-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+7 -1
View File
@@ -4,8 +4,14 @@ function test_bloomfilter() {
const k = 2;
const bloomFilter = new BloomFilter(m, k);
const array: Int32Array[] = bloomFilter.buckets;
const array: Int32Array = bloomFilter.buckets;
const length: number = bloomFilter.buckets.length;
bloomFilter.add('someString');
const test: boolean = bloomFilter.test('someString');
const buckets: Int32Array = bloomFilter.buckets;
const bloom2 = new BloomFilter(buckets, k);
const a: Int32Array = new Int32Array(16);
a[3];
}
+18 -3
View File
@@ -1,14 +1,29 @@
// Type definitions for BloomFilter 0.1
// Type definitions for BloomFilter 0.0
// Project: https://github.com/jasondavies/bloomfilter.js
// Definitions by: slawiko <https://github.com/slawiko>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class BloomFilter {
buckets: Int32Array[];
buckets: Int32Array;
constructor(m: number, k: number);
/**
* Create a new empty bloom filter of size m with hashes k or
* provide buckets as a number[] or Int32Array to deserialize a bloom filter
* @param mOrBucketsArray number of bits (will be rounded up to nearest 32), or buckets
* to deserialize into a filled bloomfilter
* @param k number of hashes
*/
constructor(m: number | number[] | Int32Array, k: number);
/**
* Add a value to a bloom filter
* @param value
*/
add(value: any): void;
/**
* Test whether a value exists in a bloom filter. (False positives are
* possible, false negatives are not.)
*/
test(value: any): boolean;
}
@@ -40,3 +40,7 @@ function testPromiseRejection() {
return value.toUpperCase();
});
}
function testGithubTicket28081Regression() {
Promise.resolve([3]).map((n: number) => true);
}
+46 -46
View File
@@ -67,52 +67,52 @@ declare global {
* Patch all instance method
*/
interface Promise<T> {
all: typeof Bluebird.prototype.all;
any: typeof Bluebird.prototype.any;
asCallback: typeof Bluebird.prototype.asCallback;
bind: typeof Bluebird.prototype.bind;
call: typeof Bluebird.prototype.call;
cancel: typeof Bluebird.prototype.cancel;
// catch: typeof Bluebird.prototype.catch;
caught: typeof Bluebird.prototype.caught;
delay: typeof Bluebird.prototype.delay;
disposer: typeof Bluebird.prototype.disposer;
done: typeof Bluebird.prototype.done;
each: typeof Bluebird.prototype.each;
error: typeof Bluebird.prototype.error;
filter: typeof Bluebird.prototype.filter;
// finally: typeof Bluebird.prototype.finally;
get: typeof Bluebird.prototype.get;
isCancelled: typeof Bluebird.prototype.isCancelled;
isFulfilled: typeof Bluebird.prototype.isFulfilled;
isPending: typeof Bluebird.prototype.isPending;
isRejected: typeof Bluebird.prototype.isRejected;
isResolved: typeof Bluebird.prototype.isResolved;
lastly: typeof Bluebird.prototype.lastly;
map: typeof Bluebird.prototype.map;
mapSeries: typeof Bluebird.prototype.mapSeries;
nodeify: typeof Bluebird.prototype.nodeify;
props: typeof Bluebird.prototype.props;
race: typeof Bluebird.prototype.race;
reason: typeof Bluebird.prototype.reason;
reduce: typeof Bluebird.prototype.reduce;
reflect: typeof Bluebird.prototype.reflect;
return: typeof Bluebird.prototype.return;
some: typeof Bluebird.prototype.some;
spread: typeof Bluebird.prototype.spread;
suppressUnhandledRejections: typeof Bluebird.prototype.suppressUnhandledRejections;
tap: typeof Bluebird.prototype.tap;
tapCatch: typeof Bluebird.prototype.tapCatch;
// then: typeof Bluebird.prototype.then;
thenReturn: typeof Bluebird.prototype.thenReturn;
thenThrow: typeof Bluebird.prototype.thenThrow;
catchReturn: typeof Bluebird.prototype.catchReturn;
catchThrow: typeof Bluebird.prototype.catchThrow;
throw: typeof Bluebird.prototype.throw;
timeout: typeof Bluebird.prototype.timeout;
toJSON: typeof Bluebird.prototype.toJSON;
toString: typeof Bluebird.prototype.toString;
value: typeof Bluebird.prototype.value;
all: Bluebird<T>["all"];
any: Bluebird<T>["any"];
asCallback: Bluebird<T>["asCallback"];
bind: Bluebird<T>["bind"];
call: Bluebird<T>["call"];
cancel: Bluebird<T>["cancel"];
// catch: Bluebird<T>["catch"];
caught: Bluebird<T>["caught"];
delay: Bluebird<T>["delay"];
disposer: Bluebird<T>["disposer"];
done: Bluebird<T>["done"];
each: Bluebird<T>["each"];
error: Bluebird<T>["error"];
filter: Bluebird<T>["filter"];
// finally: Bluebird<T>["finally"];
get: Bluebird<T>["get"];
isCancelled: Bluebird<T>["isCancelled"];
isFulfilled: Bluebird<T>["isFulfilled"];
isPending: Bluebird<T>["isPending"];
isRejected: Bluebird<T>["isRejected"];
isResolved: Bluebird<T>["isResolved"];
lastly: Bluebird<T>["lastly"];
map: Bluebird<T>["map"];
mapSeries: Bluebird<T>["mapSeries"];
nodeify: Bluebird<T>["nodeify"];
props: Bluebird<T>["props"];
race: Bluebird<T>["race"];
reason: Bluebird<T>["reason"];
reduce: Bluebird<T>["reduce"];
reflect: Bluebird<T>["reflect"];
return: Bluebird<T>["return"];
some: Bluebird<T>["some"];
spread: Bluebird<T>["spread"];
suppressUnhandledRejections: Bluebird<T>["suppressUnhandledRejections"];
tap: Bluebird<T>["tap"];
tapCatch: Bluebird<T>["tapCatch"];
// then: Bluebird<T>["then"];
thenReturn: Bluebird<T>["thenReturn"];
thenThrow: Bluebird<T>["thenThrow"];
catchReturn: Bluebird<T>["catchReturn"];
catchThrow: Bluebird<T>["catchThrow"];
throw: Bluebird<T>["throw"];
timeout: Bluebird<T>["timeout"];
toJSON: Bluebird<T>["toJSON"];
toString: Bluebird<T>["toString"];
value: Bluebird<T>["value"];
/*
* Copy&paste ::then and ::catch from lib.es2015.promise.d.ts, because Bluebird's typings are not
+1
View File
@@ -9,6 +9,7 @@
// David Koblas <https://github.com/koblas>
// Bond Akinmade <https://github.com/bondz>
// Wuha Team <https://github.com/wuha-team>
// Alec Brunelle <https://github.com/aleccool213>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
+31 -1
View File
@@ -54,6 +54,24 @@ declare module "bull" {
* since pubsub does not give any guarantees.
*/
finished(): Promise<void>;
/**
* Moves a job to the `completed` queue. Pulls a job from 'waiting' to
* 'active' and returns a tuple containing the next jobs data and id. If no
* job is in the `waiting` queue, returns null.
* @param returnValue The jobs success message.
* @param ignoreLock True when wanting to ignore the redis lock on this job.
* @returns Contains the next jobs data and id or null if job left in 'waiting' queue.
*/
moveToCompleted(returnValue: string, ignoreLock: boolean): Promise<string[] | null>;
/**
* Moves a job to the failed queue.
* @param errorInfo The jobs error message.
* @param ignoreLock True when wanting to ignore the redis lock on this job.
* @returns void
*/
moveToFailed(errorInfo: ErrorMessage, ignoreLock: boolean): Promise<void>;
}
export interface Backoff {
@@ -204,7 +222,7 @@ declare module "bull" {
* Returns a promise that will return the job instance associated with the jobId parameter.
* If the specified job cannot be located, the promise callback parameter will be set to null.
*/
getJob(jobId: string): Promise<Job>;
getJob(jobId: string): Promise<Job | null>;
/**
* Tells the queue remove all jobs created outside of a grace period in milliseconds.
@@ -217,6 +235,18 @@ declare module "bull" {
* 'ready', 'error', 'activ', 'progress', 'completed', 'failed', 'paused', 'resumed', 'cleaned'
*/
on(eventName: string, callback: EventCallback): void;
/**
* Moves the next job from 'waiting' to 'active'.
* Sets the processedOn timestamp to the current datetime.
* @param jobId If specified, will move a specific job from 'waiting' to 'active',
* @returns Returns the job moved from waiting to active queue.
*/
getNextJob:(jobId?: string) => Promise<Job | null>;
}
interface ErrorMessage {
message: string;
}
interface EventCallback {
+1
View File
@@ -452,6 +452,7 @@ function gauge_examples() {
max: 100,
units: " %",
width: 10,
fullCircle: true,
}
});
}
+6
View File
@@ -276,6 +276,12 @@ export interface ChartConfiguration {
* Set width of gauge chart.
*/
width?: number;
/**
* Whether this should be displayed
* as a full circle instead of a
* half circle.
*/
fullCircle?: boolean;
};
spline?: {
+2 -1
View File
@@ -14,6 +14,7 @@
// Slavik Nychkalo <https://github.com/gebeto>
// Francesco Benedetto <https://github.com/frabnt>
// Alexandros Dorodoulis <https://github.com/alexdor>
// Manuel Heidrich <https://github.com/mahnuh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -31,7 +32,7 @@ declare class Chart {
stop: () => {};
resize: () => {};
clear: () => {};
toBase64: () => string;
toBase64Image: () => string;
generateLegend: () => {};
getElementAtEvent: (e: any) => {};
getElementsAtEvent: (e: any) => Array<{}>;
@@ -0,0 +1,277 @@
import * as ChartMogul from 'chartmogul-node';
const config = new ChartMogul.Config("token", "secret", "baseURL");
config.retries = 10;
config.getAccountToken(); // $ExpectType string
config.getSecretKey(); // $ExpectType string
config.VERSION; // $ExpectType string
ChartMogul.Ping.ping(config); // $ExpectType Promise<string>
// $ExpectType Promise<DataSource>
ChartMogul.DataSource.create(config, {
name: ""
});
// $ExpectType Promise<DataSource>
ChartMogul.DataSource.retrieve(config, "");
// $ExpectType Promise<{}>
ChartMogul.DataSource.destroy(config, "");
// $ExpectType Promise<DataSources>
ChartMogul.DataSource.all(config, {
name: ""
});
ChartMogul.DataSource.all(config).then(data => {
data.data_sources[0]; // $ExpectType DataSource
data.data_sources[0].name; // $ExpectType string
});
// $ExpectType Promise<Customer>
ChartMogul.Customer.create(config, {
data_source_uuid: "",
name: "",
external_id: "",
attributes: {
tags: ["important", "Prio1"],
custom: [
{type: "String", key: "channel", value: "Facebook", source: "integration"},
{type: "Integer", key: "age", value: 18}
]
}
});
// $ExpectType Promise<Customer>
ChartMogul.Customer.retrieve(config, "");
// $ExpectType Promise<Customer>
ChartMogul.Customer.modify(config, "", {});
// $ExpectType Promise<{}>
ChartMogul.Customer.destroy(config, "");
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Customer.all(config, {
data_source_uuid: ""
});
ChartMogul.Customer.all(config).then(data => {
data.entries[0]; // $ExpectType Customer
data.entries[0].attributes!.stripe!['something']; // $ExpectType any
data.page!; // $ExpectType number
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Customer.search(config, {
email: ""
});
// $ExpectType Promise<{}>
ChartMogul.Customer.merge(config, {
from: {customer_uuid: ""},
into: {customer_uuid: ""}
});
// $ExpectType Promise<Attributes>
ChartMogul.Customer.attributes(config, "");
// $ExpectType Promise<Plan>
ChartMogul.Plan.create(config, {
data_source_uuid: "",
name: "",
interval_count: 1,
interval_unit: "",
external_id: ""
});
// $ExpectType Promise<Plan>
ChartMogul.Plan.retrieve(config, "");
// $ExpectType Promise<Plan>
ChartMogul.Plan.modify(config, "", {
name: ""
});
// $ExpectType Promise<{}>
ChartMogul.Plan.destroy(config, "");
ChartMogul.Plan.all(config, {
page: 1
}).then(data => {
data.plans[0]; // $ExpectType Plan
data.plans[0].name!; // $ExpectType string
data.page!; // $ExpectType number
});
// $ExpectType Promise<Invoice>
ChartMogul.Invoice.retrieve(config, "");
// $ExpectType Promise<Invoice>
ChartMogul.Invoice.create(config, "", {
invoices: [
{
external_id: ""
}
]
});
// $ExpectType Promise<{}>
ChartMogul.Invoice.destroy(config, "");
ChartMogul.Invoice.all(config, {
external_id: ""
}).then(data => {
data.invoices[0]; // $ExpectType Invoice
data.invoices[0].uuid!; // $ExpectType string
data.page!; // $ExpectType number
});
ChartMogul.Invoice.all(config, "", {
page: 1
}).then(data => {
data.customer_uuid!; // $ExpectType string
data.invoices[0]; // $ExpectType Invoice
data.invoices[0].uuid!; // $ExpectType string
data.page!; // $ExpectType number
});
// $ExpectType Promise<Transaction>
ChartMogul.Transaction.create(config, "", {
type: "",
date: "",
result: ""
});
ChartMogul.Subscription.all(config, "", {
page: 1
}).then(data => {
data.customer_uuid!; // $ExpectType string
data.subscriptions[0]; // $ExpectType Subscription
data.subscriptions[0].uuid; // $ExpectType string
data.current_page!; // $ExpectType number
});
ChartMogul.Subscription.cancel(config, "", {
cancelled_at: ""
}).then(data => {
data.customer_uuid; // $ExpectType string
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Tag.add(config, "", {
email: "",
tags: [""]
});
// $ExpectType Promise<Tags>
ChartMogul.Tag.add(config, "", {
tags: [""]
});
// $ExpectType Promise<Tags>
ChartMogul.Tag.remove(config, "", {
tags: [""]
});
// $ExpectType Promise<CustomAttributes>
ChartMogul.CustomAttribute.add(config, "", {
custom: [
{type: "", key: "", value: 0}
]
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.CustomAttribute.add(config, "", {
email: "",
custom: [
{type: "", key: "", value: 0}
]
});
// $ExpectType Promise<CustomAttributes>
ChartMogul.CustomAttribute.update(config, "", {
custom: {
pro: true,
channel: ""
}
});
ChartMogul.CustomAttribute.remove(config, "", {
custom: [""]
}).then(data => {
data.custom["key"]; // $ExpectType any
});
// $ExpectType Promise<All>
ChartMogul.Metrics.all(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-24',
interval: '',
geo: '',
plans: ''
});
// $ExpectType Promise<EntriesSummary<MRR>>
ChartMogul.Metrics.mrr(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ARR>>
ChartMogul.Metrics.arr(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ARPA>>
ChartMogul.Metrics.arpa(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ASP>>
ChartMogul.Metrics.asp(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<CustomerCount>>
ChartMogul.Metrics.customerCount(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<CustomerChurnRate>>
ChartMogul.Metrics.customerChurnRate(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01',
geo: '',
plans: ''
});
// $ExpectType Promise<EntriesSummary<MRRChurnRate>>
ChartMogul.Metrics.mrrChurnRate(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
ChartMogul.Metrics.ltv(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
}).then(data => {
data.entries[0].ltv; // $ExpectType number
data.summary; // $ExpectType Summary
data.summary.current; // $ExpectType number
});
// $ExpectType Promise<Entries<MetricsSubscription>>
ChartMogul.Metrics.Customer.subscriptions(config, "", {
page: 1
});
ChartMogul.Metrics.Customer.activities(config, "", {
page: 1
}).then(data => {
data.entries; // $ExpectType MetricsActivity[]
data.entries[0]; // $ExpectType MetricsActivity
data.entries[0]['activity-mrr']; // $ExpectType number
data.page!; // $ExpectType number
});
+28
View File
@@ -0,0 +1,28 @@
export interface Map {
[key: string]: any
}
export interface CursorParams {
page?: number;
per_page?: number;
}
export type Strings = string[];
export interface Cursor {
page?: number;
per_page?: number;
has_more?: boolean;
current_page?: number;
total_pages?: number;
}
export interface Entries<T> extends Cursor {
entries: T[]
}
interface Summary {
current: number;
previous: number;
['percentage-change']: number;
}
export interface EntriesSummary<T> {
entries: T[];
summary: Summary;
}
+410
View File
@@ -0,0 +1,410 @@
// Type definitions for chartmogul-node 1.0
// Project: https://github.com/chartmogul/chartmogul-node
// Definitions by: ChartMogul <https://github.com/chartmogul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Map, Cursor, CursorParams, Strings, Entries, EntriesSummary } from './common';
export class Config {
VERSION: string;
API_BASE: string;
retries: number;
constructor(token: string, secret: string, base?: string);
getAccountToken(): string;
getSecretKey(): string;
}
export namespace Ping {
function ping(config: Config): Promise<string>;
}
export namespace DataSource {
interface DataSource {
uuid?: string;
name: string;
created_at?: string;
status?: string;
system?: string;
}
interface DataSources {
data_sources: DataSource[];
}
interface ListDataSourcesParams {
name?: string;
system?: string;
}
function create(config: Config, data: DataSource): Promise<DataSource>;
function retrieve(config: Config, uuid: string): Promise<DataSource>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListDataSourcesParams): Promise<DataSources>;
}
export namespace Customer {
interface Customer {
id?: number;
data_source_uuid?: string;
data_source_uuids?: Strings;
uuid?: string;
external_id?: string;
external_ids?: Strings;
name?: string;
email?: string;
status?: string;
['customer-since']?: string;
attributes?: Attributes;
address?: {
address_zip?: string;
city?: string;
state?: string;
country?: string;
};
mrr?: number;
arr?: number;
['billing-system-url']?: string;
['chartmogul-url']?: string;
['billing-system-type']?: string;
currency?: string;
['currency-sign']?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
}
interface NewCustomer {
data_source_uuid: string;
external_id: string;
name: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface UpdateCustomer {
name?: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface NewAttributes {
tags?: Strings;
custom?: NewCustomAttributes[];
}
interface NewCustomAttributes {
type?: string;
key: string;
value: any;
source?: string;
}
interface Attributes {
tags?: Strings;
stripe?: Map;
clearbit?: Map;
custom?: Map;
}
interface ListCustomersParams extends CursorParams {
data_source_uuid?: string;
status?: string;
system?: string;
external_id?: string;
}
interface SearchCustomersParams extends CursorParams {
email: string;
}
interface MergeID {
customer_uuid?: string;
external_id?: string;
}
interface MergeCustomersParams {
from: MergeID;
into: MergeID;
}
function create(config: Config, data: NewCustomer): Promise<Customer>;
function retrieve(config: Config, uuid: string): Promise<Customer>;
function modify(config: Config, uuid: string, data: UpdateCustomer): Promise<Customer>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListCustomersParams): Promise<Entries<Customer>>;
function search(config: Config, params?: SearchCustomersParams): Promise<Entries<Customer>>;
function merge(config: Config, params?: MergeCustomersParams): Promise<{}>;
function attributes(config: Config, uuid: string): Promise<Attributes>;
}
export namespace Plan {
interface Plan {
uuid?: string;
data_source_uuid?: string;
external_id?: string;
name?: string;
interval_count?: number;
interval_unit?: string;
}
interface ListPlansParams extends CursorParams {
data_source_uuid?: string;
system?: string;
external_id?: string;
}
interface Plans extends Cursor {
plans: Plan[];
}
function create(config: Config, data: Plan): Promise<Plan>;
function retrieve(config: Config, uuid: string): Promise<Plan>;
function modify(config: Config, uuid: string, data: Plan): Promise<Plan>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListPlansParams): Promise<Plans>;
}
export namespace Invoice {
interface Invoice {
uuid?: string;
customer_uuid?: string;
currency?: string;
data_source_uuid?: string;
date?: string;
due_date?: string;
external_id?: string;
line_items?: LineItem[];
transactions?: Transaction[];
}
interface LineItem {
uuid?: string;
account_code?: string;
amount_in_cents?: number;
cancelled_at?: string;
description?: string;
discount_amount_in_cents?: number;
discount_code?: string;
external_id?: string;
plan_uuid?: string;
prorated?: boolean;
quantity?: number;
service_period_end?: string;
service_period_start?: string;
subscription_external_id?: string;
subscription_uuid?: string;
tax_amount_in_cents?: number;
transaction_fees_in_cents?: number;
type?: string;
}
interface Transaction {
uuid?: string;
date?: string;
external_id?: string;
result?: string;
type?: string;
}
interface ListInvoicesParams extends CursorParams {
data_source_uuid?: string;
customer_uuid?: string;
external_id?: string;
}
interface Invoices extends Cursor {
customer_uuid?: string;
invoices: Invoice[];
}
function create(config: Config, uuid: string, data: {
invoices: Invoice[]
}): Promise<Invoice>;
function retrieve(config: Config, uuid: string): Promise<Invoice>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, uuid: string, params?: ListInvoicesParams): Promise<Invoices>;
function all(config: Config, params?: ListInvoicesParams): Promise<Invoices>;
}
export namespace Transaction {
interface Transaction {
uuid?: string;
date: string;
external_id?: string;
result: string;
type: string;
}
function create(config: Config, uuid: string, data: Transaction): Promise<Transaction>;
}
export namespace Subscription {
interface Subscription {
uuid: string;
external_id: string;
customer_uuid: string;
plan_uuid: string;
cancellation_dates: Strings;
data_source_uuid: string;
}
interface CancelSubscriptionParams {
cancelled_at?: string;
cancellation_dates?: Strings;
}
interface Subscriptions extends Cursor {
customer_uuid?: string;
subscriptions: Subscription[];
}
function all(config: Config, uuid: string, data: CursorParams): Promise<Subscriptions>;
function cancel(config: Config, uuid: string, data: CancelSubscriptionParams): Promise<Subscription>;
}
export namespace Tag {
interface Tags {
tags: Strings;
}
interface TagsWithEmail {
email: string;
tags: Strings;
}
function add(config: Config, uuid: string, data: TagsWithEmail): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: Tags): Promise<Tags>;
function remove(config: Config, uuid: string, data: Tags): Promise<Tags>;
}
export namespace CustomAttribute {
import NewCustomAttributes = Customer.NewCustomAttributes;
interface CustomAttributes {
custom: Map;
}
function add(config: Config, uuid: string, data: {
email: string;
custom: NewCustomAttributes[];
}): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: {
custom: NewCustomAttributes[];
}): Promise<CustomAttributes>;
function update(config: Config, uuid: string, data: CustomAttributes): Promise<CustomAttributes>;
function remove(config: Config, uuid: string, data: {
custom: Strings;
}): Promise<CustomAttributes>;
}
export namespace Metrics {
interface Params extends ParamsNoInterval {
interval?: string;
}
interface ParamsNoInterval {
['start-date']: string;
['end-date']: string;
geo?: string;
plans?: string;
}
interface All {
entries: {
date: string;
['customer-churn-rate']: number;
['mrr-churn-rate']: number;
ltv: number;
customers: number;
asp: number;
arpa: number;
arr: number;
mrr: number;
};
}
interface MRR {
date: string;
mrr: number;
['mrr-new-business']: number;
['mrr-expansion']: number;
['mrr-contraction']: number;
['mrr-churn']: number;
['mrr-reactivation']: number;
}
interface ARR {
date: string;
arr: number;
}
interface ARPA {
date: string;
arpa: number;
}
interface ASP {
date: string;
asp: number;
}
interface CustomerCount {
date: string;
customers: number;
}
interface CustomerChurnRate {
date: string;
['customer-churn-rate']: number;
}
interface MRRChurnRate {
date: string;
['mrr-churn-rate']: number;
}
interface LTV {
date: string;
ltv: number;
}
function all(config: Config, params: Params): Promise<All>;
function mrr(config: Config, params: Params): Promise<EntriesSummary<MRR>>;
function arr(config: Config, params: Params): Promise<EntriesSummary<ARR>>;
function asp(config: Config, params: Params): Promise<EntriesSummary<ASP>>;
function arpa(config: Config, params: Params): Promise<EntriesSummary<ARPA>>;
function customerCount(config: Config, params: Params): Promise<EntriesSummary<CustomerCount>>;
function customerChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<CustomerChurnRate>>;
function mrrChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<MRRChurnRate>>;
function ltv(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<LTV>>;
namespace Customer {
interface MetricsSubscription {
id: number;
external_id: string;
plan: string;
quantity: number;
mrr: number;
arr: number;
status: string;
['billing-cycle']: string;
['billing-cycle-count']: number;
['start-date']: string;
['end-date']: string;
currency: string;
['currency-sign']: string;
}
interface MetricsActivity {
id: number;
date: string;
['activity-arr']: number;
['activity-mrr']: number;
['activity-mrr-movement']: number;
currency: string;
['currency-sign']: string;
description: string;
type: string;
}
function subscriptions(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsSubscription>>;
function activities(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsActivity>>;
}
}
export class ChartMogulError extends Error {
response: any;
httpStatus: number;
}
export class ConfigurationError extends ChartMogulError {}
export class ForbiddenError extends ChartMogulError {}
export class NotFoundError extends ChartMogulError {}
export class ResourceInvalidError extends ChartMogulError {}
export class SchemaInvalidError extends ChartMogulError {}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"chartmogul-node-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -214,6 +214,7 @@ interface CheerioOptionsInterface {
recognizeCDATA?: boolean;
recognizeSelfClosing?: boolean;
normalizeWhitespace?: boolean;
ignoreWhitespace?: boolean;
}
interface CheerioSelector {
+1
View File
@@ -4959,6 +4959,7 @@ declare namespace chrome.runtime {
export interface ConnectInfo {
name?: string;
includeTlsChannelId?: boolean;
}
export interface InstalledDetails {
+11 -6
View File
@@ -15,7 +15,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co
declare namespace CodeMirror {
export var Doc : CodeMirror.DocConstructor;
export var Pos: CodeMirror.PositionConstructor;
export var Pass: any;
export var Pass: {toString(): "CodeMirror.PASS"};
function countColumn(line: string, index: number | null, tabSize: number): number;
function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea;
@@ -129,6 +129,10 @@ declare namespace CodeMirror {
state: any;
}
interface KeyMap {
[keyName: string]: false | string | ((instance: Editor) => void | typeof Pass);
}
interface Editor {
/** Tells you whether the editor currently has focus. */
@@ -159,11 +163,11 @@ declare namespace CodeMirror {
Maps added in this way have a higher precedence than the extraKeys and keyMap options, and between them,
the maps added earlier have a lower precedence than those added later, unless the bottom argument was passed,
in which case they end up below other keymaps added with this method. */
addKeyMap(map: any, bottom?: boolean): void;
addKeyMap(map: string | KeyMap, bottom?: boolean): void;
/** Disable a keymap added with addKeyMap.Either pass in the keymap object itself , or a string,
which will be compared against the name property of the active keymaps. */
removeKeyMap(map: any): void;
removeKeyMap(map: string | KeyMap): void;
/** Enable a highlighting overlay.This is a stateless mini - mode that can be used to add extra highlighting.
For example, the search add - on uses it to highlight the term that's currently being searched.
@@ -716,8 +720,9 @@ declare namespace CodeMirror {
}
interface EditorChangeCancellable extends CodeMirror.EditorChange {
/** may be used to modify the change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. */
update(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string[]): void;
/** may be used to modify the change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact.
If the change came from undo/redo, `update` is undefined and the change cannot be modified. */
update?(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string[]): void;
cancel(): void;
}
@@ -780,7 +785,7 @@ declare namespace CodeMirror {
keyMap?: string;
/** Can be used to specify extra keybindings for the editor, alongside the ones defined by keyMap. Should be either null, or a valid keymap value. */
extraKeys?: any;
extraKeys?: string | KeyMap;
/** Whether CodeMirror should scroll or wrap for long lines. Defaults to false (scroll). */
lineWrapping?: boolean;
+23 -3
View File
@@ -4,7 +4,18 @@ var myCodeMirror: CodeMirror.Editor = CodeMirror(document.body);
var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
mode: "javascript",
extraKeys: {
Enter: (cm) => { console.log("save"); },
Esc: (cm) => { return CodeMirror.Pass; }
}
});
// $ExpectError
var myCodeMirror2_1: CodeMirror.Editor = CodeMirror(document.body, {
extraKeys: {
"Shift-Enter": (cm) => { return 42; } // not a valid return value
}
});
var range = myCodeMirror2.findWordAt(CodeMirror.Pos(0, 2));
@@ -13,9 +24,9 @@ var head = range.head;
var from = range.from();
var to = range.to();
var myTextArea: HTMLTextAreaElement;
var myTextArea: HTMLTextAreaElement = undefined!;
var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
myTextArea.parentNode!.replaceChild(elt, myTextArea);
}, { value: myTextArea.value });
var myCodeMirror4: CodeMirror.Editor = CodeMirror.fromTextArea(myTextArea);
@@ -67,6 +78,15 @@ myCodeMirror.on(
(instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => { }
);
myCodeMirror.on(
"beforeChange",
(instance: CodeMirror.Editor, change: CodeMirror.EditorChangeCancellable) => {
// $ExpectError
change.update();
if (change.update != null) change.update();
}
);
CodeMirror.registerHelper("lint", "javascript", {});
myCodeMirror.isReadOnly();
+1 -1
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
+1 -1
View File
@@ -61,7 +61,7 @@ interface CopyWebpackPluginConfiguration {
}
interface CopyWebpackPlugin {
new (patterns?: CopyPattern[], options?: CopyWebpackPluginConfiguration): Plugin
new (patterns?: (string | CopyPattern)[], options?: CopyWebpackPluginConfiguration): Plugin
}
declare const copyWebpackPlugin: CopyWebpackPlugin
+112 -92
View File
@@ -13,8 +13,10 @@ import * as d3Hierarchy from 'd3-hierarchy';
// -----------------------------------------------------------------------
let num: number;
let numOrUndefined: number | undefined;
let size: [number, number];
let idString: string;
let sizeOrNull: [number, number] | null;
let idString: string | undefined;
// -----------------------------------------------------------------------
// Hierarchy
@@ -47,16 +49,20 @@ let hierarchyRootDatum: HierarchyDatum = {
]
};
let hierarchyNodeArray: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>>;
let hierarchyNodeArray: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = [];
let hierarchyNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> | undefined;
let hierarchyNode: d3Hierarchy.HierarchyNode<HierarchyDatum>;
let hierarchyPointNodeArray: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>>;
let hierarchyPointNodeArray: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = [];
let hierarchyPointNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> | undefined;
let hierarchyPointNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>;
let hierarchyRectangularNodeArray: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>>;
let hierarchyRectangularNodeArray: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = [];
let hierarchyRectangularNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> | undefined;
let hierarchyRectangularNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>;
let hierarchyCircularNodeArray: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>>;
let hierarchyCircularNodeArray: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = [];
let hierarchyCircularNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> | undefined;
let hierarchyCircularNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>;
// Create Hierarchy Layout Root Node =====================================
@@ -65,6 +71,10 @@ let hierarchyRootNode: d3Hierarchy.HierarchyNode<HierarchyDatum>;
hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum);
hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum, (d) => {
return d.children;
});
hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum, (d) => {
return d.children || null;
});
@@ -79,10 +89,11 @@ num = hierarchyRootNode.height;
// children, parent ------------------------------------------------------
hierarchyNodeArray = hierarchyRootNode.children;
hierarchyNodeArrayOrUndefined = hierarchyRootNode.children;
let parentNode: d3Hierarchy.HierarchyNode<HierarchyDatum>;
let parentNode: d3Hierarchy.HierarchyNode<HierarchyDatum> | null;
parentNode = hierarchyNodeArray.length ? hierarchyNodeArray[0].parent : null;
parentNode = hierarchyNodeArray[0].parent;
// id --------------------------------------------------------------------
@@ -93,17 +104,17 @@ idString = hierarchyRootNode.id;
const ancestors: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.ancestors();
const descendants: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.descendants();
// leaves() ---------------------------------------------------------------
// leaves() --------------------------------------------------------------
hierarchyNodeArray = hierarchyRootNode.leaves();
// path() -------------------------------------------------------------------
// path() ----------------------------------------------------------------
hierarchyNode = descendants[descendants.length - 1];
const path: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.path(hierarchyNode);
// links() and HierarchyLink<...> ------------------------------------------
// links() and HierarchyLink<...> ----------------------------------------
let links: Array<d3Hierarchy.HierarchyLink<HierarchyDatum>>;
@@ -115,26 +126,26 @@ link = links[0];
hierarchyNode = link.source;
hierarchyNode = link.target;
// sum() and value ----------------------------------------------------------
// sum() and value -------------------------------------------------------
hierarchyRootNode = hierarchyRootNode.sum((d) => d.val);
num = hierarchyRootNode.value;
numOrUndefined = hierarchyRootNode.value;
// count() and value ----------------------------------------------------------
// count() and value -----------------------------------------------------
hierarchyRootNode = hierarchyRootNode.count();
num = hierarchyRootNode.value;
numOrUndefined = hierarchyRootNode.value;
// sort ---------------------------------------------------------------------
// sort ------------------------------------------------------------------
hierarchyRootNode = hierarchyRootNode.sort((a, b) => {
console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyNode<HierarchyDatum>
return b.height - a.height || b.value - a.value;
return b.height - a.height || b.value! - a.value!;
});
// each(), eachAfter(), eachBefore() ----------------------------------------
// each(), eachAfter(), eachBefore() -------------------------------------
hierarchyRootNode = hierarchyRootNode.each((node) => {
console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum>
@@ -151,7 +162,7 @@ hierarchyRootNode = hierarchyRootNode.eachBefore((node) => {
console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum>
});
// copy() --------------------------------------------------------------------
// copy() ----------------------------------------------------------------
let copiedHierarchyNode: d3Hierarchy.HierarchyNode<HierarchyDatum>;
copiedHierarchyNode = hierarchyRootNode.copy();
@@ -161,12 +172,12 @@ copiedHierarchyNode = hierarchyRootNode.copy();
// -----------------------------------------------------------------------
interface HierarchyDatumWithParentId extends HierarchyDatum {
parentId: string;
parentId: string | null;
}
interface TabularHierarchyDatum {
name: string;
parentId: string;
parentId: string | null;
val: number;
}
@@ -178,7 +189,7 @@ tabularData = [
{ name: 'n121', parentId: 'n12', val: 30 }
];
let idStringAccessor: (d: TabularHierarchyDatum, i?: number, data?: TabularHierarchyDatum[]) => (string | null | '' | undefined);
let idStringAccessor: (d: TabularHierarchyDatum, i: number, data: TabularHierarchyDatum[]) => (string | null | '' | undefined);
// Create Stratify Operator ---------------------------------------------
@@ -217,7 +228,8 @@ idStringAccessor = stratificatorizer.parentId();
// Use Stratify Operator ------------------------------------------------
const stratifiedRootNode: d3Hierarchy.HierarchyNode<HierarchyDatumWithParentId> = stratificatorizer(tabularData);
const stratifiedRootNode: d3Hierarchy.HierarchyNode<TabularHierarchyDatum> = stratificatorizer(tabularData);
const pId: string | null = stratifiedRootNode.data.parentId;
// -----------------------------------------------------------------------
// Cluster
@@ -235,12 +247,12 @@ clusterLayout = d3Hierarchy.cluster<HierarchyDatumWithParentId>();
clusterLayout = clusterLayout.size([200, 200]);
size = clusterLayout.size();
sizeOrNull = clusterLayout.size();
// nodeSize() ------------------------------------------------------------
clusterLayout = clusterLayout.nodeSize([10, 10]);
size = clusterLayout.nodeSize();
sizeOrNull = clusterLayout.nodeSize();
// separation() ----------------------------------------------------------
@@ -272,10 +284,11 @@ num = clusterRootNode.height;
// children, parent ------------------------------------------------------
hierarchyPointNodeArray = clusterRootNode.children;
hierarchyPointNodeArrayOrUndefined = clusterRootNode.children;
let parentPointNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>;
let parentPointNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId> | null;
parentPointNode = hierarchyPointNodeArray.length ? hierarchyPointNodeArray[0].parent : null;
parentPointNode = hierarchyPointNodeArray[0].parent;
// id --------------------------------------------------------------------
@@ -286,17 +299,17 @@ idString = clusterRootNode.id;
const pointNodeAncestors: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.ancestors();
const pointNodeDescendants: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.descendants();
// leaves() ---------------------------------------------------------------
// leaves() --------------------------------------------------------------
hierarchyPointNodeArray = clusterRootNode.leaves();
// path() -------------------------------------------------------------------
// path() ----------------------------------------------------------------
hierarchyPointNode = pointNodeDescendants[pointNodeDescendants.length - 1];
const clusterPath: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.path(hierarchyPointNode);
// links() and HierarchyPointLink<...> ------------------------------------------
// links() and HierarchyPointLink<...> -----------------------------------
let pointLinks: Array<d3Hierarchy.HierarchyPointLink<HierarchyDatumWithParentId>>;
@@ -308,27 +321,27 @@ pointLink = pointLinks[0];
hierarchyPointNode = pointLink.source;
hierarchyPointNode = pointLink.target;
// sum() and value ----------------------------------------------------------
// sum() and value -------------------------------------------------------
clusterRootNode = clusterRootNode.sum((d) => d.val);
num = clusterRootNode.value;
numOrUndefined = clusterRootNode.value;
// count() and value ----------------------------------------------------------
// count() and value -----------------------------------------------------
clusterRootNode = clusterRootNode.count();
num = clusterRootNode.value;
numOrUndefined = clusterRootNode.value;
// sort ---------------------------------------------------------------------
// sort ------------------------------------------------------------------
clusterRootNode = clusterRootNode.sort((a, b) => {
console.log('x-coordinates of a:', a.x, ' and b:', b.x); // a and b are of type HierarchyPointNode<HierarchyDatumWithParentId>
console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyPointNode<HierarchyDatumWithParentId>
return b.height - a.height || b.value - a.value;
return b.height - a.height || b.value! - a.value!;
});
// each(), eachAfter(), eachBefore() ----------------------------------------
// each(), eachAfter(), eachBefore() -------------------------------------
clusterRootNode = clusterRootNode.each((node) => {
console.log('ParentId:', node.data.parentId); // node type is HierarchyPointNode<HierarchyDatumWithParentId>
@@ -345,7 +358,7 @@ clusterRootNode = clusterRootNode.eachBefore((node) => {
console.log('X-coordinate of node:', node.x); // node type is HierarchyPointNode<HierarchyDatumWithParentId>
});
// copy() --------------------------------------------------------------------
// copy() ----------------------------------------------------------------
let copiedClusterNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>;
copiedClusterNode = clusterRootNode.copy();
@@ -354,24 +367,24 @@ copiedClusterNode = clusterRootNode.copy();
// Tree
// -----------------------------------------------------------------------
// Create tree layout generator =======================================
// Create tree layout generator ==========================================
let treeLayout: d3Hierarchy.TreeLayout<HierarchyDatumWithParentId>;
treeLayout = d3Hierarchy.tree<HierarchyDatumWithParentId>();
// Configure tree layout generator ====================================
// Configure tree layout generator =======================================
// size() ----------------------------------------------------------------
treeLayout = treeLayout.size([200, 200]);
size = treeLayout.size();
sizeOrNull = treeLayout.size();
// nodeSize() ------------------------------------------------------------
treeLayout = treeLayout.nodeSize([10, 10]);
size = treeLayout.nodeSize();
sizeOrNull = treeLayout.nodeSize();
// separation() ----------------------------------------------------------
@@ -424,13 +437,13 @@ treemapLayout = treemapLayout.size([400, 200]);
size = treemapLayout.size();
// round() ------------------------------------------------------------
// round() ---------------------------------------------------------------
treemapLayout = treemapLayout.round(true);
let roundFlag: boolean = treemapLayout.round();
// padding() ----------------------------------------------------------------
// padding() -------------------------------------------------------------
treemapLayout = treemapLayout.padding(1);
treemapLayout = treemapLayout.padding((node) => {
@@ -440,7 +453,7 @@ treemapLayout = treemapLayout.padding((node) => {
numberRectangularNodeAccessor = treemapLayout.padding();
// paddingInner() ----------------------------------------------------------------
// paddingInner() --------------------------------------------------------
treemapLayout = treemapLayout.paddingInner(1);
treemapLayout = treemapLayout.paddingInner((node) => {
@@ -450,7 +463,7 @@ treemapLayout = treemapLayout.paddingInner((node) => {
numberRectangularNodeAccessor = treemapLayout.paddingInner();
// paddingOuter() ----------------------------------------------------------------
// paddingOuter() --------------------------------------------------------
treemapLayout = treemapLayout.paddingOuter(1);
treemapLayout = treemapLayout.paddingOuter((node) => {
@@ -460,7 +473,7 @@ treemapLayout = treemapLayout.paddingOuter((node) => {
numberRectangularNodeAccessor = treemapLayout.paddingOuter();
// paddingTop() ----------------------------------------------------------------
// paddingTop() ----------------------------------------------------------
treemapLayout = treemapLayout.paddingTop(1);
treemapLayout = treemapLayout.paddingTop((node) => {
@@ -470,7 +483,7 @@ treemapLayout = treemapLayout.paddingTop((node) => {
numberRectangularNodeAccessor = treemapLayout.paddingTop();
// paddingRight() ----------------------------------------------------------------
// paddingRight() --------------------------------------------------------
treemapLayout = treemapLayout.paddingRight(1);
treemapLayout = treemapLayout.paddingRight((node) => {
@@ -480,7 +493,7 @@ treemapLayout = treemapLayout.paddingRight((node) => {
numberRectangularNodeAccessor = treemapLayout.paddingRight();
// paddingBottom() ----------------------------------------------------------------
// paddingBottom() -------------------------------------------------------
treemapLayout = treemapLayout.paddingBottom(1);
treemapLayout = treemapLayout.paddingBottom((node) => {
@@ -490,7 +503,7 @@ treemapLayout = treemapLayout.paddingBottom((node) => {
numberRectangularNodeAccessor = treemapLayout.paddingBottom();
// paddingLeft() ----------------------------------------------------------------
// paddingLeft() ---------------------------------------------------------
treemapLayout = treemapLayout.paddingLeft(1);
treemapLayout = treemapLayout.paddingLeft((node) => {
@@ -530,7 +543,7 @@ tilingFactoryFn = d3Hierarchy.treemapResquarify.ratio(2);
treemapLayout.tile(d3Hierarchy.treemapResquarify.ratio(2));
// Use HierarchyRectangularNode ================================================
// Use HierarchyRectangularNode ==========================================
// x and y coordinates ---------------------------------------------------
@@ -547,10 +560,11 @@ num = treemapRootNode.height;
// children, parent ------------------------------------------------------
hierarchyRectangularNodeArray = treemapRootNode.children;
hierarchyRectangularNodeArrayOrUndefined = treemapRootNode.children;
let parentRectangularNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>;
let parentRectangularNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId> | null;
parentRectangularNode = hierarchyRectangularNodeArray.length ? hierarchyRectangularNodeArray[0].parent : null;
parentRectangularNode = hierarchyRectangularNodeArray[0].parent;
// id --------------------------------------------------------------------
@@ -561,17 +575,17 @@ idString = treemapRootNode.id;
const rectangularNodeAncestors: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.ancestors();
const rectangularNodeDescendants: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.descendants();
// leaves() ---------------------------------------------------------------
// leaves() --------------------------------------------------------------
hierarchyRectangularNodeArray = treemapRootNode.leaves();
// path() -------------------------------------------------------------------
// path() ----------------------------------------------------------------
hierarchyRectangularNode = rectangularNodeDescendants[rectangularNodeDescendants.length - 1];
const treemapPath: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.path(hierarchyRectangularNode);
// links() and HierarchyRectangularLink<...> ------------------------------------------
// links() and HierarchyRectangularLink<...> -----------------------------
let rectangularLinks: Array<d3Hierarchy.HierarchyRectangularLink<HierarchyDatumWithParentId>>;
@@ -583,26 +597,26 @@ rectangularLink = rectangularLinks[0];
hierarchyRectangularNode = rectangularLink.source;
hierarchyRectangularNode = rectangularLink.target;
// sum() and value ----------------------------------------------------------
// sum() and value -------------------------------------------------------
treemapRootNode = treemapRootNode.sum((d) => d.val);
num = treemapRootNode.value;
numOrUndefined = treemapRootNode.value;
// count() and value ----------------------------------------------------------
// count() and value -----------------------------------------------------
treemapRootNode = treemapRootNode.count();
num = treemapRootNode.value;
// sort ---------------------------------------------------------------------
numOrUndefined = treemapRootNode.value;
// sort ------------------------------------------------------------------
treemapRootNode = treemapRootNode.sort((a, b) => {
console.log('x0-coordinates of a:', a.x0, ' and b:', b.x0); // a and b are of type HierarchyRectangularNode<HierarchyDatumWithParentId>
console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyRectangularNode<HierarchyDatumWithParentId>
return b.height - a.height || b.value - a.value;
return b.height - a.height || b.value! - a.value!;
});
// each(), eachAfter(), eachBefore() ----------------------------------------
// each(), eachAfter(), eachBefore() -------------------------------------
treemapRootNode = treemapRootNode.each((node) => {
console.log('ParentId:', node.data.parentId); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId>
@@ -619,7 +633,7 @@ treemapRootNode = treemapRootNode.eachBefore((node) => {
console.log('X0-coordinate of node:', node.x0); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId>
});
// copy() --------------------------------------------------------------------
// copy() ----------------------------------------------------------------
let copiedTreemapNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>;
copiedTreemapNode = treemapRootNode.copy();
@@ -628,13 +642,13 @@ copiedTreemapNode = treemapRootNode.copy();
// Partition
// -----------------------------------------------------------------------
// Create partition layout generator =======================================
// Create partition layout generator =====================================
let partitionLayout: d3Hierarchy.PartitionLayout<HierarchyDatumWithParentId>;
partitionLayout = d3Hierarchy.partition<HierarchyDatumWithParentId>();
// Configure partition layout generator ====================================
// Configure partition layout generator ==================================
// size() ----------------------------------------------------------------
@@ -642,19 +656,19 @@ partitionLayout = partitionLayout.size([400, 200]);
size = partitionLayout.size();
// round() ------------------------------------------------------------
// round() ---------------------------------------------------------------
partitionLayout = partitionLayout.round(true);
roundFlag = partitionLayout.round();
// padding() ----------------------------------------------------------------
// padding() -------------------------------------------------------------
partitionLayout = partitionLayout.padding(1);
num = partitionLayout.padding();
// Use partition layout generator ==========================================
// Use partition layout generator ========================================
let partitionRootNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>;
@@ -664,15 +678,17 @@ partitionRootNode = partitionLayout(stratifiedRootNode);
// Pack
// -----------------------------------------------------------------------
let numberCircularNodeAccessor: (node: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>) => number;
type CircularAccessor = (node: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>) => number;
let numberCircularNodeAccessor: CircularAccessor;
let numberCircularNodeAccessorOrNull: CircularAccessor | null;
// Create pack layout generator =======================================
// Create pack layout generator ==========================================
let packLayout: d3Hierarchy.PackLayout<HierarchyDatumWithParentId>;
packLayout = d3Hierarchy.pack<HierarchyDatumWithParentId>();
// Configure pack layout generator ====================================
// Configure pack layout generator =======================================
// size() ----------------------------------------------------------------
@@ -680,37 +696,39 @@ packLayout = packLayout.size([400, 400]);
size = packLayout.size();
// radius() ------------------------------------------------------------
// radius() --------------------------------------------------------------
packLayout = packLayout.radius(null);
packLayout = packLayout.radius((node) => {
console.log('Radius property of node before completing accessor: ', node.r); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId>
console.log('Parent id of node: ', node.data.parentId); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId>
return node.value;
return node.value!;
});
numberCircularNodeAccessor = packLayout.radius();
numberCircularNodeAccessorOrNull = packLayout.radius();
// padding() ----------------------------------------------------------------
// padding() -------------------------------------------------------------
packLayout = packLayout.padding(1);
packLayout = packLayout.padding((node) => {
console.log('Radius property of node: ', node.r); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId>
console.log('Parent id of node: ', node.data.parentId); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId>
return node.value > 10 ? 2 : 1;
return node.value! > 10 ? 2 : 1;
});
numberCircularNodeAccessor = packLayout.padding();
// Use partition layout generator ==========================================
// Use partition layout generator ========================================
let packRootNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>;
packRootNode = packLayout(stratifiedRootNode);
// Use HierarchyCircularNode ================================================
// Use HierarchyCircularNode =============================================
// x and y coordinates and radius r ------------------------------------------
// x and y coordinates and radius r --------------------------------------
num = packRootNode.x;
num = packRootNode.y;
@@ -724,10 +742,11 @@ num = packRootNode.height;
// children, parent ------------------------------------------------------
hierarchyCircularNodeArray = packRootNode.children;
hierarchyCircularNodeArrayOrUndefined = packRootNode.children;
let parentCircularNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>;
let parentCircularNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId> | null;
parentCircularNode = hierarchyCircularNodeArray.length ? hierarchyCircularNodeArray[0].parent : null;
parentCircularNode = hierarchyCircularNodeArray[0].parent;
// id --------------------------------------------------------------------
@@ -738,17 +757,17 @@ idString = packRootNode.id;
const circularNodeAncestors: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.ancestors();
const circularNodeDescendants: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.descendants();
// leaves() ---------------------------------------------------------------
// leaves() --------------------------------------------------------------
hierarchyCircularNodeArray = packRootNode.leaves();
// path() -------------------------------------------------------------------
// path() ----------------------------------------------------------------
hierarchyCircularNode = circularNodeDescendants[circularNodeDescendants.length - 1];
const packPath: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.path(hierarchyCircularNode);
// links() and HierarchyRectangularLink<...> ------------------------------------------
// links() and HierarchyRectangularLink<...> -----------------------------
let circularLinks: Array<d3Hierarchy.HierarchyCircularLink<HierarchyDatumWithParentId>>;
@@ -760,26 +779,27 @@ circularLink = circularLinks[0];
hierarchyCircularNode = circularLink.source;
hierarchyCircularNode = circularLink.target;
// sum() and value ----------------------------------------------------------
// sum() and value -------------------------------------------------------
packRootNode = packRootNode.sum((d) => d.val);
num = packRootNode.value;
numOrUndefined = packRootNode.value;
// count() and value ----------------------------------------------------------
// count() and value -----------------------------------------------------
packRootNode = packRootNode.count();
num = packRootNode.value;
// sort ---------------------------------------------------------------------
numOrUndefined = packRootNode.value;
// sort ------------------------------------------------------------------
packRootNode = packRootNode.sort((a, b) => {
console.log('radius of a:', a.r, ' and b:', b.r); // a and b are of type HierarchyCircularNode<HierarchyDatumWithParentId>
console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyCircularNode<HierarchyDatumWithParentId>
return b.height - a.height || b.value - a.value;
return b.height - a.height || b.value! - a.value!;
});
// each(), eachAfter(), eachBefore() ----------------------------------------
// each(), eachAfter(), eachBefore() -------------------------------------
packRootNode = packRootNode.each((node) => {
console.log('ParentId:', node.data.parentId); // node type is HierarchyCircularNode<HierarchyDatumWithParentId>
@@ -796,7 +816,7 @@ packRootNode = packRootNode.eachBefore((node) => {
console.log('Radius of node:', node.r); // node type is HierarchyCircularNode<HierarchyDatumWithParentId>
});
// copy() --------------------------------------------------------------------
// copy() ----------------------------------------------------------------
let copiedPackNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>;
copiedPackNode = packRootNode.copy();
+5 -5
View File
@@ -154,7 +154,7 @@ export interface HierarchyNode<Datum> {
* Must return an array of data representing the children, and return null or undefined if the current datum has no children.
* If children is not specified, it defaults to: `(d) => d.children`.
*/
export function hierarchy<Datum>(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode<Datum>;
export function hierarchy<Datum>(data: Datum, children?: (d: Datum) => (Datum[] | null | undefined)): HierarchyNode<Datum>;
// -----------------------------------------------------------------------
// Stratify
@@ -182,7 +182,7 @@ export interface StratifyOperator<Datum> {
*
* @param id The id accessor.
*/
id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
id(id: (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined)): this;
/**
* Returns the current parent id accessor, which defaults to: `(d) => d.parentId`.
@@ -197,7 +197,7 @@ export interface StratifyOperator<Datum> {
*
* @param parentId The parent id accessor.
*/
parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
parentId(parentId: (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined)): this;
}
/**
@@ -576,7 +576,7 @@ export interface TreemapLayout<Datum> {
*/
export function treemap<Datum>(): TreemapLayout<Datum>;
// Tiling functions -----------------------------------------------------------------------
// Tiling functions ------------------------------------------------------
/**
* Recursively partitions the specified nodes into an approximately-balanced binary tree,
@@ -748,7 +748,7 @@ export interface PackLayout<Datum> {
*
* @param radius The specified radius accessor.
*/
radius(radius: (node: HierarchyCircularNode<Datum>) => number): this;
radius(radius: null | ((node: HierarchyCircularNode<Datum>) => number)): this;
/**
* Returns the current size, which defaults to [1, 1].
+1 -1
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
+1 -1
View File
@@ -1184,7 +1184,7 @@ interface SymbolDatum {
let customSymbol: d3Shape.SymbolType;
customSymbol = {
draw(context: CanvasPathMethods, size: number): void {
draw(context: d3Shape.CanvasPath_D3Shape, size: number): void {
// draw custom symbol using canvas path methods
}
};
+24 -3
View File
@@ -7,6 +7,27 @@
import { Path } from 'd3-path';
// -----------------------------------------------------------------------------------
// Shared Types and Interfaces
// -----------------------------------------------------------------------------------
/**
* @deprecated
* This interface is used to bridge the gap between two incompatible versions of TypeScript (see [#25944](https://github.com/Microsoft/TypeScript/pull/25944)).
* Use `CanvasPathMethods` instead with TS <= 3.0 and `CanvasPath` with TS >= 3.1.
*/
export interface CanvasPath_D3Shape {
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
closePath(): void;
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
lineTo(x: number, y: number): void;
moveTo(x: number, y: number): void;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
rect(x: number, y: number, w: number, h: number): void;
}
// -----------------------------------------------------------------------------------
// Arc Generator
// -----------------------------------------------------------------------------------
@@ -2264,13 +2285,13 @@ export function linkRadial<This, LinkDatum, NodeDatum>(): LinkRadial<This, LinkD
*/
export interface SymbolType {
/**
* Renders this symbol type to the specified context with the specified size in square pixels. The context implements the CanvasPathMethods interface.
* Renders this symbol type to the specified context with the specified size in square pixels. The context implements the CanvasPath interface.
* (Note that this is a subset of the CanvasRenderingContext2D interface!)
*
* @param context A rendering context implementing CanvasPathMethods.
* @param context A rendering context implementing CanvasPath.
* @param size Size of the symbol to draw.
*/
draw(context: CanvasPathMethods, size: number): void;
draw(context: CanvasPath_D3Shape, size: number): void;
}
/**
+250
View File
@@ -0,0 +1,250 @@
import * as dav from "dav";
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
);
dav.createAccount({ server: 'http://dav.example.com', xhr })
.then((account) => {
account.calendars.forEach(() => {
});
});
const client = new dav.Client(xhr);
client.createAccount({
server: 'http://dav.example.com',
accountType: 'carddav'
}).then((account) => {
account.addressBooks.forEach(() => {
});
});
})();
(() => {
const client = new dav.Client(
new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
),
{
baseUrl: 'https://mail.mozilla.com'
}
);
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: '12345'
});
client.send(req, '/calendars/123.ics')
.then(() => { });
})();
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
);
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: '12345'
});
xhr.send(req, 'https://mail.mozilla.com/calendars/123.ics')
.then(() => {
});
})();
dav.debug.enabled = true;
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'Killer BOB',
password: 'blacklodge'
})
);
const client = new dav.Client(xhr, { baseUrl: 'https://mail.mozilla.com' });
const url = 'https://mail.mozilla.com/';
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: 'abc123'
});
const sandbox = dav.createSandbox();
client.send(req, url, { sandbox });
xhr.send(req, url, { sandbox });
client.createAccount({ sandbox: {}, server: 'http://dav.example.com' });
dav.createAccount({
sandbox: {},
server: 'http://dav.example.com',
xhr
});
let calendar = new dav.Calendar();
client.createCalendarObject(calendar, {
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
filename: 'test.ics'
});
dav.createCalendarObject(
calendar,
{
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
filename: 'test.ics',
xhr
});
let object = new dav.CalendarObject();
client.updateCalendarObject(object);
dav.updateCalendarObject(
object,
{
xhr
}
);
object = new dav.CalendarObject();
client.deleteCalendarObject(object);
dav.deleteCalendarObject(
object,
{
xhr
}
);
calendar = new dav.Calendar();
client.syncCalendar(calendar, { syncMethod: 'webdav' });
dav.syncCalendar(
calendar,
{
syncMethod: 'webdav',
xhr
}
);
let account = new dav.Account();
client.syncCaldavAccount(account, { syncMethod: 'webdav' });
dav.syncCaldavAccount(
account,
{
syncMethod: 'webdav',
xhr
}
);
let addressBook = new dav.AddressBook();
client.createCard(addressBook, {
data: 'BEGIN:VCARD\nEND:VCARD',
filename: 'test.vcf'
});
dav.createCard(addressBook,
{
data: 'BEGIN:VCARD\nEND:VCARD',
filename: 'test.vcf',
xhr
});
let vcard = new dav.VCard();
client.updateCard(vcard);
dav.updateCard(
vcard,
{
xhr
}
);
vcard = new dav.VCard();
client.deleteCard(vcard);
dav.deleteCard(
vcard,
{
xhr
});
addressBook = new dav.AddressBook();
client.syncAddressBook(addressBook, {
syncMethod: 'basic'
});
dav.syncAddressBook(
addressBook,
{
syncMethod: 'basic',
xhr
});
account = new dav.Account();
client.syncCarddavAccount(account, { syncMethod: 'basic' });
dav.syncCarddavAccount(
account,
{
syncMethod: 'basic',
xhr
});
})();
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({ username: 'admin', password: 'admin' })
);
const req: dav.Request = {
method: 'GET',
transformRequest: (xhr: any) => xhr
};
const sandbox = dav.createSandbox();
xhr.send(req, 'http://127.0.0.1:1337', { sandbox });
sandbox.requestList;
xhr.send(req, 'http://127.0.0.1:1337');
})();
(() => {
const credentials = new dav.Credentials({
clientId: '605300196874-1ki833poa7uqabmh3hq' +
'6u1onlqlsi54h.apps.googleusercontent.com',
clientSecret: 'jQTKlOhF-RclGaGJot3HIcVf',
redirectUrl: 'https://oauth.gaiamobile.org/authenticated',
tokenUrl: 'https://accounts.google.com/o/oauth2/token',
authorizationCode: 'gareth'
});
const xhr = new dav.transport.OAuth2(credentials);
const req = { method: 'GET' };
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = '1/oPHTPFgECWFPrs7KgHdis24u6Xl4E4EnRrkkiwLfzdk';
credentials.expiration = Date.now() - 1;
xhr.send(req, 'http://127.0.0.1:1337', {
retry: false
});
credentials.accessToken = 'Little Bear';
credentials.refreshToken = 'spicy tamales';
const expiration = credentials.expiration = Date.now() + 60 * 60 * 1000;
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = 'raspberry pie';
credentials.expiration = Date.now() + 60 * 60 * 1000;
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = 'soda';
})();
+804
View File
@@ -0,0 +1,804 @@
// Type definitions for dav 1.7
// Project: https://github.com/lambdabaa/dav/
// Definitions by: ToastHawaii <https://github.com/ToastHawaii>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export let version: string;
/**
* Perform an initial download of a caldav or carddav account's data.
* @param options
* @returns a Promise which will be fulfilled with a dav.Account object.
*/
export function createAccount(options: CreateAccountOptions): Promise<Account>;
export interface CreateAccountOptions {
/**
* one of 'caldav' or 'carddav'. Defaults to 'caldav'.
*/
accountType?: "caldav" | "carddav";
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* whether or not to load dav collections.
*/
loadCollections?: boolean;
/**
* whether or not to load dav objects.
*/
loadObjects?: boolean;
/**
* request sandox.
*/
sandbox?: Sandbox | {};
/**
* some url for server (needn't be base url).
*/
server: string;
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a calendar object on the parameter calendar.
* @param calendar the calendar to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been created.
*/
export function createCalendarObject(calendar: Calendar, options: CreateCalendarObjectOptions): Promise<CalendarObject>;
export interface CreateCalendarObjectOptions {
/**
* rfc 5545 VCALENDAR object.
*/
data: string;
/**
* name for the calendar ics file.
*/
filename: string;
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Persist updates to the parameter calendar object to the server.
* @param calendarObject updated calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been updated.
*/
export function updateCalendarObject(calendarObject: CalendarObject, options: UpdateCalendarObjectOptions): Promise<CalendarObject>;
export interface UpdateCalendarObjectOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Delete the parameter calendar object on the server.
* @param calendarObject target calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been deleted.
*/
export function deleteCalendarObject(calendarObject: CalendarObject, options: DeleteCalendarObjectOptions): Promise<CalendarObject>;
export interface DeleteCalendarObjectOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the parameter calendar.
* @param calendar the calendar to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Calendar object once sync is complete.
*/
export function syncCalendar(calendar: Calendar, options: SyncCalendarOptions): Promise<Calendar>;
export interface SyncCalendarOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the account's calendars.
* @param account the calendar account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Account object once sync is complete.
*/
export function syncCaldavAccount(account: Account, options: SyncCaldavAccountOptions): Promise<Account>;
export interface SyncCaldavAccountOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a vcard object on the parameter address book.
* @param addressBook the address book to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been created.
*/
export function createCard(addressBook: AddressBook, options: CreateCardOptions): Promise<AddressBook>;
export interface CreateCardOptions {
/**
* VCARD object.
*/
data: string;
/**
* name for the vcard vcf file.
*/
filename: string;
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Persist updates to the parameter vcard object to the server.
* @param card updated vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been updated.
*/
export function updateCard(card: VCard, options: UpdateCardOptions): Promise<VCard>;
export interface UpdateCardOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Delete the parameter vcard object on the server.
* @param card target vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been deleted.
*/
export function deleteCard(card: VCard, options: DeleteCardOptions): Promise<VCard>;
export interface DeleteCardOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the parameter address books.
* @param addressBook the address book to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated AddressBook object once sync is complete.
*/
export function syncAddressBook(addressBook: AddressBook, options: SyncAddressBookOptions): Promise<AddressBook>;
export interface SyncAddressBookOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'.If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the account's address books.
* @param account the address book account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated Account object once sync is complete.
*/
export function syncCarddavAccount(account: Account, options: SyncCarddavAccountOptions): Promise<Account>;
export interface SyncCarddavAccountOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a request sandbox.
*/
export class Sandbox {
constructor();
requestList: any[];
add(request: any): void;
/**
* abort sandboxed requests as a group.
*/
abort(): void;
}
/**
* @deprecated
*/
export function createSandbox(): Sandbox;
export namespace transport {
class Transport {
/**
* @param credentials user authorization.
*/
constructor(credentials: Credentials);
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
interface TransportOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
retry?: boolean;
}
class Basic extends Transport {
/**
* Create a new Basic object. This sends dav requests using http basic authentication.
* @param credentials user authorization.
*/
constructor(credentials: Credentials);
/**
*
* @param request object with request info.
* @param url
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
/**
* Create a new OAuth2 object.This sends dav requests authorized via rfc 6749 oauth2.
* @param credentials user authorization.
*/
class OAuth2 extends Transport {
constructor(credentials: Credentials);
/**
*
* @param request object with request info.
* @param url
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
}
export namespace request {
/**
*
* @param options
* @returns
*/
function addressBookQuery(options: AddressBookQueryOptions): string;
interface AddressBookQueryOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
}
/**
*
* @param options
* @returns
*/
function basic(options: BasicOptions): Request;
interface BasicOptions {
/**
* put request body.
*/
data: string;
/**
* http method.
*/
method: string;
/**
* cached calendar object etag.
*/
etag: string;
}
/**
*
* @param options
* @returns
*/
function calendarQuery(options: CalendarQueryOptions): string;
interface CalendarQueryOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of filters to send with request.
*/
filters: object[];
/**
* list of props to request.
*/
props: object[];
/**
* VTIMEZONE calendar object.
*/
timezone: string;
}
/**
*
* @param options
* @returns
*/
function propfind(options: PropfindOptions): string;
interface PropfindOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
}
/**
*
* @param options
* @returns
*/
function syncCollection(options: SyncCollectionOptions): string;
interface SyncCollectionOptions {
/**
* option value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
/**
* indicates scope of the sync report request.
*/
syncLevel: number;
/**
* synchronization token provided by the server.
*/
syncToken: string;
}
}
export class Client {
/**
* Create a new Client object. The client interface allows consumers to set
* their credentials and transport once and then make authorized requests
* without passing them to each request. Each of the other, public API
* methods should be available on Client objects.
* @param xhr request sender.
* @param options
*/
constructor(xhr: transport.Transport, options?: ClientOptions);
/**
* Send a request using this client's transport (and perhaps baseUrl).
* @param req dav request.
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(req: Request, uri: string, options?: ClientSendOptions): Promise<any>;
/**
* Perform an initial download of a caldav or carddav account's data.
* @param options
* @returns a Promise which will be fulfilled with a dav.Account object.
*/
createAccount(options?: CreateAccountOptions): Promise<Account>;
/**
* Create a calendar object on the parameter calendar.
* @param calendar the calendar to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been created.
*/
createCalendarObject(calendar: Calendar, options?: CreateCalendarObjectOptions): Promise<CalendarObject>;
/**
* Persist updates to the parameter calendar object to the server.
* @param calendarObject updated calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been updated.
*/
updateCalendarObject(calendarObject: CalendarObject, options?: UpdateCalendarObjectOptions): Promise<CalendarObject>;
/**
* Delete the parameter calendar object on the server.
* @param calendarObject target calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been deleted.
*/
deleteCalendarObject(calendarObject: CalendarObject, options?: DeleteCalendarObjectOptions): Promise<CalendarObject>;
/**
* Fetch changes from the remote server to the parameter calendar.
* @param calendar the calendar to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Calendar object once sync is complete.
*/
syncCalendar(calendar: Calendar, options?: SyncCalendarOptions): Promise<Calendar>;
/**
* Fetch changes from the remote server to the account's calendars.
* @param account the calendar account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Account object once sync is complete.
*/
syncCaldavAccount(account: Account, options?: SyncCaldavAccountOptions): Promise<Account>;
/**
* Create a vcard object on the parameter address book.
* @param addressBook the address book to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been created.
*/
createCard(addressBook: AddressBook, options?: CreateCardOptions): Promise<AddressBook>;
/**
* Persist updates to the parameter vcard object to the server.
* @param card updated vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been updated.
*/
updateCard(card: VCard, options?: UpdateCardOptions): Promise<VCard>;
/**
*
* Delete the parameter vcard object on the server.
* @param card target vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been deleted.
*/
deleteCard(card: VCard, options?: DeleteCardOptions): Promise<VCard>;
/**
* Fetch changes from the remote server to the parameter address books.
* @param addressBook the address book to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated AddressBook object once sync is complete.
*/
syncAddressBook(addressBook: AddressBook, options?: SyncAddressBookOptions): Promise<AddressBook>;
/**
* Fetch changes from the remote server to the account's address books.
* @param account the address book account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated Account object once sync is complete.
*/
syncCarddavAccount(account: Account, options?: SyncCarddavAccountOptions): Promise<Account>;
}
export interface ClientOptions {
/**
* root url to resolve relative request urls with.
*/
baseUrl: string;
}
export interface ClientSendOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* relative url for request.
*/
url?: string;
}
export type Partial<T> = {
[P in keyof T]?: T[P];
};
export class Account {
constructor(options?: AccountOptions);
server: string;
credentials: Credentials;
rootUrl: string;
principalUrl: string;
homeUrl: string;
calendars: Calendar[];
addressBooks: AddressBook[];
}
export type AccountOptions = Partial<Account>;
export class Credentials {
constructor(options?: CredentialsOptions);
/**
* username (perhaps email) for calendar user.
*/
username: string;
/**
* plaintext password for calendar user.
*/
password: string;
/**
* oauth client id.
*/
clientId: string;
/**
* oauth client secret.
*/
clientSecret: string;
/**
* oauth code.
*/
authorizationCode: string;
/**
* oauth redirect url.
*/
redirectUrl: string;
/**
* oauth token url.
*/
tokenUrl: string;
/**
* oauth access token.
*/
accessToken: string;
/**
* oauth refresh token.
*/
refreshToken: string;
/**
* unix time for access token expiration.
*/
expiration: number;
}
export type CredentialsOptions = Partial<Credentials>;
export class DAVCollection<T> {
constructor(options: DAVCollectionOptions<T>);
data: string;
objects: T[];
account: Account;
ctag: string;
description: string;
displayName: string;
reports: string[];
resourcetype: string;
syncToken: string;
url: string;
}
export type DAVCollectionOptions<T> = Partial<DAVCollection<T>>;
export class AddressBook extends DAVCollection<VCard> {
constructor(options?: AddressBookOptions);
}
export type AddressBookOptions = Partial<AddressBook>;
export class Calendar extends DAVCollection<CalendarObject> {
constructor(options?: CalendarOptions);
components: string[];
timezone: string;
}
export type CalendarOptions = Partial<Calendar>;
export class DAVObject {
constructor(options: DAVObjectOptions);
data: string;
etag: string;
url: string;
}
export type DAVObjectOptions = Partial<DAVObject>;
export class CalendarObject extends DAVObject {
constructor(options?: CalendarObjectOptions);
calendar: Calendar;
calendarData: string;
}
export type CalendarObjectOptions = Partial<CalendarObject>;
export class VCard extends DAVObject {
constructor(options?: VCardOptions);
addressBook: AddressBook;
addressData: string;
}
export type VCardOptions = Partial<VCard>;
export class Request {
constructor(options?: RequestOptions);
method: string;
requestData?: string;
transformRequest?: (xhr: any) => any;
transformResponse?: (xhr: any) => any;
onerror?: (error: Error) => any;
}
export type RequestOptions = Partial<Request>;
export namespace debug {
let enabled: boolean;
}
export namespace ns {
const CALENDAR_SERVER = 'http://calendarserver.org/ns/';
const CALDAV_APPLE = 'http://apple.com/ns/ical/';
const CALDAV = 'urn:ietf:params:xml:ns:caldav';
const CARDDAV = 'urn:ietf:params:xml:ns:carddav';
const DAV = 'DAV:';
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"dav-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+13 -3
View File
@@ -1,7 +1,7 @@
import * as ddTrace from 'dd-trace';
import * as tracer from 'dd-trace';
import SpanContext = require('dd-trace/src/opentracing/span_context');
const tracer = ddTrace.init({
tracer.init({
service: 'MyLovelyService',
hostname: 'localhost',
port: 8126,
@@ -14,7 +14,7 @@ const tracer = ddTrace.init({
tracer
.trace('web.request', {
service: 'my_service',
childOf: new SpanContext({ traceId: 1337, spanId: 42 }),
childOf: new SpanContext({ traceId: 1337, spanId: 42 }), // Childof must be an instance of this type. See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99
tags: {
env: 'dev'
}
@@ -23,3 +23,13 @@ tracer
span.setTag('my_tag', 'my_value');
span.finish();
});
const parentScope = tracer.scopeManager().active();
const span = tracer.startSpan('memcached', {
childOf: parentScope && parentScope.span(),
tags: {
'service.name': 'my-memcached',
'resource.name': 'get',
'span.type': 'memcached',
},
});
+43 -5
View File
@@ -1,11 +1,11 @@
// Type definitions for dd-trace-js 0.2
// Type definitions for dd-trace-js 0.5
// Project: https://github.com/DataDog/dd-trace-js
// Definitions by: Colin Bradley <https://github.com/ColinBradley>
// Eloy Durán <https://github.com/alloy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Tracer = require('./src/opentracing/tracer');
import Span = require('./src/opentracing/span');
import SpanContext = require('./src/opentracing/span_context');
import { Tracer, Span, SpanContext } from "opentracing";
import DatadogSpanContext = require('./src/opentracing/span_context');
declare var trace: TraceProxy;
export = trace;
@@ -42,6 +42,11 @@ declare class TraceProxy extends Tracer {
* @returns The current span or null if outside a trace context.
*/
currentSpan(): Span | null;
/**
* Get the scope manager to manager context propagation for the tracer.
*/
scopeManager(): ScopeManager;
}
interface TracerOptions {
@@ -139,11 +144,44 @@ interface TraceOptions {
/**
* The parent span or span context for the new span. Generally this is not needed as it will be
* fetched from the current context.
* If creating your own, this must be an instance of DatadogSpanContext from ./src/opentracing/span_context
* See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99
*/
childOf?: Span | SpanContext;
childOf?: Span | SpanContext | DatadogSpanContext;
/**
* Global tags that should be assigned to every span.
*/
tags?: { [key: string]: any } | string;
}
declare class ScopeManager {
/**
* Get the current active scope or null if there is none.
*
* @todo The dd-trace source returns null, but opentracing's childOf span
* option is typed as taking undefined or a scope, so using undefined
* here instead.
*/
active(): Scope | undefined;
/**
* Activate a new scope wrapping the provided span.
*
* @param span The span for which to activate the new scope.
* @param finishSpanOnClose Whether to automatically finish the span when the scope is closed.
*/
activate(span: Span, finishSpanOnClose?: boolean): Scope;
}
declare class Scope {
/**
* Get the span wrapped by this scope.
*/
span(): Span;
/**
* Close the scope, and finish the span if the scope was created with `finishSpanOnClose` set to true.
*/
close(): void;
}
@@ -1,6 +1,6 @@
{
"private": true,
"dependencies": {
"styled-components": "^3.3.2"
"opentracing": ">=0.14.1"
}
}
-29
View File
@@ -1,29 +0,0 @@
import Span = require('./span');
import SpanContext = require('./span_context');
declare class Reference {
/**
* @return The Reference type (e.g., REFERENCE_CHILD_OF or
* REFERENCE_FOLLOWS_FROM).
*/
type(): string;
/**
* @return The SpanContext being referred to (e.g., the
* parent in a REFERENCE_CHILD_OF Reference).
*/
referencedContext(): SpanContext;
/**
* Initialize a new Reference instance.
*
* @param type - the Reference type constant (e.g.,
* REFERENCE_CHILD_OF or REFERENCE_FOLLOWS_FROM).
* @param referencedContext - the SpanContext being referred
* to. As a convenience, a Span instance may be passed in instead
* (in which case its .context() is used here).
*/
constructor(type: string, referencedContext: SpanContext | Span);
}
export = Reference;
-120
View File
@@ -1,120 +0,0 @@
import Tracer = require('./tracer');
import SpanContext = require('./span_context');
declare class Span {
/**
* Returns the SpanContext object associated with this Span.
*/
context(): SpanContext;
/**
* Returns the Tracer object used to create this Span.
*/
tracer(): Tracer;
/**
* Sets the string name for the logical operation this span represents.
*/
setOperationName(name: string): this;
/**
* Sets a key:value pair on this Span that also propagates to future
* children of the associated Span.
*
* setBaggageItem() enables powerful functionality given a full-stack
* opentracing integration (e.g., arbitrary application data from a web
* client can make it, transparently, all the way into the depths of a
* storage system), and with it some powerful costs: use this feature with
* care.
*
* IMPORTANT NOTE #1: setBaggageItem() will only propagate baggage items to
* *future* causal descendants of the associated Span.
*
* IMPORTANT NOTE #2: Use this thoughtfully and with care. Every key and
* value is copied into every local *and remote* child of the associated
* Span, and that can add up to a lot of network and cpu overhead.
*/
setBaggageItem(key: string, value: string): this;
/**
* Returns the value for a baggage item given its key.
*
* @param key
* The key for the given trace attribute.
* @return String value for the given key, or undefined if the key does not
* correspond to a set trace attribute.
*/
getBaggageItem(key: string): string | undefined;
/**
* Adds a single tag to the span. See `addTags()` for details.
*/
setTag(key: string, value: any): this;
/**
* Adds the given key value pairs to the set of span tags.
*
* Multiple calls to addTags() results in the tags being the superset of
* all calls.
*
* The behavior of setting the same key multiple times on the same span
* is undefined.
*
* The supported type of the values is implementation-dependent.
* Implementations are expected to safely handle all types of values but
* may choose to ignore unrecognized / unhandle-able values (e.g. objects
* with cyclic references, function objects).
*/
addTags(keyValueMap: {
[key: string]: any;
}): this;
/**
* Add a log record to this Span, optionally at a user-provided timestamp.
*
* For example:
*
* span.log({
* size: rpc.size(), // numeric value
* URI: rpc.URI(), // string value
* payload: rpc.payload(), // Object value
* "keys can be arbitrary strings": rpc.foo(),
* });
*
* span.log({
* "error.description": someError.description(),
* }, someError.timestampMillis());
*
* @param keyValuePairs
* An object mapping string keys to arbitrary value types. All
* Tracer implementations should support bool, string, and numeric
* value types, and some may also support Object values.
* @param timestamp
* An optional parameter specifying the timestamp in milliseconds
* since the Unix epoch. Fractional values are allowed so that
* timestamps with sub-millisecond accuracy can be represented. If
* not specified, the implementation is expected to use its notion
* of the current time of the call.
*/
log(keyValuePairs: {
[key: string]: any;
}, timestamp?: number): this;
/**
* Sets the end timestamp and finalizes Span state.
*
* With the exception of calls to Span.context() (which are always allowed),
* finish() must be the last call made to any span instance, and to do
* otherwise leads to undefined behavior.
*
* @param finishTime
* Optional finish time in milliseconds as a Unix timestamp. Decimal
* values are supported for timestamps with sub-millisecond accuracy.
* If not specified, the current time (as defined by the
* implementation) will be used.
*/
finish(finishTime?: number): void;
}
export = Span;
+14 -24
View File
@@ -1,38 +1,28 @@
/**
* SpanContext represents Span state that must propagate to descendant Spans
* and across process boundaries.
*
* SpanContext is logically divided into two pieces: the user-level "Baggage"
* (see setBaggageItem and getBaggageItem) that propagates across Span
* boundaries and any Tracer-implementation-specific fields that are needed to
* identify or otherwise contextualize the associated Span instance (e.g., a
* <trace_id, span_id, sampled> tuple).
*/
declare class SpanContext {
import { SpanContext } from 'opentracing';
declare class DatadogSpanContext extends SpanContext {
/**
* Use to create references to parent spans.
* Used to create references to parent spans.
* See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99
*/
constructor(props: SpanContextLike);
}
public traceId: number;
interface SpanContextLike {
traceId: number;
public spanId: number;
spanId: number;
public parentId?: number | null;
parentId?: number | null;
public sampled?: boolean;
sampled?: boolean;
public baggageItems?: { [key: string]: string };
baggageItems?: { [key: string]: string };
public trace?: {
trace?: {
started: number[],
finished: number[]
}
}
interface SpanContextLike {
traceId: number;
spanId: number;
}
export = SpanContext;
export = DatadogSpanContext;
-37
View File
@@ -1,37 +0,0 @@
import Span = require('./span');
import Reference = require('./reference');
import SpanContext = require('./span_context');
interface SpanOptions {
/**
* a parent SpanContext (or Span, for convenience) that the newly-started
* span will be the child of (per REFERENCE_CHILD_OF). If specified,
* `references` must be unspecified.
*/
childOf?: Span | SpanContext;
/**
* an array of Reference instances, each pointing to a causal parent
* SpanContext. If specified, `fields.childOf` must be unspecified.
*/
references?: Reference[];
/**
* set of key-value pairs which will be set as tags on the newly created
* Span. Ownership of the object is passed to the created span for
* efficiency reasons (the caller should not modify this object after
* calling startSpan).
*/
tags?: {
[key: string]: any;
};
/**
* a manually specified start time for the created Span object. The time
* should be specified in milliseconds as Unix timestamp. Decimal value are
* supported to represent time values with sub-millisecond accuracy.
*/
startTime?: number;
}
export = SpanOptions;
-91
View File
@@ -1,91 +0,0 @@
import SpanOptions = require('./span_options');
import Span = require('./span');
import SpanContext = require('./span_context');
/**
* Tracer is the entry-point between the instrumentation API and the tracing
* implementation.
*/
declare class Tracer {
/**
* Starts and returns a new Span representing a logical unit of work.
*
* For example:
*
* // Start a new (parentless) root Span:
* var parent = Tracer.startSpan('DoWork');
*
* // Start a new (child) Span:
* var child = Tracer.startSpan('load-from-db', {
* childOf: parent.context(),
* });
*
* // Start a new async (FollowsFrom) Span:
* var child = Tracer.startSpan('async-cache-write', {
* references: [
* opentracing.followsFrom(parent.context())
* ],
* });
*
* @param name - the name of the operation (REQUIRED).
* @param options - options for the newly created span.
* @return A new Span object.
*/
startSpan(name: string, options?: SpanOptions): Span;
/**
* Injects the given SpanContext instance for cross-process propagation
* within `carrier`. The expected type of `carrier` depends on the value of
* `format.
*
* OpenTracing defines a common set of `format` values (see
* FORMAT_TEXT_MAP, FORMAT_HTTP_HEADERS, and FORMAT_BINARY), and each has
* an expected carrier type.
*
* Consider this pseudocode example:
*
* var clientSpan = ...;
* ...
* // Inject clientSpan into a text carrier.
* var headersCarrier = {};
* Tracer.inject(clientSpan.context(), Tracer.FORMAT_HTTP_HEADERS, headersCarrier);
* // Incorporate the textCarrier into the outbound HTTP request header
* // map.
* Object.assign(outboundHTTPReq.headers, headersCarrier);
* // ... send the httpReq
*
* @param spanContext - the SpanContext to inject into the
* carrier object. As a convenience, a Span instance may be passed
* in instead (in which case its .context() is used for the
* inject()).
* @param format - the format of the carrier.
* @param carrier - see the documentation for the chosen `format`
* for a description of the carrier object.
*/
inject(spanContext: SpanContext | Span, format: string, carrier: any): void;
/**
* Returns a SpanContext instance extracted from `carrier` in the given
* `format`.
*
* OpenTracing defines a common set of `format` values (see
* FORMAT_TEXT_MAP, FORMAT_HTTP_HEADERS, and FORMAT_BINARY), and each has
* an expected carrier type.
*
* Consider this pseudocode example:
*
* // Use the inbound HTTP request's headers as a text map carrier.
* var headersCarrier = inboundHTTPReq.headers;
* var wireCtx = Tracer.extract(Tracer.FORMAT_HTTP_HEADERS, headersCarrier);
* var serverSpan = Tracer.startSpan('...', { childOf : wireCtx });
*
* @param format - the format of the carrier.
* @param carrier - the type of the carrier object is determined by
* the format.
* @return The extracted SpanContext, or null if no such SpanContext could
* be found in `carrier`
*/
extract(format: string, carrier: any): SpanContext | null;
}
export = Tracer;
+10
View File
@@ -0,0 +1,10 @@
import * as dialogflow from "dialogflow";
const agentsClient = new dialogflow.AgentsClient();
const contextsClient = new dialogflow.ContextsClient();
const entityTypesClient = new dialogflow.EntityTypesClient();
const intentsClient = new dialogflow.IntentsClient();
const sessionEntityTypesClient = new dialogflow.SessionEntityTypesClient();
const sessionsClient = new dialogflow.SessionsClient();
// TODO: Add real significant tests
+927
View File
@@ -0,0 +1,927 @@
// Type definitions for dialogflow 0.6
// Project: https://github.com/dialogflow/dialogflow-nodejs-client-v2#readme
// Definitions by: Daniel Dyla <https://github.com/dyladan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export namespace v2 {
class AgentsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
getAgent(
request: GetAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, agent: Agent) => void
): Promise<[Agent]>;
searchAgents(
request: SearchAgentRequest,
options?: gax.CallOptions,
cb?: (
err: Error,
agents: Agent[],
arg3: any,
response: any
) => void
): Promise<Agent[]>;
searchAgentsStream(
request: SearchAgentRequest,
options?: gax.CallOptions
): any;
trainAgent(
request: TrainAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
exportAgent(
request: ExportAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
importAgent(
request: ImportAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
restoreAgent(
request: RestoreAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
}
class ContextsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listContexts(
request: ListContextsRequest,
options?: gax.CallOptions
): Promise<[Context[]]>;
listContextsStream(
request: ListContextsRequest,
options?: gax.CallOptions
): any;
getContext(
request: GetContextRequest,
options?: gax.CallOptions
): Promise<[Context]>;
createContext(
request: CreateContextReqeust,
options?: gax.CallOptions
): Promise<[Context]>;
updateContext(
request: UpdateContextRequest,
options?: gax.CallOptions
): Promise<[Context]>;
deleteContext(
request: DeleteContextRequest,
options?: gax.CallOptions
): Promise<void>;
deleteAllContexts(
request: DeleteAllContextsRequest,
options?: gax.CallOptions
): Promise<void>;
sessionPath(project: string, session: string): string;
contextPath(project: string, session: string, context: string): string;
matchProjectFromContextName(name: string): string;
matchSessionFromContextName(name: string): string;
matchContextFromContextName(name: string): string;
matchProjectFromSessionName(name: string): string;
matchSessionFromSessionName(name: string): string;
}
class EntityTypesClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listEntityTypes(
request: ListEntityTypesRequest,
options?: gax.CallOptions
): Promise<[EntityType[]]>;
listEntityTypesStream(
request: ListEntityTypesRequest,
options?: gax.CallOptions
): any;
getEntityType(
request: GetEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
createEntityType(
request: CreateEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
updateEntityType(
request: UpdateEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
deleteEntityType(
request: DeleteEntityTypeRequest,
options?: gax.CallOptions
): Promise<void>;
// TODO: add batch style calls
// batchUpdateEntityTypes
// batchDeleteEntityTypes
// batchCreateEntities
// batchUpdateEntities
// batchDeleteEntities
projectAgentPath(project: string): string;
entityTypePath(project: string, entityType: string): string;
matchProjectFromProjectAgentName(entityTypeName: string): string;
matchProjectFromEntityTypeName(entityTypeName: string): string;
matchEntityTypeFromEntityTypeName(entityTypeName: string): string;
}
class IntentsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listIntents(
request: ListIntentsRequest,
options?: gax.CallOptions
): Promise<[Intent[]]>;
getIntent(
request: GetIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
createIntent(
request: CreateIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
updateIntent(
request: UpdateIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
deleteIntent(
request: DeleteIntentRequest,
options?: gax.CallOptions
): Promise<void>;
// TODO: add batch style calls
// batchUpdateIntents(request: BatchUpdateIntentsRequest): void;
// batchDeleteIntents(request: BatchDeleteIntentsRequest): void;
projectAgentPath(project: string): string;
intentPath(project: string, intent: string): string;
agentPath(project: string, agent: string): string;
matchProjectFromProjectAgentName(projectAgentName: string): string;
matchProjectFromIntentName(intentName: string): string;
matchIntentFromIntentName(intentName: string): string;
matchProjectFromAgentName(agentName: string): string;
matchAgentFromAgentName(agentName: string): string;
}
class SessionEntityTypesClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
// TODO: add Session Entity Types service methods
}
class SessionsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
detectIntent(
request: DetectIntentRequest,
options?: gax.CallOptions
): Promise<DetectIntentResponse[]>;
streamingDetectIntent(options?: gax.CallOptions): Promise<any>;
sessionPath(projectId: string, sessionId: string): string;
}
}
export namespace v2beta1 {
class AgentsClient extends v2.AgentsClient {}
class ContextsClient extends v2.ContextsClient {
environmentSessionPath(
project: string,
environment: string,
user: string,
session: string
): string;
environmentContextPath(
project: string,
environment: string,
user: string,
session: string,
context: string
): string;
matchProjectFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchEnvironmentFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchUserFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchSessionFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchProjectFromEnvironmentContextName(
environmentContextName: string
): string;
matchEnvironmentFromEnvironmentContextName(
environmentContextName: string
): string;
matchUserFromEnvironmentContextName(
environmentContextName: string
): string;
matchSessionFromEnvironmentContextName(
environmentContextName: string
): string;
matchContextFromEnvironmentContextName(
environmentContextName: string
): string;
}
class EntityTypesClient extends v2.EntityTypesClient {}
class IntentsClient extends v2.IntentsClient {}
class SessionEntityTypesClient extends v2.SessionEntityTypesClient {}
class SessionsClient extends v2.SessionsClient {
environmentSessionPath(
project: string,
environment: string,
user: string,
session: string
): string;
matchProjectFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchEnvironmentFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchUserFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchSessionFromEnvironmentSessionName(
environmentSessionName: string
): string;
}
}
export class AgentsClient extends v2.AgentsClient {}
export class ContextsClient extends v2.ContextsClient {}
export class EntityTypesClient extends v2.EntityTypesClient {}
export class IntentsClient extends v2.IntentsClient {}
export class SessionEntityTypesClient extends v2.SessionEntityTypesClient {}
export class SessionsClient extends v2.SessionsClient {}
export namespace entities {
namespace DateTimeVariants {
interface DateTime {
date_time: string;
}
interface DateTimePeriod {
startDateTime: DateTime;
endDateTime: DateTime;
}
interface DatePeriod {
startDate: Date;
endDate: Date;
}
interface TimePeriod {
startTime: string;
endTime: string;
}
}
type DateTime =
| string
| DateTimeVariants.DatePeriod
| DateTimeVariants.TimePeriod
| DateTimeVariants.DateTime
| DateTimeVariants.DateTimePeriod;
interface Duration {
unit: string;
amount: number;
}
type Date = string;
type Time = string;
}
export namespace gax {
interface BackoffSettings {
initialRetryDelayMillis: number;
retryDelayMultiplier: number;
maxRetryDelayMillis: number;
initialRpcTimeoutMillis: number;
maxRpcTimeoutMillis: number;
totalTimeoutMillis: number;
}
interface RetryOptions {
retryCodes: string[];
backoffSettings: BackoffSettings;
}
interface CallOptions {
timeout?: number;
retry?: RetryOptions;
autoPaginate?: boolean;
pageToken?: any;
isBundling?: boolean;
longrunning?: BackoffSettings;
promise?: PromiseConstructor;
}
interface Operation {
grpcOp: longrunning.Operation;
longrunningDescriptor: any;
backoffSettings: BackoffSettings;
callOptions?: CallOptions;
}
}
export namespace longrunning {
type Operation =
| UnfinishedOperation
| FailedOperation
| SuccessfulOperation;
interface BaseOperation {
name: string;
metadata: any;
done: boolean;
}
interface UnfinishedOperation extends BaseOperation {
done: false;
}
interface FailedOperation extends BaseOperation {
done: true;
error: Status;
}
interface SuccessfulOperation extends BaseOperation {
done: true;
response: any;
}
interface Status {
code: number;
message: string;
details: any[];
}
}
export interface GetAgentRequest {
parent: string;
}
export interface SearchAgentRequest {
parent: string;
pageSize?: number;
}
export interface TrainAgentRequest {
parent: string;
}
export interface ExportAgentRequest {
parent: string;
agentUri?: string;
}
export interface ImportAgentRequest {
parent: string;
agentUri?: string;
agentContent?: string;
}
export interface RestoreAgentRequest {
parent: string;
agentUri?: string;
agentContent?: string;
}
export interface ListContextsRequest {
parent: string;
pageSize?: number;
}
export interface GetContextRequest {
name: string;
}
export interface CreateContextReqeust {
parent: string;
context: Context;
}
export interface UpdateContextRequest {
context: Context;
updatemask?: any;
}
export interface DeleteContextRequest {
name: string;
}
export interface DeleteAllContextsRequest {
parent: string;
}
export interface ListEntityTypesRequest {
parent: string;
languageCode?: string;
pageSize?: number;
}
export interface GetEntityTypeRequest {
name: string;
languageCode?: string;
}
export interface CreateEntityTypeRequest {
parent: string;
entityType: EntityType;
}
export interface UpdateEntityTypeRequest {
entityType: EntityType;
languageCode?: string;
/** @link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto */
updateMask?: any;
}
export interface DeleteEntityTypeRequest {
name: string;
}
export interface ListIntentsRequest {
parent: string;
languageCode?: string;
intentView?: IntentView;
pageSize?: number;
}
export interface GetIntentRequest {
name: string;
languageCode?: string;
intentView?: IntentView;
}
export interface CreateIntentRequest {
parent: string;
intent: Intent;
languageCode?: string;
intentView?: IntentView;
}
export interface UpdateIntentRequest {
intent: Intent;
languageCode?: string;
updateMask?: any;
intentView?: IntentView;
}
export interface DeleteIntentRequest {
name: string;
}
export interface DetectIntentRequest {
session: string;
queryInput: QueryInput;
queryParams?: QueryParams;
inputAudio?: any;
}
export interface DetectIntentResponse {
responseId: string;
queryResult: QueryResult;
webhookStatus: Status;
}
export interface QueryResult {
queryText: string;
laugnageCode: string;
speechRecognitionConfidence: number;
action: string;
parameters: any;
allRequiredParamsSent: boolean;
fulfillmentText: string;
fulfillmentMessages: Message[];
webhookSource: string;
webhookPayload: any;
outputContexts: Context[];
intent: Intent;
intentDetectionConfidence: number;
diagnosticInfo: any;
}
export interface Status {
code: StatusCode;
message: string;
details: any[];
}
export enum StatusCode {
// Not an error; returned on success
//
// HTTP Mapping: 200 OK
OK = 0,
// The operation was cancelled, typically by the caller.
//
// HTTP Mapping: 499 Client Closed Request
CANCELLED = 1,
// Unknown error. For example, this error may be returned when
// a `Status` value received from another address space belongs to
// an error space that is not known in this address space. Also
// errors raised by APIs that do not return enough error information
// may be converted to this error.
//
// HTTP Mapping: 500 Internal Server Error
UNKNOWN = 2,
// The client specified an invalid argument. Note that this differs
// from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments
// that are problematic regardless of the state of the system
// (e.g., a malformed file name).
//
// HTTP Mapping: 400 Bad Request
INVALID_ARGUMENT = 3,
// The deadline expired before the operation could complete. For operations
// that change the state of the system, this error may be returned
// even if the operation has completed successfully. For example, a
// successful response from a server could have been delayed long
// enough for the deadline to expire.
//
// HTTP Mapping: 504 Gateway Timeout
DEADLINE_EXCEEDED = 4,
// Some requested entity (e.g., file or directory) was not found.
//
// Note to server developers: if a request is denied for an entire class
// of users, such as gradual feature rollout or undocumented whitelist,
// `NOT_FOUND` may be used. If a request is denied for some users within
// a class of users, such as user-based access control, `PERMISSION_DENIED`
// must be used.
//
// HTTP Mapping: 404 Not Found
NOT_FOUND = 5,
// The entity that a client attempted to create (e.g., file or directory)
// already exists.
//
// HTTP Mapping: 409 Conflict
ALREADY_EXISTS = 6,
// The caller does not have permission to execute the specified
// operation. `PERMISSION_DENIED` must not be used for rejections
// caused by exhausting some resource (use `RESOURCE_EXHAUSTED`
// instead for those errors). `PERMISSION_DENIED` must not be
// used if the caller can not be identified (use `UNAUTHENTICATED`
// instead for those errors). This error code does not imply the
// request is valid or the requested entity exists or satisfies
// other pre-conditions.
//
// HTTP Mapping: 403 Forbidden
PERMISSION_DENIED = 7,
// The request does not have valid authentication credentials for the
// operation.
//
// HTTP Mapping: 401 Unauthorized
UNAUTHENTICATED = 16,
// Some resource has been exhausted, perhaps a per-user quota, or
// perhaps the entire file system is out of space.
//
// HTTP Mapping: 429 Too Many Requests
RESOURCE_EXHAUSTED = 8,
// The operation was rejected because the system is not in a state
// required for the operation's execution. For example, the directory
// to be deleted is non-empty, an rmdir operation is applied to
// a non-directory, etc.
//
// Service implementors can use the following guidelines to decide
// between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`:
// (a) Use `UNAVAILABLE` if the client can retry just the failing call.
// (b) Use `ABORTED` if the client should retry at a higher level
// (e.g., when a client-specified test-and-set fails, indicating the
// client should restart a read-modify-write sequence).
// (c) Use `FAILED_PRECONDITION` if the client should not retry until
// the system state has been explicitly fixed. E.g., if an "rmdir"
// fails because the directory is non-empty, `FAILED_PRECONDITION`
// should be returned since the client should not retry unless
// the files are deleted from the directory.
//
// HTTP Mapping: 400 Bad Request
FAILED_PRECONDITION = 9,
// The operation was aborted, typically due to a concurrency issue such as
// a sequencer check failure or transaction abort.
//
// See the guidelines above for deciding between `FAILED_PRECONDITION`,
// `ABORTED`, and `UNAVAILABLE`.
//
// HTTP Mapping: 409 Conflict
ABORTED = 10,
// The operation was attempted past the valid range. E.g., seeking or
// reading past end-of-file.
//
// Unlike `INVALID_ARGUMENT`, this error indicates a problem that may
// be fixed if the system state changes. For example, a 32-bit file
// system will generate `INVALID_ARGUMENT` if asked to read at an
// offset that is not in the range [0,2^32-1], but it will generate
// `OUT_OF_RANGE` if asked to read from an offset past the current
// file size.
//
// There is a fair bit of overlap between `FAILED_PRECONDITION` and
// `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific
// error) when it applies so that callers who are iterating through
// a space can easily look for an `OUT_OF_RANGE` error to detect when
// they are done.
//
// HTTP Mapping: 400 Bad Request
OUT_OF_RANGE = 11,
// The operation is not implemented or is not supported/enabled in this
// service.
//
// HTTP Mapping: 501 Not Implemented
UNIMPLEMENTED = 12,
// Internal errors. This means that some invariants expected by the
// underlying system have been broken. This error code is reserved
// for serious errors.
//
// HTTP Mapping: 500 Internal Server Error
INTERNAL = 13,
// The service is currently unavailable. This is most likely a
// transient condition, which can be corrected by retrying with
// a backoff.
//
// See the guidelines above for deciding between `FAILED_PRECONDITION`,
// `ABORTED`, and `UNAVAILABLE`.
//
// HTTP Mapping: 503 Service Unavailable
UNAVAILABLE = 14,
// Unrecoverable data loss or corruption.
//
// HTTP Mapping: 500 Internal Server Error
DATA_LOSS = 15
}
export interface Agent {
parent: string;
displayName: string;
defaultLanguageCode: string;
supportedLanguageCodes?: string[];
timeZone: string;
description?: string;
avatarUri?: string;
enableLogging?: boolean;
matchMode?: MatchMode;
classificationThreshold?: number;
}
export interface Context {
name: string;
lifespanCount?: number;
parameters?: any;
}
export interface EntityType {
name: string;
entities: EntitySynonyms[];
displayName: string;
kind: EntityKind;
autoExpansionMode: EntityAutoExpansionMode;
}
export enum MatchMode {
MATCH_MODE_UNSPECIFIED = "MATCH_MODE_UNSPECIFIED",
MATCH_MODE_HYBRID = "MATCH_MODE_HYBRID",
MATCH_MODE_ML_ONLY = "MATCH_MODE_ML_ONLY"
}
export interface Credentials {
clientEmail?: string;
privateKey?: string;
}
export interface ClientOptions {
credentials?: Credentials;
email?: string;
keyFilename?: string;
port?: number;
projectId?: string;
promise?: PromiseConstructor;
servicePath?: string;
}
export interface EntitySynonyms {
synonyms: string[];
value: string;
}
export enum EntityKind {
KIND_MAP = "KIND_MAP",
KIND_LIST = "KIND_LIST"
}
export enum EntityAutoExpansionMode {
AUTO_EXPANSION_MODE_DEFAULT = "AUTO_EXPANSION_MODE_DEFAULT",
AUTO_EXPANSION_MODE_UNSPECIFIED = "AUTO_EXPANSION_MODE_UNSPECIFIED"
}
export enum IntentView {
INTENT_VIEW_UNSPECIFIED = "INTENT_VIEW_UNSPECIFIED",
INTENT_VIEW_FULL = "INTENT_VIEW_FULL"
}
export interface Intent {
name: string;
displayName: string;
webhookState: string;
priority?: number;
isFallback?: boolean;
mlEnabled?: boolean;
inputContextNames?: string[];
events?: string[];
trainingPhrases?: TrainingPhrase[];
action?: string;
outputContexts?: Context[];
resetContexts?: boolean;
parameters?: Parameter[];
messages?: Message[];
defaultResponsePlatforms?: string[];
rootFollowupIntentName: string;
parentFollowupIntentName: string;
followupIntentInfo?: FollowupIntentInfo[];
}
export interface TrainingPhrase {
name: string;
type: string;
parts: Part[];
timesAddedCount?: number;
}
export interface Part {
text: string;
entityType?: string;
alias?: string;
userDefined?: boolean;
}
export interface Parameter {
name: string;
displayName: string;
value?: string;
defaultValue?: string;
entityTypeDisplayName?: string;
mandatory?: boolean;
prompts?: string[];
isList?: boolean;
}
export interface FollowupIntentInfo {
followupIntentName: string;
parentFollowupIntentName: string;
}
export interface Message {
platform?: string;
text?: Text;
card?: Card;
payload?: any;
}
export interface Text {
text: string[];
}
export interface Card {
title?: string;
subtitle?: string;
imageUri?: string;
buttons?: Button[];
}
export interface Button {
text?: string;
postback?: string;
}
export interface EventInput {
name: string;
languageCode: string;
parameters?: any;
}
export interface TextInput {
text: string;
languageCode: string;
}
export interface QueryInput {
text?: TextInput;
event?: EventInput;
}
export interface QueryParams {
timeZone?: string;
geoLocation?: LatLong;
contexts?: Context[];
resetContexts?: boolean;
sessionEntityTypes?: SessionEntityType[];
payload?: any;
}
export interface LatLong {
latitude: number;
longitude: number;
}
export interface SessionEntityType {
name: string;
entityOverrideMode: string;
entities: Entity[];
}
export interface Entity {
value: string;
synonyms: string[];
}
export interface WebhookRequest {
session: string;
responseId: string;
queryResult: QueryResult;
originalDetectIntentRequest?: any;
}
export interface WebhookResponse {
fulfillmentText?: string;
fulfillmentMessages?: Message[];
source?: string;
payload?: any;
outputContexts?: Context[];
followupEventInput?: EventInput;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"dialogflow-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,16 @@
const clipboard = navigator.clipboard;
let text: string;
clipboard.writeText('foo');
clipboard.readText().then((val) => {
text = val;
});
const transfer = new DataTransfer();
transfer.setData('text/plain', 'foo');
clipboard.write(transfer);
clipboard.read().then((tf) => {
text = tf.getData('text/plain');
});
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for w3c Clipboard API 1.0
// Project: https://w3c.github.io/clipboard-apis/
// Definitions by: James Garbutt <https://github.com/43081j>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Clipboard extends EventTarget {
read(): Promise<DataTransfer>;
readText(): Promise<string>;
write(data: DataTransfer): Promise<void>;
writeText(data: string): Promise<void>;
}
interface Navigator {
readonly clipboard: Clipboard;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"dom-clipboard-api-tests.ts"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "dtslint/dt.json",
"rules": {
}
}
+405 -58
View File
@@ -1,122 +1,414 @@
// Type definitions for echarts
// Type definitions for echarts 4.1.0
// Project: http://echarts.baidu.com/
// Definitions by: Xie Jingyang <https://github.com/xieisabug>
// AntiMoron <https://github.com/AntiMoron>
// Liveangela <https://github.com/liveangela>
// Ovilia <https://github.com/Ovilia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace echarts {
function init(dom: HTMLDivElement | HTMLCanvasElement, theme?: object | string, opts?: {
devicePixelRatio?: number
renderer?: string
width?: number | string
height?: number | string
}): ECharts;
/**
* Creates an ECharts instance, and returns an echartsInstance. You shall
* not initialize multiple ECharts instances on a single container.
*
* @param {HTMLDivElement | HTMLCanvasElement} dom Instance container,
* usually is a `div` element with height and width defined.
* @param {object | string} [theme] Theme to be applied.
* This can be a configuring object of a theme, or a theme name
* registered through [echarts.registerTheme](https://echarts.apache.org/api.html#echarts.registerTheme).
* @param {object} [opts] Chart configurations.
* @param {number} [opts.devicePixelRatio] Ratio of one physical pixel to
* the size of one device independent pixels. Browser's
* `window.devicePixelRatio` is used by default.
* @param {string} [opts.renderer] Supports `'canvas'` or `'svg'`.
* See [Render by Canvas or SVG](https://echarts.apache.org/tutorial.html#Render%20by%20Canvas%20or%20SVG).
* @param {number} [opts.width] Specify width explicitly, in pixel.
* If setting to `null`/`undefined`/`'auto'`, width of `dom`
* (instance container) will be used.
* @param {number} [opts.height] Specify height explicitly, in pixel.
* If setting to `null`/`undefined`/`'auto'`, height of `dom`
* (instance container) will be used.
*/
function init(
dom: HTMLDivElement | HTMLCanvasElement,
theme?: object | string,
opts?: {
devicePixelRatio?: number
renderer?: string
width?: number | string
height?: number | string
}
): ECharts
const graphic: Graphic;
/**
* Connects interaction of multiple chart series. For example:
*
```js
// set group id of each instance respectively.
chart1.group = 'group1';
chart2.group = 'group1';
echarts.connect('group1');
// or incoming instance array that need to be linked.
echarts.connect([chart1, chart2]);
```
*
* @param group Group id in string, or array of chart instance.
*/
function connect(group: string | ECharts[]): void
interface Graphic {
clipPointsByRect(points: number[][], rect: ERectangle): number[][];
clipRectByRect(targetRect: ERectangle, rect: ERectangle): ERectangle;
LinearGradient: { new(x: number, y: number, x2: number, y2: number, colorStops: object[], globalCoord?: boolean): LinearGradient }
}
/**
* Disconnects interaction of multiple chart series. To have one single
* instance to be removed, you can set `group` of chart instance to be null.
*
* @param {string} group Group id in string.
*/
function disConnect(group: string): void
function connect(group: string | string[]): void;
/**
* Destroys chart instance, after which the instance cannot be used any
* more.
*
* @param target Chart instance or container.
*/
function dispose(target: ECharts | HTMLDivElement | HTMLCanvasElement)
: void
function disConnect(group: string): void;
/**
* Returns chart instance of dom container.
*
* @param target Chart container.
*/
function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement)
: ECharts
function dispose(target: ECharts | HTMLDivElement | HTMLCanvasElement): void;
/**
* Registers available maps. This can only be used after including
* [geo](https://echarts.apache.org/option.html#geo)
* component or chart series of
* [map](https://echarts.apache.org/option.html#series-map).
*
* @param {string} mapName Map name, referring to `map` value set in
* [geo](https://echarts.apache.org/option.html#geo)
* component or
* [map](https://echarts.apache.org/option.html#series-map).
* @param {object} geoJson Data in GeoJson format. See
* [http://geojson.org/](http://geojson.org/) for more format information.
* @param {object} [specialAreas] Zoomed part of a specific area in the map
* for better visual effect.
* See [USA Population Estimates example](https://ecomfe.github.io/echarts-examples/public/editor.html?c=map-usa).
*/
function registerMap(
mapName: string,
geoJson: object,
specialAreas?: object
): void
function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement): ECharts;
function registerMap(mapName: string, geoJson: object, specialAreas?: object): void;
function registerTheme(themeName: string, theme: object): void;
/**
* Registers a theme, should be specified when
* [initialize the chart instance](https://echarts.apache.org/api.html#echarts.init).
*
* @param {string} themeName Theme name.
* @param {object} theme Theme configurations.
*/
function registerTheme(themeName: string, theme: object): void
interface MapObj {
/** geoJson data for map */
/**
* geoJson data for map
*/
geoJson: object,
/** special areas fro map */
/**
* special areas fro map
*/
specialAreas: object
}
function getMap(mapName: string): MapObj;
/**
* Get a registed map.
*
* @param {string} mapName Map name.
* @return {MapObj} Map data.
*/
function getMap(mapName: string): MapObj
interface LinearGradient {
colorStops: object[];
global: boolean;
type: string;
x: number
x2: number
y: number
y2: number
/**
* Util methods about graphics.
*/
const graphic: Graphic;
interface Graphic {
/**
* Clip the given points by the given rectangular.
*
* @param {number[][]} points The points to be clipped,
* like [[23, 44], [12, 15], ...].
* @param {ERectangle} rect The rectangular that is used to clip points.
*/
clipPointsByRect(points: number[][], rect: ERectangle): number[][];
/**
* Clip the first input rectangular by the second input rectangular.
*
* @param {ERectangle} targetRect The rectangular to be clipped.
* @param {ERectangle} rect The rectangular that is used to clip
* targetRect.
*/
clipRectByRect(targetRect: ERectangle, rect: ERectangle): ERectangle;
}
interface ECharts {
/**
* Group name to be used in chart connection
*/
group: string
setOption(option: EChartOption, notMerge?: boolean, notRefreshImmediately?: boolean): void
/**
* Configuration item, data, universal interface, all parameters and
* data can all be modified through `setOption`. ECharts will merge
* new parameters and data, and then refresh chart.
*
* @param {EChartOption} option Configuration item and data. Please
* refer to [configuration item manual](https://echarts.apache.org/option.html)
* for more information.
* @param {boolean} [notMerge=false] Whether not to merge with previous
* `option`
* @param {boolean} [lazyUpdate=false] Whether not to update chart
* immediately
*/
setOption(
option: EChartOption,
notMerge?: boolean,
lazyUpdate?: boolean
) : void
/**
* Configuration item, data, universal interface, all parameters and
* data can all be modified through `setOption`. ECharts will merge
* new parameters and data, and then refresh chart.
*
* @param {EChartOption} option Configuration item and data. Please
* refer to [configuration item manual](https://echarts.apache.org/option.html)
* for more information.
* @param {EChartsOptionConfig} [opts] Options about how to setOption
*/
setOption(option: EChartOption, opts?: EChartsOptionConfig): void
/**
* Gets width of ECharts instance container.
*
* @return {number} Width.
*/
getWidth(): number
/**
* Gets height of ECharts instance container.
*
* @return {number} Height.
*/
getHeight(): number
/**
* Gets DOM element of ECharts instance container.
*
* @return {HTMLCanvasElement|HTMLDivElement} DOM container.
*/
getDom(): HTMLCanvasElement | HTMLDivElement
getOption(): object
/**
* Gets `option` object maintained in current instance, which contains
* configuration item and data merged from previous `setOption`
* operations by users, along with user interaction states.
* For example, switching of legend, zooming area of data zoom,
* and so on. Therefore, a new instance that is exactly the same
* can be recovered from this option.
*/
getOption(): EChartOption
resize(): void
/**
* Resizes chart, which should be called manually when container size
* changes. When `opts` is not provided, DOM size is used.
*
* @param {EChartsResizeOption} opts Specify parameters explicitly.
*/
resize(opts?: EChartsResizeOption): void
/**
* Triggers chart action, like chart switch `legendToggleSelect`,
* zoom data area `dataZoom`, show tooltip `showTip` and so on.
* See [action](https://echarts.apache.org/api.html#action) and
* [events](https://echarts.apache.org/api.html#events)
* for more information.
*
* @param payload Trigger multiple actions through `batch` attribute.
*/
dispatchAction(payload: object): void
/**
* Binds event-handling function.
* There are two kinds of events in ECharts, one of which is mouse
* events, which will be triggered when the mouse clicks certain
* element in the chart, the other kind will be triggered after
* `dispatchAction` is called. Every action has a corresponding
* event.
* If event is triggered externally by `dispatchAction`, and there
* is batch attribute in action to trigger batch action, then the
* corresponding response event parameters be in batch.
*
* @param {string} eventName Event names are all in lower-cases,
* for example, `'click'`, `'mousemove'`, `'legendselected'`
* @param {Function} handler Event-handling function, whose format
* is as following:
```js
(event: object)
```
* @param {object} [context] context of callback function, what
* `this` refers to.
*/
on(eventName: string, handler: Function, context?: object): void
/**
* Unbind event-handler function.
*
* @param {string} eventName Event names are all in lower-cases,
* for example, `'click'`, `'mousemove'`, `'legendselected'`
* @param {Function} [handler] The function to be unbound could be
* passed. Otherwise, all event functions of this type will be
* unbound.
*/
off(eventName: string, handler?: Function): void
showLoading(type?: string, opts?: object): void
/**
* Convert a point from logical coordinate (e.g., in geo, cartesian,
* graph, ...) to pixel coordinate.
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be converted.
*/
convertToPixel(finder: EChartsConvertFinder, value: string | any[])
: string | any[]
/**
* Convert a point from pixel coordinate to logical coordinate
* (e.g., in geo, cartesian, graph, ...).
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be converted.
*/
convertFromPixel(finder: EChartsConvertFinder, value: any[] | string)
: any[] | string
/**
* Determine whether the given point is in the given coordinate systems or series.
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be judged, in pixel
* coordinate system.
*/
containPixel(finder: EChartsConvertFinder, value: any[]): boolean
/**
* Shows loading animation. You can call this interface manually before
* data is loaded, and call `hideLoading` to hide loading animation
* after data is loaded.
*
* @param {string} [type='default']
* @param {EChartsLoadingOption} [opts]
*/
showLoading(type?: string, opts?: EChartsLoadingOption): void
/**
* Hides animation loading effect.
*/
hideLoading(): void
/**
* Exports chart image; returns a base64 URL; can be set to `src` of
* `Image`.
*
* @param opts Options.
*/
getDataURL(opts: {
/** 导出的格式,可选 png, jpeg */
// Exporting format, can be either png, or jpeg
type?: string,
/** 导出的图片分辨率比例,默认为 1。*/
// Resolution ratio of exporting image, 1 by default.
pixelRatio?: number,
/** 导出的图片背景色,默认使用 option 里的 backgroundColor */
backgroundColor?: string
// Background color of exporting image, use backgroundColor in
// option by default.
backgroundColor?: string,
// Excluded components list. e.g. ['toolbox']
excludeComponents?: string[]
}): string
/**
* Exports connected chart image; returns a base64 url; can be set to
* `src` of `Image`. Position of charts in exported image are
* related to that of the container.
*
* @param opts Options.
*/
getConnectedDataURL(opts: {
/** 导出的格式,可选 png, jpeg */
// Exporting format, can be either png, or jpeg
type: string,
/** 导出的图片分辨率比例,默认为 1。 */
// Resolution ratio of exporting image, 1 by default.
pixelRatio: number,
/** 导出的图片背景色,默认使用 option 里的 backgroundColor */
backgroundColor: string
// Background color of exporting image, use backgroundColor in
// option by default.
backgroundColor: string,
// Excluded components list. e.g. ['toolbox']
excludeComponents?: string[]
}): string
/**
* The method is used in rendering millions of data
* (e.g. rendering geo data). In these scenario, the entire size of
* data is probably up to 10 or 100 MB, even using binary format.
* So chunked load data and rendering is required. When using
* `appendData`, the graphic elements that have been rendered will
* not be cleared, but keep rendering new graphic elements.
*
* @param opts Data options.
*/
appendData(opts: {
// Specify which series the data will be appended to.
seriesIndex?: string,
// The data to be appended.
data?: any[]|TypedArray,
}): void
/**
* Clears current instance; removes all components and charts in
* current instance.
*/
clear(): void
/**
* Returns whether current instance has been disposed.
*
* @return {boolean} Whether has been disposed.
*/
isDisposed(): boolean
/**
* Disposes instance. Once disposed, the instance can not be used again.
*/
dispose(): void
/** 转换逻辑点到像素 */
convertToPixel(finder: ConvertFinder | string, value: string | any[]): string | any[]
convertFromPixel(finder: ConvertFinder | string, value: any[] | string): any[] | string
containPixel(finder: ConvertFinder | string,
/** 要被判断的点,为像素坐标值,以 echarts 实例的 dom 节点的左上角为坐标 [0, 0] 点。*/
value: any[]): boolean
getModel(): {
getComponent(finder: string): any;
}
}
interface ConvertFinder {
type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array
| Int32Array | Uint32Array | Uint8ClampedArray | Float32Array
| Float64Array;
interface EChartsConvertFinder {
seriesIndex?: number,
seriesId?: string,
seriesName?: string,
@@ -193,6 +485,29 @@ declare namespace echarts {
zAxis3D?: object
}
interface EChartsOptionConfig {
notMerge?: boolean,
lazyUpdate?: boolean,
silent?: boolean
}
interface EChartsResizeOption {
/**
* Chart width.
*/
width?: number | string,
/**
* Chart height.
*/
height?: number | string,
/**
* Specify whether or not to prevent triggering events.
*/
silent?: boolean
}
interface EChartTitleOption {
show?: boolean;
text?: string;
@@ -219,6 +534,38 @@ declare namespace echarts {
shadowOffsetX?: number,
shadowOffsetY?: number,
}
interface EChartsLoadingOption {
/**
* Loading text.
* @default 'loading'
*/
text?: string,
/**
* Loading circle color.
* @default '#c23531'
*/
color?: string,
/**
* Loading text color.
* @default '#000'
*/
textColor?: string,
/**
* Mask background color.
* @default 'rgba(255, 255, 255, 0.8)'
*/
maskColor?: string,
/**
* Zlevel of loading. If not 0, it creates a new canvas for loading.
* @default 0
*/
zlevel?: 0
}
}
declare module 'echarts' {
+2 -3
View File
@@ -1,12 +1,11 @@
import React = require('react');
import { EmojiData } from '..';
import { Emoji, EmojiProps, I18n } from '.';
import { Emoji, EmojiData, EmojiProps, I18n, CategoryName } from '..';
export interface Props {
emojis?: Array<string|EmojiData>;
hasStickyPosition?: boolean;
id: CategoryName;
name: string;
native: boolean;
perLine: number;
-31
View File
@@ -1,31 +0,0 @@
import React = require('react');
import { EmojiData, EmojiSkin } from '..';
export type BackgroundImageFn = (set: EmojiSet, sheetSize: EmojiSheetSize) => string;
export type EmojiSet = 'apple'|'google'|'twitter'|'emojione'|'messenger'|'facebook';
export type EmojiSheetSize = 16|20|32|64;
export interface Props {
onOver?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
onLeave?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
onClick?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
/** defaults to returning a png from unpkg.com-hosted emoji-datasource-${set} */
backgroundImageFn?: BackgroundImageFn;
native?: boolean;
forceSize?: boolean;
tooltip?: boolean;
/** defaults to 1 */
skin?: EmojiSkin;
/** defaults to 64 */
sheetSize?: EmojiSheetSize;
/** defaults to 'apple' */
set?: EmojiSet;
size: number;
emoji: string|EmojiData;
}
// tslint:disable-next-line strict-export-declare-modifiers
declare const Emoji: React.SFC<Props>;
export { Emoji as default };
+8
View File
@@ -0,0 +1,8 @@
import React = require('react');
import { EmojiProps } from '../..';
// tslint:disable-next-line strict-export-declare-modifiers
declare const Emoji: React.StatelessComponent<EmojiProps>;
export { Emoji as default };
@@ -0,0 +1,12 @@
import React = require('react');
import { EmojiProps, Data } from '../..';
export interface NimbleEmojiProps extends EmojiProps {
data: Data;
}
// tslint:disable-next-line strict-export-declare-modifiers
declare const NimbleEmoji: React.SFC<NimbleEmojiProps>;
export { NimbleEmoji as default };
+4 -2
View File
@@ -1,4 +1,6 @@
// The other exports on the components folder are not public API
export { default as Category, Props as CategoryProps } from './category';
export { default as Emoji, Props as EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from './emoji';
export { default as Picker, Props as PickerProps, I18n, PartialI18n, CustomEmoji } from './picker';
export { default as Emoji } from './emoji/emoji';
export { default as NimbleEmoji, NimbleEmojiProps } from './emoji/nimble-emoji';
export { default as Picker } from './picker/picker';
export { default as NimblePicker, NimblePickerProps } from './picker/nimble-picker';
-54
View File
@@ -1,54 +0,0 @@
import React = require('react');
import { EmojiData, EmojiSkin } from '..';
import { Category, Emoji, EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from '.';
// tslint:disable-next-line interface-name
export interface I18n {
search: string;
categories: Record<'search'|'recent'|'people'|'nature'|'foods'|'activity'|'places'|'objects'|'symbols'|'flags'|'custom', string>;
notfound: string;
}
export type PartialI18n = Partial<Pick<I18n, 'search'|'notfound'> & { categories: Partial<I18n['categories']>}>;
export interface CustomEmoji {
// id is overridden by short_names[0]
name: string;
/** Must contain at least one name. The first name is used as the unique id. */
short_names: string[];
emoticons?: string[];
keywords?: string[];
imageUrl: string;
}
export interface Props {
/** NOTE: default is not preventable */
onClick?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
perLine?: number;
emojiSize?: number;
i18n?: PartialI18n;
style?: React.CSSProperties;
title?: string;
emoji?: string;
color?: string;
set?: EmojiSet;
skin?: EmojiSkin;
native?: boolean;
backgroundImageFn?: BackgroundImageFn;
sheetSize?: EmojiSheetSize;
emojisToShowFilter?(emoji: EmojiData): boolean;
showPreview?: boolean;
emojiTooltip?: boolean;
include?: string[];
exclude?: string[];
recent?: string[];
autoFocus?: boolean;
/** NOTE: custom emoji are copied into a singleton object on every new mount */
custom: CustomEmoji[];
}
export default class Picker extends React.PureComponent<Props> {
// everything inside it is supposed to be private
}
@@ -0,0 +1,11 @@
import React = require('react');
import { Data, PickerProps } from '../..';
export interface NimblePickerProps extends PickerProps {
data: Data;
}
export default class NimblePicker extends React.PureComponent<NimblePickerProps> {
// everything inside it is supposed to be private
}
@@ -0,0 +1,7 @@
import React = require('react');
import { PickerProps } from '../..';
export default class Picker extends React.PureComponent<PickerProps> {
// everything inside it is supposed to be private
}
+21 -6
View File
@@ -1,15 +1,30 @@
export { default as emojiIndex, EmojiData, EmojiSkin } from './utils/emoji-index';
export { default as store, StoreHandlers } from './utils/store';
export { default as frequently } from './utils/frequently';
export { Data } from './utils/data';
export {
PickerProps,
EmojiProps,
I18n,
PartialI18n,
CategoryName
} from './utils/shared-props';
export {
emojiIndex,
nimbleEmojiIndex,
EmojiData,
CustomEmoji,
EmojiSkin
} from './utils/emoji-index';
export {
Picker,
PickerProps,
I18n,
PartialI18n,
CustomEmoji,
NimblePicker,
NimblePickerProps,
Emoji,
EmojiProps,
NimbleEmoji,
NimbleEmojiProps,
Category,
CategoryProps
} from './components';
+73
View File
@@ -0,0 +1,73 @@
export interface Data {
compressed: boolean;
categories: Category[];
emojis: { [key: string]: Emoji };
aliases: { [key: string]: string };
}
export interface Category {
id: string;
name: string;
emojis: string[];
}
export interface Emoji {
name?: string;
a?: string;
unified?: string;
b?: string;
non_qualified?: string;
c?: string;
has_img_apple?: boolean;
d?: boolean;
has_img_google?: boolean;
e?: boolean;
has_img_twitter?: boolean;
f?: boolean;
has_img_emojione?: boolean;
g?: boolean;
has_img_facebook?: boolean;
h?: boolean;
has_img_messenger?: boolean;
i?: boolean;
keywords?: string[];
j?: string[];
sheet?: number[];
k?: number[];
emoticons?: string[];
l?: string[];
text?: string;
m?: string;
short_names?: string[];
n?: string[];
added_in?: number;
o?: number;
sheet_x?: number;
sheet_y?: number;
skin_variations?: { [key: string]: SkinVariation };
obsoleted_by?: string;
obsoletes?: string;
}
export interface SkinVariation {
unified: string;
non_qualified: null | string;
image: string;
sheet_x: number;
sheet_y: number;
added_in: string;
has_img_apple: boolean;
has_img_google: boolean;
has_img_twitter: boolean;
has_img_emojione: boolean;
has_img_facebook: boolean;
has_img_messenger: boolean;
obsoleted_by?: string;
obsoletes?: string;
}
export function buildSearch(emoji: Emoji): string;
export function compress(emoji: Emoji): void;
export function uncompress(data: Data): void;
-25
View File
@@ -1,25 +0,0 @@
export type EmojiSkin = 1|2|3|4|5|6;
export interface EmojiData {
id: string;
name: string;
colons: string;
/** Reverse mapping to keyof emoticons */
emoticons: string[];
unified: string;
skin: EmojiSkin|null;
native: string;
}
// tslint:disable-next-line strict-export-declare-modifiers
declare const _default: {
search(query: ''): null
search(query: string): EmojiData|null
emojis: { [emoji: string]: EmojiData }
/** Mapping of string to keyof emojis */
emoticons: { [emoticon: string]: string }
};
export { _default as default };
@@ -0,0 +1,14 @@
import { EmojiData } from './nimble-emoji-index';
// tslint:disable-next-line strict-export-declare-modifiers
declare const _default: {
search(query: ''): null;
search(query: string): EmojiData|null;
emojis: { [emoji: string]: EmojiData };
/** Mapping of string to keyof emojis */
emoticons: { [emoticon: string]: string };
};
export { _default as default };
+2
View File
@@ -0,0 +1,2 @@
export { default as emojiIndex } from './emoji-index';
export { default as nimbleEmojiIndex, EmojiData, CustomEmoji, EmojiSkin } from './nimble-emoji-index';
@@ -0,0 +1,40 @@
import { Data } from "../data";
import { CategoryName } from '../shared-props';
export type EmojiSkin = 1 | 2 | 3 | 4 | 5 | 6;
export interface BaseEmoji {
id: string;
name: string;
colons: string;
/** Reverse mapping to keyof emoticons */
emoticons: string[];
unified: string;
skin: EmojiSkin | null;
native: string;
}
export interface CustomEmoji {
// id is overridden by short_names[0]
id?: string;
// colons is overridden by :id:
colons?: string;
name: string;
/** Must contain at least one name. The first name is used as the unique id. */
short_names: string[];
emoticons?: string[];
keywords?: string[];
imageUrl: string;
}
export type EmojiData = BaseEmoji | CustomEmoji;
export default class NimbleEmojiIndex {
constructor(data: Data);
search(query: ''): null;
search(query: string): EmojiData[]|null;
emojis: { [emoji: string]: EmojiData };
/** Mapping of string to keyof emojis */
emoticons: { [emoticon: string]: string };
}
+83
View File
@@ -0,0 +1,83 @@
import React = require('react');
import { EmojiData, EmojiSkin, CustomEmoji } from './emoji-index/nimble-emoji-index';
export type BackgroundImageFn = (set: EmojiSet, sheetSize: EmojiSheetSize) => string;
export type EmojiSet = 'apple' | 'google' | 'twitter' | 'emojione' | 'messenger' | 'facebook';
export type EmojiSheetSize = 16 | 20 | 32 | 64;
export interface EmojiProps {
onOver?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
onLeave?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
onClick?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
fallback?(emoji: EmojiData, props: EmojiProps): React.Component;
/** defaults to returning a png from unpkg.com-hosted emoji-datasource-${set} */
backgroundImageFn?: BackgroundImageFn;
native?: boolean;
forceSize?: boolean;
tooltip?: boolean;
/** defaults to 1 */
skin?: EmojiSkin;
/** defaults to 64 */
sheetSize?: EmojiSheetSize;
/** defaults to 52 */
sheetColumns?: number;
/** defaults to 52 */
sheetRows?: number;
/** defaults to 'apple' */
set?: EmojiSet;
size: number;
emoji: string | EmojiData;
html?: boolean;
/** data is omitted here as it should be used for NimbleEmoji only - not emoji */
}
export type CategoryName = 'search' | 'recent' | 'people' | 'nature' | 'foods' | 'activity' | 'places' | 'objects' | 'symbols' | 'flags' | 'custom';
// tslint:disable-next-line interface-name
export interface I18n {
search: string;
categories: Record<CategoryName, string>;
notfound: string;
skintext: string;
}
export type PartialI18n = Partial<Pick<I18n, 'search' | 'notfound'> & { categories: Partial<I18n['categories']> }>;
export interface CustomIcons {
categories: Record<CategoryName, () => React.Component>;
}
export interface PickerProps {
/** NOTE: default is not preventable */
onClick?(emoji: EmojiData, e: React.MouseEvent<HTMLElement>): void;
onSelect?(emoji: EmojiData): void;
onSkinChange?(skin: EmojiSkin): void;
perLine?: number;
emojiSize?: number;
i18n?: PartialI18n;
style?: React.CSSProperties;
title?: string;
emoji?: string;
color?: string;
set?: EmojiSet;
skin?: EmojiSkin;
defaultSkin?: EmojiSkin;
native?: boolean;
backgroundImageFn?: BackgroundImageFn;
sheetSize?: EmojiSheetSize;
emojisToShowFilter?(emoji: EmojiData): boolean;
showPreview?: boolean;
showSkinTones?: boolean;
emojiTooltip?: boolean;
include?: CategoryName[];
exclude?: CategoryName[];
recent?: string[];
autoFocus?: boolean;
/** NOTE: custom emoji are copied into a singleton object on every new mount */
custom: CustomEmoji[];
skinEmoji?: string;
notFound?(): React.Component;
notFoundEmoji?: string;
icons?: CustomIcons;
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Port of https://github.com/missive/emoji-mart/blob/master/src/components/emoji.js
// Port of https://github.com/missive/emoji-mart/blob/v2.8.0/stories/index.js
import React = require('react');
+2 -3
View File
@@ -1,9 +1,8 @@
// Type definitions for emoji-mart 2.2
// Type definitions for emoji-mart 2.8
// Project: https://github.com/missive/emoji-mart
// Definitions by: Diogo Franco <https://github.com/Kovensky>
// Nick Winans <https://github.com/Nicell>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// These definitions should work with 2.3, but the tests doesn't pass on 2.3.
export * from './dist-es';
+9 -3
View File
@@ -20,11 +20,17 @@
"files": [
"index.d.ts",
"dist-es/components/category.d.ts",
"dist-es/components/emoji.d.ts",
"dist-es/components/emoji/emoji.d.ts",
"dist-es/components/emoji/nimble-emoji.d.ts",
"dist-es/components/index.d.ts",
"dist-es/components/picker.d.ts",
"dist-es/utils/emoji-index.d.ts",
"dist-es/components/picker/picker.d.ts",
"dist-es/components/picker/nimble-picker.d.ts",
"dist-es/utils/emoji-index/emoji-index.d.ts",
"dist-es/utils/emoji-index/nimble-emoji-index.d.ts",
"dist-es/utils/emoji-index/index.d.ts",
"dist-es/utils/data.d.ts",
"dist-es/utils/frequently.d.ts",
"dist-es/utils/shared-props.d.ts",
"dist-es/utils/store.d.ts",
"dist-es/index.d.ts",
"emoji-mart-tests.tsx"
+1
View File
@@ -44,6 +44,7 @@ declare module 'leaflet' {
| 'GrayLabels'
| 'DarkGrayLabels'
| 'ImageryLabels'
| 'ImageryClarity'
| 'ImageryTransportation'
| 'ShadedReliefLabels'
| 'TerrainLabels';
+1 -1
View File
@@ -52,7 +52,7 @@ declare namespace Evaporate {
customAuthMethod?: null | ((
signParams: string,
signHeaders: string,
stringToSign: () => string | undefined,
stringToSign: string,
signatureDateTime: string,
canonicalRequest: string
) => Promise<string>);
+6 -3
View File
@@ -374,9 +374,12 @@ async () => {
};
async () => {
const result = await ImageManipulator.manipulate('url', [{
rotate: 90
}], {
const result = await ImageManipulator.manipulate('url', [
{ rotate: 90 },
{ resize: { width: 300 } },
{ resize: { height: 300 } },
{ resize: { height: 300, width: 300 } },
], {
compress: 0.75
});
+1 -1
View File
@@ -1519,7 +1519,7 @@ export namespace ImageManipulator {
type Action = Resize | Rotate | Flip | Crop;
interface Resize {
resize: { width: number, height: number };
resize: { width?: number, height?: number };
}
interface Rotate {
+5 -1
View File
@@ -1,6 +1,7 @@
// Type definitions for express-fileupload 0.1
// Type definitions for express-fileupload 0.4
// Project: https://github.com/richardgirges/express-fileupload#readme
// Definitions by: Gintautas Miselis <https://github.com/Naktibalda>
// Sefa Ilkimen <https://github.com/silkimen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -28,13 +29,16 @@ declare namespace fileUpload {
encoding: string;
mimetype: string;
data: Buffer;
truncated: boolean;
mv(path: string, callback: (err: any) => void): void;
mv(path: string): Promise<void>;
}
interface Options {
debug?: boolean;
safeFileNames?: boolean;
preserveExtension?: boolean | string | number;
abortOnLimit?: boolean;
[property: string]: any;
}
}
+2 -1
View File
@@ -11,7 +11,8 @@ declare const fakerStatic: Faker.FakerStatic;
declare namespace Faker {
interface FakerStatic {
locale: string;
setLocale(locale: string): void;
address: {
zipCode(format?: string): string;
city(format?: number): string;
+106
View File
@@ -0,0 +1,106 @@
import ffi = require('ffi-napi');
import ref = require('ref-napi');
import Struct = require('ref-struct-di');
import Union = require('ref-union-di');
import TArray = require('ref-array-di');
{
const sqlite3 = ref.types.void;
const sqlite3Ptr = ref.refType(sqlite3);
const sqlite3PtrPtr = ref.refType(sqlite3Ptr);
const stringPtr = ref.refType(ref.types.CString);
const libsqlite3 = ffi.Library('libsqlite3', {
sqlite3_open: [ 'int', [ 'string', sqlite3PtrPtr ] ],
sqlite3_close: [ 'int', [ sqlite3PtrPtr ] ],
sqlite3_exec: [ 'int', [ sqlite3PtrPtr, 'string', 'pointer', 'pointer', stringPtr ] ],
sqlite3_changes: [ 'int', [ sqlite3PtrPtr ]]
});
const dbPtrPtr = ref.alloc(sqlite3PtrPtr);
libsqlite3.sqlite3_open("test.sqlite3", dbPtrPtr);
}
{
const func = ffi.ForeignFunction(new Buffer(10), 'int', [ 'int' ]);
func(-5);
func.async(-5, (err: any, res: any) => {});
}
{
const funcPtr = ffi.Callback('int', [ 'int' ], Math.abs);
const func = ffi.ForeignFunction(funcPtr, 'int', [ 'int' ]);
}
{
const printfPointer = ffi.DynamicLibrary().get('printf');
const printfGen = ffi.VariadicForeignFunction(printfPointer, 'void', [ 'string' ]);
printfGen()('Hello World!\n');
printfGen('int')('This is an int: %d\n', 10);
printfGen('string')('This is a string: %s\n', 'hello');
}
{
ref.address(new Buffer(1));
const intBuf = ref.alloc(ref.types.int);
const intWith4 = ref.alloc(ref.types.int, 4);
const buf0 = ref.allocCString('hello world');
const type = ref.coerceType('int **');
const val = ref.deref(intBuf);
}
{
ref.isNull(new Buffer(1));
}
{
const str = ref.readCString(new Buffer('hello\0world\0'), 0);
const buf = ref.alloc('int64');
ref.writeInt64BE(buf, 0, '9223372036854775807');
const val = ref.readInt64BE(buf, 0);
}
{
const voidPtrType = ref.refType(ref.types.void);
const buf = ref.alloc('int64');
ref.writeInt64LE(buf, 0, '9223372036854775807');
}
{
const S1 = Struct({ a: ref.types.int });
const S2 = new Struct({ a: 'int' });
}
{
const P = new Struct();
P.defineProperty('a', ref.types.int);
P.defineProperty('d', 'long');
}
{
const SimpleStruct = Struct({
first : ref.types.byte,
last : ref.types.byte
});
const ss = new SimpleStruct({ first: 50, last: 100 });
ss.first += 200;
}
{
const ST = Struct();
const test: ref.Type = ST.fields['t'].type;
}
{
const CharArray = TArray('char');
const b = new Buffer('hello', 'ascii');
const a = new CharArray(b);
}
{
const Int32Array = TArray(ref.types.int32);
const input = [1, 4, 91, 123123, 5123512, 0, -1];
const a = new Int32Array(input);
}
{
const int = ref.types.int;
const IntArray = TArray(int);
const buf = new Buffer(int.size * 3);
int.set(buf, int.size * 0, 5);
int.set(buf, int.size * 1, 8);
int.set(buf, int.size * 2, 0);
const array = IntArray.untilZeros(buf);
}
{
const refCharArr = TArray('char')([1, 3, 5], 2).ref();
}
+186
View File
@@ -0,0 +1,186 @@
// Type definitions for node-ffi-napi 2.4
// Project: https://github.com/node-ffi/node-ffi
// Definitions by: Keerthi Niranjan <https://github.com/keerthi16>, Kiran Niranjan <https://github.com/KiranNiranjan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import ref = require('ref-napi');
import StructType = require('ref-struct-di');
/** Provides a friendly API on-top of `DynamicLibrary` and `ForeignFunction`. */
export interface Library {
/** The extension to use on libraries. */
EXT: string;
/**
* @param libFile name of library
* @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}]
* @param lib hash that will be extended
*/
new (libFile: string, funcs?: {[key: string]: any[]}, lib?: object): any;
/**
* @param libFile name of library
* @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}]
* @param lib hash that will be extended
*/
(libFile: string, funcs?: {[key: string]: any[]}, lib?: object): any;
}
export const Library: Library;
/** Get value of errno. */
export function errno(): number;
export interface Function extends ref.Type {
/** The type of return value. */
retType: ref.Type;
/** The type of arguments. */
argTypes: ref.Type[];
/** Is set for node-ffi functions. */
ffi_type: Buffer;
abi: number;
/** Get a `Callback` pointer of this function type. */
toPointer(fn: (...args: any[]) => any): Buffer;
/** Get a `ForeignFunction` of this function type. */
toFunction(buf: Buffer): ForeignFunction;
}
/** Creates and returns a type for a C function pointer. */
export const Function: {
new (retType: ref.Type | string, argTypes: any[], abi?: number): Function;
(retType: ref.Type | string, argTypes: any[], abi?: number): Function;
};
export interface ForeignFunction {
(...args: any[]): any;
async(...args: any[]): void;
}
/**
* Represents a foreign function in another library. Manages all of the aspects
* of function execution, including marshalling the data parameters for the
* function into native types and also unmarshalling the return from function
* execution.
*/
export const ForeignFunction: {
new (ptr: Buffer, retType: ref.Type | string, argTypes: any[], abi?: number): ForeignFunction;
(ptr: Buffer, retType: ref.Type | string, argTypes: any[], abi?: number): ForeignFunction;
};
export interface VariadicForeignFunction {
/**
* What gets returned is another function that needs to be invoked with the rest
* of the variadic types that are being invoked from the function.
*/
(...args: any[]): ForeignFunction;
/**
* Return type as a property of the function generator to
* allow for monkey patching the return value in the very rare case where the
* return type is variadic as well
*/
returnType: any;
}
/**
* For when you want to call to a C function with variable amount of arguments.
* i.e. `printf`.
*
* This function takes care of caching and reusing `ForeignFunction` instances that
* contain the same ffi_type argument signature.
*/
export const VariadicForeignFunction: {
new (ptr: Buffer, ret: ref.Type | string, fixedArgs: any[], abi?: number): VariadicForeignFunction;
(ptr: Buffer, ret: ref.Type | string, fixedArgs: any[], abi?: number): VariadicForeignFunction;
};
export interface DynamicLibrary {
/** Close library, returns the result of the `dlclose` system function. */
close(): number;
/** Get a symbol from this library. */
get(symbol: string): Buffer;
/** Get the result of the `dlerror` system function. */
error(): string;
}
/**
* This class loads and fetches function pointers for dynamic libraries
* (.so, .dylib, etc). After the libray's function pointer is acquired, then you
* call `get(symbol)` to retreive a pointer to an exported symbol. You need to
* call `get___` on the pointer to dereference it into its actual value, or
* turn the pointer into a callable function with `ForeignFunction`.
*/
export const DynamicLibrary: {
FLAGS: {
RTLD_LAZY: number;
RTLD_NOW: number;
RTLD_LOCAL: number;
RTLD_GLOBAL: number;
RTLD_NOLOAD: number;
RTLD_NODELETE: number;
RTLD_NEXT: Buffer;
RTLD_DEFAUL: Buffer;
}
new (path?: string, mode?: number): DynamicLibrary;
(path?: string, mode?: number): DynamicLibrary;
};
/**
* Turns a JavaScript function into a C function pointer.
* The function pointer may be used in other C functions that
* accept C callback functions.
*/
export interface Callback {
new (retType: any, argTypes: any[], abi: number, fn: any): Buffer;
new (retType: any, argTypes: any[], fn: any): Buffer;
(retType: any, argTypes: any[], abi: number, fn: any): Buffer;
(retType: any, argTypes: any[], fn: any): Buffer;
}
export const Callback: Callback;
export const ffiType: {
/** Get a `ffi_type *` Buffer appropriate for the given type. */
(type: ref.Type | string): Buffer
FFI_TYPE: StructType;
};
export function CIF(retType: any, types: any[], abi?: any): Buffer;
export function CIF_var(retType: any, types: any[], numFixedArgs: number, abi?: any): Buffer;
export const HAS_OBJC: boolean;
export const FFI_TYPES: {[key: string]: Buffer};
export const FFI_OK: number;
export const FFI_BAD_TYPEDEF: number;
export const FFI_BAD_ABI: number;
export const FFI_DEFAULT_ABI: number;
export const FFI_FIRST_ABI: number;
export const FFI_LAST_ABI: number;
export const FFI_SYSV: number;
export const FFI_UNIX64: number;
export const RTLD_LAZY: number;
export const RTLD_NOW: number;
export const RTLD_LOCAL: number;
export const RTLD_GLOBAL: number;
export const RTLD_NOLOAD: number;
export const RTLD_NODELETE: number;
export const RTLD_NEXT: Buffer;
export const RTLD_DEFAULT: Buffer;
export const LIB_EXT: string;
export const FFI_TYPE: StructType;
/** Default types. */
export const types: {
void: ref.Type; int64: ref.Type; ushort: ref.Type;
int: ref.Type; uint64: ref.Type; float: ref.Type;
uint: ref.Type; long: ref.Type; double: ref.Type;
int8: ref.Type; ulong: ref.Type; Object: ref.Type;
uint8: ref.Type; longlong: ref.Type; CString: ref.Type;
int16: ref.Type; ulonglong: ref.Type; bool: ref.Type;
uint16: ref.Type; char: ref.Type; byte: ref.Type;
int32: ref.Type; uchar: ref.Type; size_t: ref.Type;
uint32: ref.Type; short: ref.Type;
};
+50
View File
@@ -0,0 +1,50 @@
// DefinitelyTyped: partial
interface Buffer {
/** Shorthand for `ref.address`. */
address(): number;
/** Shorthand for `ref.deref`. */
deref(): any;
/** Shorthand for `ref.isNull`. */
isNull(): boolean;
/** Shorthand for `ref.readCString`. */
readCString(offset?: number): string;
/** Shorthand for `ref.readInt64BE`. */
readInt64BE(offset?: number): string;
/** Shorthand for `ref.readInt64LE`. */
readInt64LE(offset?: number): string;
/** Shorthand for `ref.readObject`. */
readObject(offset?: number): string;
/** Shorthand for `ref.readPointer`. */
readPointer(offset?: number): string;
/** Shorthand for `ref.readUInt64BE`. */
readUInt64BE(offset?: number): string;
/** Shorthand for `ref.readUInt64LE`. */
readUInt64LE(offset?: number): string;
/** Shorthand for `ref.ref`. */
ref(): Buffer;
/** Shorthand for `ref.reinterpret`. */
reinterpret(size: number, offset?: number): Buffer;
/** Shorthand for `ref.reinterpretUntilZeros`. */
reinterpretUntilZeros(size: number, offset?: number): Buffer;
/** Shorthand for `ref.writeCString`. */
writeCString(offset: number, input: string, encoding?: string): void;
/** Shorthand for `ref.writeInt64BE`. */
writeInt64BE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeInt64LE`. */
writeInt64LE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeObject`. */
writeObject(offset: number, object: object): void;
/** Shorthand for `ref.writePointer`. */
writePointer(offset: number, pointer: Buffer): void;
/** Shorthand for `ref.writeUInt64BE`. */
writeUInt64BE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeUInt64LE`. */
writeUInt64LE(offset: number, input: number | string): any;
/**
* Generate string for inspecting.
* String includes the hex-encoded memory address of the Buffer instance.
*/
inspect(): string;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"node-ffi-napi-buffer.d.ts",
"ffi-napi-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-consecutive-blank-lines": [true, 3],
"ban-types": [false]
}
}
+1 -1
View File
@@ -45,7 +45,7 @@ declare class Class_DgramSocket extends Class_EventEmitter {
*
* @async
*/
bind(opts: Object): void;
bind(opts: object): void;
/**
*
+3 -13
View File
@@ -52,23 +52,13 @@ declare class Class_Digest extends Class__object {
/**
*
* @brief 计算并返回摘要
* @param data 二进制数据块,此数据块将在计算前更新进摘要
* @return 返回摘要的二进制数据
* @param codec 指定编码格式,允许值为:"buffer", "hex", "base64", "utf8", 或者系统支持的字符集
* @return 返回指定编码的摘要表示
*
*
*
*/
digest(data: Class_Buffer): Class_Buffer;
/**
*
* @brief 计算并返回摘要
* @return 返回摘要的二进制数据
*
*
*
*/
digest(): Class_Buffer;
digest(codec?: string/** = "buffer"*/): any;
} /** endof class */
+17 -17
View File
@@ -56,7 +56,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
on(ev: string, func: Function): Object;
on(ev: string, func: Function): object;
/**
*
@@ -67,7 +67,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
on(map: Object): Object;
on(map: object): object;
/**
*
@@ -79,7 +79,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
addListener(ev: string, func: Function): Object;
addListener(ev: string, func: Function): object;
/**
*
@@ -90,7 +90,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
addListener(map: Object): Object;
addListener(map: object): object;
/**
*
@@ -102,7 +102,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
prependListener(ev: string, func: Function): Object;
prependListener(ev: string, func: Function): object;
/**
*
@@ -113,7 +113,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
prependListener(map: Object): Object;
prependListener(map: object): object;
/**
*
@@ -125,7 +125,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
once(ev: string, func: Function): Object;
once(ev: string, func: Function): object;
/**
*
@@ -136,7 +136,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
once(map: Object): Object;
once(map: object): object;
/**
*
@@ -148,7 +148,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
prependOnceListener(ev: string, func: Function): Object;
prependOnceListener(ev: string, func: Function): object;
/**
*
@@ -159,7 +159,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
prependOnceListener(map: Object): Object;
prependOnceListener(map: object): object;
/**
*
@@ -171,7 +171,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
off(ev: string, func: Function): Object;
off(ev: string, func: Function): object;
/**
*
@@ -182,7 +182,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
off(ev: string): Object;
off(ev: string): object;
/**
*
@@ -193,7 +193,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
off(map: Object): Object;
off(map: object): object;
/**
*
@@ -205,7 +205,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
removeListener(ev: string, func: Function): Object;
removeListener(ev: string, func: Function): object;
/**
*
@@ -216,7 +216,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
removeListener(ev: string): Object;
removeListener(ev: string): object;
/**
*
@@ -227,7 +227,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
removeListener(map: Object): Object;
removeListener(map: object): object;
/**
*
@@ -238,7 +238,7 @@ declare class Class_EventEmitter extends Class__object {
*
*
*/
removeAllListeners(evs?: any[]/** = v8::Array::New(isolate)*/): Object;
removeAllListeners(evs?: any[]/** = v8::Array::New(isolate)*/): object;
/**
*
+1 -1
View File
@@ -70,7 +70,7 @@ declare class Class_EventInfo extends Class__object {
* @type Object
*/
target: Object
target: object
+1 -1
View File
@@ -44,7 +44,7 @@ declare class Class_Handler extends Class__object {
*
*
*/
constructor(map: Object);
constructor(map: object);
/**
*

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