From 11f441840ca8ad0d6dc14fe7a69b60abf9f254d5 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Fri, 27 Jul 2018 17:54:15 +0200 Subject: [PATCH 001/275] Add koa-router's Router to koa's Context (#27472) --- types/koa-router/index.d.ts | 5 ++++ types/koa-router/koa-router-tests.ts | 36 ++++++++++++++++------------ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 7382dd91e6..f8a31e71cb 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Jerry Chin // Pavel Ivanov // JounQin +// Romain Faust // Definitions: https://github.com/hellopao/DefinitelyTyped // TypeScript Version: 2.3 @@ -51,6 +52,10 @@ declare namespace Router { * url params */ params: any; + /** + * the router instance + */ + router: Router; } export interface IMiddleware { diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 1325da0de0..b2bec9ad0c 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -8,21 +8,27 @@ const router = new Router({ }); router - .param('id', function(id, ctx, next) { - next(); - }) - .get('/', function (ctx, next) { - ctx.body = 'Hello World!'; - }) - .post('/users', function (ctx, next) { - // ... - }) - .put('/users/:id', function (ctx, next) { - ctx.body = ctx.params.id; - }) - .del('/users/:id', function () { - // ... - }); + .param('id', function (id, ctx, next) { + next(); + }) + .get('/', function (ctx, next) { + ctx.body = 'Hello World!'; + }) + .get('/users/:id', function (ctx, next) { + ctx.body = ctx.router.url('user-accounts', { id: ctx.params.id }) + }) + .get('user-accounts', '/users/:id/accounts', function (ctx, next) { + // ... + }) + .post('/users', function (ctx, next) { + // ... + }) + .put('/users/:id', function (ctx, next) { + ctx.body = ctx.params.id; + }) + .del('/users/:id', function () { + // ... + }); router.get('user', '/users/:id', function (ctx) { ctx.body = "sdsd"; From afa493da176fc1a0e689cc279a9288c1804ae7d0 Mon Sep 17 00:00:00 2001 From: Martin Kasban Tange Date: Fri, 27 Jul 2018 17:55:05 +0200 Subject: [PATCH 002/275] Added tooltip props (#27470) --- types/rc-slider/index.d.ts | 10 ++++++++-- types/rc-slider/rc-slider-tests.tsx | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/types/rc-slider/index.d.ts b/types/rc-slider/index.d.ts index 139f4e2ef0..109819e20c 100644 --- a/types/rc-slider/index.d.ts +++ b/types/rc-slider/index.d.ts @@ -8,6 +8,7 @@ // TypeScript Version: 2.6 import * as React from "react"; +import { RCTooltip } from 'rc-tooltip'; export interface Marks { [number: number]: @@ -178,9 +179,14 @@ export interface HandleProps extends CommonApiProps { offset: number; } +export interface WithTooltipProps { + tipFormatter?: (value: number) => React.ReactNode; + tipProps?: Partial; +} + export default class Slider extends React.Component { } export class Range extends React.Component { } export class Handle extends React.Component { } -export function createSliderWithTooltip(slider: typeof Slider): new() => Slider; -export function createSliderWithTooltip(range: typeof Range): new() => Range; +export function createSliderWithTooltip(slider: typeof Slider): new() => React.Component; +export function createSliderWithTooltip(range: typeof Range): new() => React.Component; diff --git a/types/rc-slider/rc-slider-tests.tsx b/types/rc-slider/rc-slider-tests.tsx index e08a674dca..2de87bc4e2 100644 --- a/types/rc-slider/rc-slider-tests.tsx +++ b/types/rc-slider/rc-slider-tests.tsx @@ -62,3 +62,8 @@ ReactDOM.render( , document.querySelector('.app') ); + +ReactDOM.render( + , + document.querySelector('.app') +); From be6b064799ed68157660ae142223168708b83edd Mon Sep 17 00:00:00 2001 From: Bond Date: Fri, 27 Jul 2018 16:56:00 +0100 Subject: [PATCH 003/275] Support custom backoff strategy (#27529) https://github.com/OptimalBits/bull/commit/ddc0879e2655209b13c642814f4dd51643bc0c84 --- types/bull/index.d.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index c204fea135..6ed6fa88e7 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -84,6 +84,13 @@ declare namespace Bull { * Delay before processing next job in case of internal error */ retryProcessDelay?: number; + + /** + * Define a custom backoff strategy + */ + backoffStrategies: { + [key: string]: (attemptsMade: number, err: typeof Error) => number; + }; } type DoneCallback = (error?: Error | null, value?: any) => void; @@ -167,12 +174,12 @@ declare namespace Bull { /** * Backoff type, which can be either `fixed` or `exponential` */ - type: 'fixed' | 'exponential'; + type: string; /** * Backoff delay, in milliseconds */ - delay: number; + delay?: number; } interface RepeatOptions { From 73124d44b4368e3192e8cb9e8ba858b29709c335 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 27 Jul 2018 08:56:38 -0700 Subject: [PATCH 004/275] chart.js: barThickness string value must be "flex" (#27613) --- types/chart.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index d3762d54be..09230f6702 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -584,7 +584,7 @@ declare namespace Chart { position?: string; ticks?: TickOptions; gridLines?: GridLineOptions; - barThickness?: number | string; + barThickness?: number | "flex"; maxBarThickness?: number; scaleLabel?: ScaleTitleOptions; time?: TimeScale; From 270cd04a6a1c59bb40cfa9b1e1e0d6a5ec694fb3 Mon Sep 17 00:00:00 2001 From: Tane Morgan Date: Sat, 28 Jul 2018 03:58:15 +1200 Subject: [PATCH 005/275] Remove react-svg (#27614) --- notNeededPackages.json | 6 +++++ types/react-svg/index.d.ts | 37 ----------------------------- types/react-svg/react-svg-tests.tsx | 15 ------------ types/react-svg/tsconfig.json | 24 ------------------- types/react-svg/tslint.json | 1 - 5 files changed, 6 insertions(+), 77 deletions(-) delete mode 100644 types/react-svg/index.d.ts delete mode 100644 types/react-svg/react-svg-tests.tsx delete mode 100644 types/react-svg/tsconfig.json delete mode 100644 types/react-svg/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index db3cd3f68e..7c6d2629a8 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1224,6 +1224,12 @@ "sourceRepoURL": "https://github.com/tomkp/react-split-pane", "asOfVersion": "0.1.67" }, + { + "libraryName": "react-svg", + "typingsPackageName": "react-svg", + "sourceRepoURL": "https://github.com/tanem/react-svg", + "asOfVersion": "5.0.0" + }, { "libraryName": "realm", "typingsPackageName": "realm", diff --git a/types/react-svg/index.d.ts b/types/react-svg/index.d.ts deleted file mode 100644 index 5484191442..0000000000 --- a/types/react-svg/index.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Type definitions for react-svg 3.0 -// Project: https://github.com/atomic-app/react-svg -// Definitions by: Chen Junda -// Chris Garber -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 - -import * as React from "react"; - -declare class ReactSVG extends React.Component, HTMLDivElement>> {} - -export = ReactSVG; - -declare namespace ReactSVG { - interface ReactSVGProps { - /** - * Path to the SVG. - */ - path: string; - /** - * Run any script blocks found in the SVG (always, once, or never). Defaults to never. - */ - evalScripts?: 'always' | 'once' | 'never'; - /** - * Function to call after the SVG is injected. Receives the newly injected SVG DOM element as a parameter. Defaults to null. - */ - onInjected?: (dom: SVGSVGElement) => void; - /** - * Class name to be added to the SVG. Defaults to ''. - */ - svgClassName?: string; - /** - * Inline styles to be added to the SVG. Defaults to {}. - */ - svgStyle?: any; - } -} diff --git a/types/react-svg/react-svg-tests.tsx b/types/react-svg/react-svg-tests.tsx deleted file mode 100644 index 676e1e5663..0000000000 --- a/types/react-svg/react-svg-tests.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import * as React from 'react'; -import * as ReactDOM from 'react-dom'; -import ReactSVG = require("react-svg"); - -const complete = {}} - className="wrapper-class-name" - svgClassName="svg-class-name" - onClick={() => {}} - evalScripts="once" - svgStyle={{}} - />; - -const minimal = ; diff --git a/types/react-svg/tsconfig.json b/types/react-svg/tsconfig.json deleted file mode 100644 index 43b8246d54..0000000000 --- a/types/react-svg/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "jsx": "react", - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "react-svg-tests.tsx" - ] -} diff --git a/types/react-svg/tslint.json b/types/react-svg/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/react-svg/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From 21aee9586c14520576725e9601c75a77097ab941 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 27 Jul 2018 08:59:06 -0700 Subject: [PATCH 006/275] redux-form/v4: Fix missing type argument to Reducer (#27542) --- types/redux-form/v4/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/redux-form/v4/index.d.ts b/types/redux-form/v4/index.d.ts index 4e21aee1fa..d9ac180ccf 100644 --- a/types/redux-form/v4/index.d.ts +++ b/types/redux-form/v4/index.d.ts @@ -464,7 +464,7 @@ export declare const reducer: { [formName: string]: { [fieldName: string]: Normalizer } - }): Reducer; + }): Reducer; /** * Returns a form reducer that will also pass each action through @@ -473,5 +473,5 @@ export declare const reducer: { * passed to each reducer will only be the slice that pertains to that * form. */ - plugin(reducers: { [formName: string]: Reducer }): Reducer; + plugin(reducers: { [formName: string]: Reducer }): Reducer; }; From 509d927c516091e5a01abcf92b16324d92a8f5e9 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 27 Jul 2018 08:59:20 -0700 Subject: [PATCH 007/275] react-sortable-tree: Add react-dnd dependency (#27541) --- types/react-sortable-tree/package.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 types/react-sortable-tree/package.json diff --git a/types/react-sortable-tree/package.json b/types/react-sortable-tree/package.json new file mode 100644 index 0000000000..2e009d2f82 --- /dev/null +++ b/types/react-sortable-tree/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "react-dnd": "^5.0.0" + } +} From c083ea5eda72b08e8457a5e8b0cef891afdf58ca Mon Sep 17 00:00:00 2001 From: Anatoly Tokalov Date: Fri, 27 Jul 2018 20:43:04 +0300 Subject: [PATCH 008/275] [@types/kafka-node]: add missind Admin class and loadMetadataForTopics getListGroups and describeGroups methods (#27475) --- types/kafka-node/index.d.ts | 9 +++++++++ types/kafka-node/kafka-node-tests.ts | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 71d1fd6728..2f44a7e767 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -9,6 +9,7 @@ export class Client { constructor(connectionString: string, clientId?: string, options?: ZKOptions, noBatchOptions?: AckBatchOptions, sslOptions?: any); close(cb?: () => void): void; + loadMetadataForTopics(topics: string[], cb: (error: TopicsNotExistError | any, data: any) => any): void; topicExists(topics: string[], cb: (error?: TopicsNotExistError | any) => any): void; refreshMetadata(topics: string[], cb?: (error?: any) => any): void; sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; @@ -20,6 +21,8 @@ export class Client { export class KafkaClient extends Client { constructor(options?: KafkaClientOptions); connect(): void; + getListGroups(cb: (error: any, data: any) => any): void; + describeGroups(consumerGroups: any, cb: (error: any, data: any) => any): void; } export class Producer { @@ -93,6 +96,12 @@ export class KeyedMessage { constructor(key: string, value: string | Buffer); } +export class Admin { + constructor(kafkaClient: KafkaClient); + listGroups(cb: (error: any, data: any) => any): void; + describeGroups(consumerGroups: any, cb: (error: any, data: any) => any): void; +} + // # Interfaces export interface Message { diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index 0ffe5d86b7..1e433172ae 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -14,6 +14,8 @@ const optionsClient = new kafka.Client('localhost:2181/', 'sendMessage', { }); optionsClient.topicExists(['topic'], (error: any) => { }); +optionsClient.loadMetadataForTopics(['topic'], (error: any, data: any) => { +}); optionsClient.refreshMetadata(['topic'], (error: any) => { }); optionsClient.close(); @@ -48,6 +50,11 @@ const optionsProducer = new kafka.Producer(basicClient, { partitionerType: 0 }); +optionsKafkaClient.getListGroups((error: any, data: any) => { +}); +optionsKafkaClient.describeGroups([], (error: any, data: any) => { +}); + const producer = new kafka.Producer(basicClient); producer.on('error', (error: Error) => { }); @@ -265,3 +272,9 @@ offset.fetchLatestOffsets(['t'], (err, offsets) => { }); offset.fetchEarliestOffsets(['t'], (err, offsets) => { }); + +const admin = new kafka.Admin(basicKafkaClient); +admin.listGroups((err, data) => { +}); +admin.describeGroups({}, (err, data) => { +}); From 7e1ff3773b25acf72e18d97760bc44ec87394649 Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Fri, 27 Jul 2018 13:43:37 -0400 Subject: [PATCH 009/275] lodash: iteratee shorthand should allow numbers and symbols (#27642) --- types/lodash/common/common.d.ts | 19 ++++---- types/lodash/lodash-tests.ts | 80 +++++++++++++++++---------------- 2 files changed, 52 insertions(+), 47 deletions(-) diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index dcbe28cb3a..ccbd9d30f1 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -179,16 +179,17 @@ declare module "../index" { } type NotVoid = {} | null | undefined; + type IterateeShorthand = PropertyName | [PropertyName, any] | PartialDeep; type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; - type ListIteratee = ListIterator | string | [string, any] | PartialDeep; - type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; + type ListIteratee = ListIterator | IterateeShorthand; + type ListIterateeCustom = ListIterator | IterateeShorthand; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; - type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; - type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIteratee = ObjectIterator | IterateeShorthand; + type ObjectIterateeCustom = ObjectIterator | IterateeShorthand; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type StringIterator = (char: string, index: number, string: string) => TResult; @@ -207,10 +208,10 @@ declare module "../index" { type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; type MemoVoidIteratorCapped = (acc: TResult, curr: T) => void; - type ValueIteratee = ((value: T) => NotVoid) | string | [string, any] | PartialDeep; - type ValueIterateeCustom = ((value: T) => TResult) | string | [string, any] | PartialDeep; + type ValueIteratee = ((value: T) => NotVoid) | IterateeShorthand; + type ValueIterateeCustom = ((value: T) => TResult) | IterateeShorthand; type ValueIteratorTypeGuard = (value: T) => value is S; - type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | string | [string, any] | PartialDeep; + type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | IterateeShorthand; type Comparator = (a: T, b: T) => boolean; type Comparator2 = (a: T1, b: T2) => boolean; @@ -263,6 +264,6 @@ declare module "../index" { type DictionaryIteratorTypeGuard = ObjectIteratorTypeGuard, S>; // NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated. type NumericDictionaryIterator = (value: T, key: string, collection: NumericDictionary) => TResult; - type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; - type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIteratee = NumericDictionaryIterator | IterateeShorthand; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | IterateeShorthand; } diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 2201a9a5cd..e9eb4d98ae 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -2539,65 +2539,67 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper ""; + const subKey: string | number | symbol = anything; _.keyBy("abcd"); // $ExpectType Dictionary _.keyBy("abcd", stringIterator); // $ExpectType Dictionary _.keyBy(list); // $ExpectType Dictionary _.keyBy(list, valueIterator); // $ExpectType Dictionary - _.keyBy(list, "a"); // $ExpectType Dictionary + _.keyBy(list, subKey); // $ExpectType Dictionary _.keyBy(list, { a: 42 }); // $ExpectType Dictionary _.keyBy(dictionary); // $ExpectType Dictionary _.keyBy(dictionary, valueIterator); // $ExpectType Dictionary - _.keyBy(dictionary, "a"); // $ExpectType Dictionary + _.keyBy(dictionary, subKey); // $ExpectType Dictionary _.keyBy(dictionary, { a: 42 }); // $ExpectType Dictionary _.keyBy(numericDictionary); // $ExpectType Dictionary _.keyBy(numericDictionary, valueIterator); // $ExpectType Dictionary _.keyBy(numericDictionary, "a"); // $ExpectType Dictionary + _.keyBy(numericDictionary, subKey); // $ExpectType Dictionary _.keyBy(numericDictionary, { a: 42 }); // $ExpectType Dictionary _("abcd").keyBy(); // $ExpectType LoDashImplicitWrapper> _("abcd").keyBy(stringIterator); // $ExpectType LoDashImplicitWrapper> _(list).keyBy(); // $ExpectType LoDashImplicitWrapper> _(list).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(list).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(list).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(list).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy(); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(dictionary).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(dictionary).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy(); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(numericDictionary).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(numericDictionary).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _.chain("abcd").keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain("abcd").keyBy(stringIterator); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(list).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(list).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(dictionary).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(dictionary).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(numericDictionary).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(numericDictionary).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> fp.keyBy(valueIterator, list); // $ExpectType Dictionary fp.keyBy(valueIterator)(list); // $ExpectType Dictionary - fp.keyBy("a", list); // $ExpectType Dictionary + fp.keyBy(subKey, list); // $ExpectType Dictionary fp.keyBy({ a: 42 }, list); // $ExpectType Dictionary - fp.keyBy(["a", 42], list); // $ExpectType Dictionary + fp.keyBy([subKey, 42], list); // $ExpectType Dictionary fp.keyBy(valueIterator, dictionary); // $ExpectType Dictionary - fp.keyBy("a", dictionary); // $ExpectType Dictionary + fp.keyBy(subKey, dictionary); // $ExpectType Dictionary fp.keyBy({ a: 42 }, dictionary); // $ExpectType Dictionary - fp.keyBy(["a", 42], dictionary); // $ExpectType Dictionary + fp.keyBy([subKey, 42], dictionary); // $ExpectType Dictionary fp.keyBy(valueIterator, numericDictionary); // $ExpectType Dictionary - fp.keyBy("a", numericDictionary); // $ExpectType Dictionary + fp.keyBy(subKey, numericDictionary); // $ExpectType Dictionary fp.keyBy({ a: 42 }, numericDictionary); // $ExpectType Dictionary - fp.keyBy(["a", 42], numericDictionary); // $ExpectType Dictionary + fp.keyBy([subKey, 42], numericDictionary); // $ExpectType Dictionary } // _.invoke @@ -3026,74 +3028,76 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper _.chain(list).some(listIterator); // $ExpectType LoDashExplicitWrapper - _.chain(list).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(list).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(list).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(list).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(list).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some(); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some(dictionaryIterator); // $ExpectType LoDashExplicitWrapper - _.chain(dictionary).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(dictionary).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(dictionary).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(dictionary).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some(); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some(numericDictionaryIterator); // $ExpectType LoDashExplicitWrapper - _.chain(numericDictionary).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(numericDictionary).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(numericDictionary).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(numericDictionary).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper fp.some(valueIterator, list); // $ExpectType boolean - fp.some("a")(list); // $ExpectType boolean + fp.some(subKey)(list); // $ExpectType boolean fp.some({ a: 42 }, list); // $ExpectType boolean - fp.some(["a", 42], list); // $ExpectType boolean + fp.some([subKey, 42], list); // $ExpectType boolean fp.some(valueIterator, dictionary); // $ExpectType boolean - fp.some("a")(dictionary); // $ExpectType boolean + fp.some(subKey)(dictionary); // $ExpectType boolean fp.some({ a: 42 })(dictionary); // $ExpectType boolean - fp.some(["a", 42])(dictionary); // $ExpectType boolean + fp.some([subKey, 42])(dictionary); // $ExpectType boolean fp.some(valueIterator, numericDictionary); // $ExpectType boolean - fp.some("a")(numericDictionary); // $ExpectType boolean + fp.some(subKey)(numericDictionary); // $ExpectType boolean fp.some({ a: 42 })(numericDictionary); // $ExpectType boolean - fp.some(["a", 42])(numericDictionary); // $ExpectType boolean + fp.some([subKey, 42])(numericDictionary); // $ExpectType boolean } // _.sortBy From bb8ca69fc13c003029060ab81f650015e713fa5e Mon Sep 17 00:00:00 2001 From: Igor Adrov Date: Fri, 27 Jul 2018 20:44:31 +0300 Subject: [PATCH 010/275] [cleave.js] Add time options (#27636) --- types/cleave.js/options/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/cleave.js/options/index.d.ts b/types/cleave.js/options/index.d.ts index 60e2e99e40..65d87d79e1 100644 --- a/types/cleave.js/options/index.d.ts +++ b/types/cleave.js/options/index.d.ts @@ -19,6 +19,12 @@ export interface CleaveOptions { datePattern?: ReadonlyArray; } +// Time Options +export interface CleaveOptions { + time?: boolean; + timePattern?: ReadonlyArray; +} + // Numeral Options export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan" | "none"; From c16617c259c04c51d686c1d5561a578a4247a427 Mon Sep 17 00:00:00 2001 From: Martin Hochel Date: Fri, 27 Jul 2018 19:46:16 +0200 Subject: [PATCH 011/275] feat(rollup-plugin-json): bump version, rollup dependency, add jsdoc (#27633) --- types/rollup-plugin-json/index.d.ts | 15 ++++++++++++++- types/rollup-plugin-json/package.json | 2 +- .../rollup-plugin-json-tests.ts | 2 ++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/types/rollup-plugin-json/index.d.ts b/types/rollup-plugin-json/index.d.ts index 150da4f1d3..795f24a005 100644 --- a/types/rollup-plugin-json/index.d.ts +++ b/types/rollup-plugin-json/index.d.ts @@ -1,14 +1,27 @@ -// Type definitions for rollup-plugin-json 2.3 +// Type definitions for rollup-plugin-json 3.0 // Project: https://github.com/rollup/rollup-plugin-json#readme // Definitions by: Andy Mockler +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { Plugin } from 'rollup'; export interface Options { + /** + * All JSON files will be parsed by default, but you can also specifically include/exclude files + */ include?: string | string[]; exclude?: string | string[]; + /** + * for tree-shaking, properties will be declared as variables, using either `var` or `const` + * @default false + */ preferConst?: boolean; + /** + * specify indentation for the generated default export — defaults to '\t' + * @default '\t' + */ indent?: string; } diff --git a/types/rollup-plugin-json/package.json b/types/rollup-plugin-json/package.json index 60161a270c..ee69ca3cd2 100644 --- a/types/rollup-plugin-json/package.json +++ b/types/rollup-plugin-json/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "rollup": "^0.54.0" + "rollup": "^0.63.4" } } diff --git a/types/rollup-plugin-json/rollup-plugin-json-tests.ts b/types/rollup-plugin-json/rollup-plugin-json-tests.ts index 50baf7f03f..32e7b26b7a 100644 --- a/types/rollup-plugin-json/rollup-plugin-json-tests.ts +++ b/types/rollup-plugin-json/rollup-plugin-json-tests.ts @@ -1,3 +1,5 @@ import json from 'rollup-plugin-json'; json(); // $ExpectType Plugin + +json({preferConst: true, indent: ' '}); // $ExpectType Plugin From da2e5d70793e0a3016dc6454dd9956aedb73d31a Mon Sep 17 00:00:00 2001 From: Alex Jerabek <38896772+AlexJerabek@users.noreply.github.com> Date: Fri, 27 Jul 2018 10:49:25 -0700 Subject: [PATCH 012/275] Adding periods to OneNote class descriptions (#27625) --- types/office-js/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 6f88772854..e064c0b3b4 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -52959,7 +52959,7 @@ declare namespace OneNote { } /** * - * Represents data obtained by OCR (optical character recognition) of an image + * Represents data obtained by OCR (optical character recognition) of an image. * * [Api set: OneNoteApi 1.1] */ @@ -52981,7 +52981,7 @@ declare namespace OneNote { } /** * - * Weak reference to an ink stroke object and its content parent + * Weak reference to an ink stroke object and its content parent. * * [Api set: OneNoteApi 1.1] */ From e10e89ab200134ff82a596ec455aad3fb7830ca2 Mon Sep 17 00:00:00 2001 From: Alex Jerabek <38896772+AlexJerabek@users.noreply.github.com> Date: Fri, 27 Jul 2018 10:49:59 -0700 Subject: [PATCH 013/275] [Office-js] Changing OWAView to an enum (#27624) * Removing quotes from string * Adding enum --- types/office-js/index.d.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index e064c0b3b4..4499687470 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -5730,6 +5730,23 @@ declare namespace Office { */ Dec = "dec" } + /** + * Represents the current view of Outlook Web App. + */ + enum OWAView { + /** + * One column view. Displayed when the screen is narrow. Outlook Web App uses this single-column layout on the entire screen of a smartphone. + */ + OneColumn = "OneColumn", + /** + * Two column view. Displayed when the screen is wider. Outlook Web App uses this view on most tablets. + */ + TwoColumns = "TwoColumns", + /** + Three column view. Displayed when the screen is wide. For example, Outlook Web App uses this view in a full screen window on a desktop computer. + */ + ThreeColumns = "ThreeColumns" + } /** * Specifies the type of recipient for an appointment. * @@ -7165,7 +7182,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ - OWAView: "string"; + OWAView: MailboxEnums.OWAView | "OneColumn" | "TwoColumns" | "ThreeColumns"; } /** * Provides the email properties of the sender or specified recipients of an email message or appointment. @@ -11898,7 +11915,7 @@ declare namespace Office { * * - hostVersion (string): A string that represents the version of either the host application or the Exchange Server. If the mail add-in is running on the Outlook desktop client or Outlook for iOS, the hostVersion property returns the version of the host application, Outlook. In Outlook Web App, the property returns the version of the Exchange Server. An example is the string 15.0.468.0. * - * - OWAView (string): A string that represents the current view of Outlook Web App. If the host application is not Outlook Web App, then accessing this property results in undefined. Outlook Web App has three views (OneColumn - displayed when the screen is narrow, TwoColumns - displayed when the screen is wider, and ThreeColumns - displayed when the screen is wide.) that correspond to the width of the screen and the window, and the number of columns that can be displayed. + * - OWAView (MailboxEnums.OWAView or string): An enum (or string literal) that represents the current view of Outlook Web App. If the host application is not Outlook Web App, then accessing this property results in undefined. Outlook Web App has three views (OneColumn - displayed when the screen is narrow, TwoColumns - displayed when the screen is wider, and ThreeColumns - displayed when the screen is wide) that correspond to the width of the screen and the window, and the number of columns that can be displayed. * * More information is under {@link Office.Diagnostics}. * From 363ddce949814ede346c5e2120f1486a87443109 Mon Sep 17 00:00:00 2001 From: Alex Jerabek <38896772+AlexJerabek@users.noreply.github.com> Date: Fri, 27 Jul 2018 10:50:13 -0700 Subject: [PATCH 014/275] Conventing coercionType descriptions to a table (#27623) --- types/office-js/index.d.ts | 130 ++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 37 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 4499687470..06a7e23655 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -2395,21 +2395,40 @@ declare namespace Office { * * * - * @param coercionType The type of data structure to return. + * The possible values for the {@link Office.CoercionType} parameter vary by the host. * - * The possible values for the {@link Office.CoercionType} parameter vary by the host: - * - * - Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online only: `Office.CoercionType.Text` (string) - * - * - Excel, Word, and Word Online only: `Office.CoercionType.Matrix` (array of arrays) - * - * - Access, Excel, Word, and Word Online only: `Office.CoercionType.Table` (TableData object) - * - * - Word only: `Office.CoercionType.Html` - * - * - Word and Word Online only: `Office.CoercionType.Ooxml` (Office Open XML) - * - * - PowerPoint and PowerPoint Online only: `Office.CoercionType.SlideRange` + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
HostSupported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online`Office.CoercionType.Text` (string)
Excel, Word, and Word Online`Office.CoercionType.Matrix` (array of arrays)
Access, Excel, Word, and Word Online`Office.CoercionType.Table` (TableData object)
Word`Office.CoercionType.Html`
Word and Word Online `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
+ * + * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. * * @param options Provides options for customizing what data is returned and how it is formatted. * @@ -2488,21 +2507,40 @@ declare namespace Office { * PowerPointInsert imageInserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio. * * - * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. + * The possible values for the {@link Office.CoercionType} parameter vary by the host. * - * The possible CoercionTypes that can be used for the data parameter, or for the coercionType option, vary by host: - * - * - `Office.CoercionType.Text`: Excel, Word, PowerPoint - * - * - `Office.CoercionType.Matrix`: Excel, Word - * - * - `Office.CoercionType.Table`: Access, Excel, Word - * - * - `Office.CoercionType.Html`: Word - * - * - `Office.CoercionType.Ooxml`: Word - * - * - `Office.CoercionType.Image`: Excel, Word, PowerPoint + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
HostSupported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online`Office.CoercionType.Text` (string)
Excel, Word, and Word Online`Office.CoercionType.Matrix` (array of arrays)
Access, Excel, Word, and Word Online`Office.CoercionType.Table` (TableData object)
Word`Office.CoercionType.Html`
Word and Word Online `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
+ * + * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. * * If the value passed for `data` is: * @@ -7821,7 +7859,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -8640,7 +8680,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -8658,7 +8700,9 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -9399,7 +9443,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -9915,7 +9961,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -9933,7 +9981,9 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read * - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -10620,7 +10670,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -11443,7 +11495,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -11461,7 +11515,9 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ From f7d9c48b415e49855df3ced6542095f23ce40995 Mon Sep 17 00:00:00 2001 From: Alex Jerabek <38896772+AlexJerabek@users.noreply.github.com> Date: Fri, 27 Jul 2018 10:50:22 -0700 Subject: [PATCH 015/275] Removing obsolete references to Excel missing coauth (#27621) --- types/office-js/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 06a7e23655..36c659a7b2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -25,7 +25,9 @@ declare namespace Office { startCustomFunctions(): Promise; } - /** A Promise object. Promises can be chained via ".then", and errors can be caught via ".catch". When a browser-provided native Promise implementation is available, Office.Promise will switch to use the native Promise instead. */ + /** A Promise object. Promises can be chained via ".then", and errors can be caught via ".catch". + * When a browser-provided native Promise implementation is available, Office.Promise will switch to use the native Promise instead. + */ var Promise: IPromiseConstructor; // Note: this is a copy of the PromiseConstructor object from @@ -2905,12 +2907,10 @@ declare namespace Office { * * Requirement SetsSettings * - * This method is useful in Word and PowerPoint coauthoring scenarios when multiple instances of the same add-in are working against the same document. + * This method is useful in Excel, Word, and PowerPoint coauthoring scenarios when multiple instances of the same add-in are working against the same document. * Because each add-in is working against an in-memory copy of the settings loaded from the document at the time the user opened it, the settings values used by each user can get out of sync. * This can happen whenever an instance of the add-in calls the Settings.saveAsync method to persist all of that user's settings to the document. * Calling the refreshAsync method from the event handler for the settingsChanged event of the add-in will refresh the settings values for all users. - * - * The refreshAsync method can be called from add-ins created for Excel, but since it doesn't support coauthoring there is no reason to do so. * * In the callback function passed to the refreshAsync method, you can use the properties of the AsyncResult object to return the following information. * @@ -2982,8 +2982,8 @@ declare namespace Office { * Any settings previously saved by an add-in are loaded when it is initialized, so during the lifetime of the session you can just use the set and get methods to work with the in-memory copy of the settings property bag. * When you want to persist the settings so that they are available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file; however, the changes to the document file itself are saved only when the user (or AutoRecover setting) saves the document to the file system. - * The refreshAsync method is only useful in coauthoring scenarios (which are only supported in Word) when other instances of the same add-in might change the settings and those changes should be made available to all instances. + * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file itself are saved only when the user (or AutoRecover setting) saves the document to the file system. + * The refreshAsync method is only useful in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to all instances. * * * From d5627ab7a85984f83dc30ede59d2cb8e6874b07d Mon Sep 17 00:00:00 2001 From: Georgii Dolzhykov Date: Fri, 27 Jul 2018 20:50:46 +0300 Subject: [PATCH 016/275] angular-mocks: add myself to reviewers (#27620) * angular-mocks: add myself to reviewers * remove blank line --- types/angular-mocks/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index 53157a1f08..b2fcc1c2b1 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Tony Curtis +// Definitions by: Diego Vilar +// Tony Curtis +// Georgii Dolzhykov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 From 21077b265715aa40260eb05e747d25da0a57168b Mon Sep 17 00:00:00 2001 From: Brian Crowell Date: Fri, 27 Jul 2018 12:52:13 -0500 Subject: [PATCH 017/275] [node]: Make stream destroy method signatures match (#27608) * [node]: Make stream destroy method signatures match The "destroy" option when creating streams has the same signature as the _destroy method on the stream: a function accepting an optional error and a callback which also takes an optional error. * Fix tests affected by the change in stream definitions --- types/amp/amp-tests.ts | 2 +- types/node/index.d.ts | 14 +++++++------- types/node/node-tests.ts | 13 ++++++++++--- types/node/v8/index.d.ts | 14 +++++++------- types/node/v8/node-tests.ts | 13 ++++++++++--- types/node/v9/index.d.ts | 14 +++++++------- types/node/v9/node-tests.ts | 13 ++++++++++--- types/stream-chain/stream-chain-tests.ts | 4 ++-- 8 files changed, 54 insertions(+), 33 deletions(-) diff --git a/types/amp/amp-tests.ts b/types/amp/amp-tests.ts index 1e17bc8507..983c1f993b 100644 --- a/types/amp/amp-tests.ts +++ b/types/amp/amp-tests.ts @@ -32,7 +32,7 @@ new Stream({ highWaterMark: 1, decodeStrings: true, objectMode: true, - destroy: (error?: Error) => { + destroy: (error: Error | null) => { return 'handle error'; }, final: (callback: (error?: Error) => void) => { diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 46810993df..2dcf9e6165 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -694,7 +694,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -707,7 +707,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -5972,7 +5972,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5990,7 +5990,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; destroy(error?: Error): void; /** @@ -6060,7 +6060,7 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: any, encoding: string, callback: Function) => any; writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; final?: (callback: (error?: Error) => void) => void; } @@ -6071,7 +6071,7 @@ declare module "stream" { constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -6164,7 +6164,7 @@ declare module "stream" { constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 86907ebb39..0ffd7b2eee 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -954,8 +954,9 @@ function simplified_stream_ctor_test() { read(size) { size.toFixed(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); } }); @@ -970,8 +971,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, final(cb) { cb(null); @@ -992,6 +994,10 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy(error, cb) { + error.stack; + cb(error); + }, readableObjectMode: true, writableObjectMode: true }); @@ -1018,8 +1024,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, allowHalfOpen: true, readableObjectMode: true, diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index da0db26be4..6acb0c62a7 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -532,7 +532,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -544,7 +544,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -5299,7 +5299,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5316,7 +5316,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; destroy(error?: Error): void; /** @@ -5384,7 +5384,7 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: any, encoding: string, callback: Function) => any; writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; final?: (callback: (error?: Error) => void) => void; } @@ -5394,7 +5394,7 @@ declare module "stream" { constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5486,7 +5486,7 @@ declare module "stream" { constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index dee74cc036..318062648a 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -913,8 +913,9 @@ function simplified_stream_ctor_test() { read(size) { size.toFixed(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); } }); @@ -929,8 +930,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, final(cb) { cb(null); @@ -951,6 +953,10 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy(error, cb) { + error.stack; + cb(error); + }, readableObjectMode: true, writableObjectMode: true }); @@ -977,8 +983,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, allowHalfOpen: true, readableObjectMode: true, diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 86866daa77..7d9b0dbb29 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -674,7 +674,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -687,7 +687,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -5376,7 +5376,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5394,7 +5394,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; destroy(error?: Error): void; /** @@ -5462,7 +5462,7 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; writev?: (chunks: Array<{ chunk: string | Buffer, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; final?: (callback: (error?: Error) => void) => void; } @@ -5473,7 +5473,7 @@ declare module "stream" { constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5566,7 +5566,7 @@ declare module "stream" { constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 72ce012a3c..30b0666773 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -942,8 +942,9 @@ function simplified_stream_ctor_test() { read(size) { size.toFixed(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); } }); @@ -958,8 +959,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, final(cb) { cb(null); @@ -980,6 +982,10 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy(error, cb) { + error.stack; + cb(error); + }, readableObjectMode: true, writableObjectMode: true }); @@ -1006,8 +1012,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, allowHalfOpen: true, readableObjectMode: true, diff --git a/types/stream-chain/stream-chain-tests.ts b/types/stream-chain/stream-chain-tests.ts index 282b88c7da..43d4f3d68b 100644 --- a/types/stream-chain/stream-chain-tests.ts +++ b/types/stream-chain/stream-chain-tests.ts @@ -142,7 +142,7 @@ const streamToArray = (array: number[]): Writable => // include Writable const out1: number[] = []; - const chain = new Chain([(x: number) => 2 * x], streamToArray(out1)); + const chain = new Chain([(x: number) => 2 * x, streamToArray(out1)]); const out2: number[] = []; streamFromArray([1, 2, 3]).pipe(chain); @@ -153,7 +153,7 @@ const streamToArray = (array: number[]): Writable => // include Readable and Writable const out1: number[] = []; - const chain = new Chain([streamFromArray([1, 2, 3]), (x: number) => 2 * x], streamToArray(out1)); + const chain = new Chain([streamFromArray([1, 2, 3]), (x: number) => 2 * x, streamToArray(out1)]); const out2: number[] = []; chain.on('data', value => out2.push(+value)); From b7d70d687917c5e4a8384b3364bfdd57a8eb80c9 Mon Sep 17 00:00:00 2001 From: George Kalpakas Date: Fri, 27 Jul 2018 22:02:54 +0000 Subject: [PATCH 018/275] Update types and docs for `angular-route` and `angular-mocks` (#27473) * angular-route: Update types and docs for `IRoute` * angular-mocks: Update types and docs for 1.7 Related to angular/angular.js#16603 and angular/angular.js#16640. --- types/angular-mocks/angular-mocks-tests.ts | 18 ++- types/angular-mocks/index.d.ts | 114 ++++++++++++++++++- types/angular-route/angular-route-tests.ts | 15 +++ types/angular-route/index.d.ts | 121 ++++++++++++++++----- 4 files changed, 234 insertions(+), 34 deletions(-) diff --git a/types/angular-mocks/angular-mocks-tests.ts b/types/angular-mocks/angular-mocks-tests.ts index 2d74dd26bc..662d75c079 100644 --- a/types/angular-mocks/angular-mocks-tests.ts +++ b/types/angular-mocks/angular-mocks-tests.ts @@ -87,7 +87,6 @@ timeoutService.verifyNoPendingTasks(); let intervalService: ng.IIntervalService; let intervalServiceTimeActuallyAdvanced: number; -intervalServiceTimeActuallyAdvanced = intervalService.flush(); intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); /////////////////////////////////////// @@ -1516,6 +1515,23 @@ requestHandler.respond(404, { key: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); +/////////////////////////////////////// +// IFlushPendingTasksService +/////////////////////////////////////// +let $flushPendingTasks: ng.IFlushPendingTasksService; +$flushPendingTasks(); +$flushPendingTasks(42); + +/////////////////////////////////////// +// IVerifyNoPendingTasksService +/////////////////////////////////////// +let $verifyNoPendingTasks: ng.IVerifyNoPendingTasksService; +$verifyNoPendingTasks(); +$verifyNoPendingTasks('task type'); + +/////////////////////////////////////// +// browserTrigger +/////////////////////////////////////// browserTrigger(document.body, 'click'); browserTrigger(angular.element(document.body), 'click'); browserTrigger(angular.element(document.body), 'click', { which: 1, keys: ['ctrl'] }); diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index b2fcc1c2b1..a2aa4fe29e 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6 +// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.7 // Project: http://angularjs.org // Definitions by: Diego Vilar // Tony Curtis @@ -61,7 +61,38 @@ declare module 'angular' { // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { + /** + * **Deprecated** since version 1.7.3. (Use `$flushPendingTasks` instead.) + * + * --- + * Flushes the queue of pending tasks. + * + * _This method is essentially an alias of `$flushPendingTasks`._ + * + * > For historical reasons, this method will also flush non-`$timeout` pending tasks, such as + * > `$q` promises and tasks scheduled via `$applyAsync` and `$evalAsync`. + * + * @param delay - The maximum timeout amount to flush up until. + */ flush(delay?: number): void; + + /** + * **Deprecated** since version 1.7.3. (Use `$verifyNoPendingTasks` instead.) + * + * --- + * Verifies that there are no pending tasks that need to be flushed. It throws an error if there + * are still pending tasks. + * + * _This method is essentially an alias of `$verifyNoPendingTasks` (called with no arguments)._ + * + * > For historical reasons, this method will also verify non-`$timeout` pending tasks, such as + * > pending `$http` requests, in-progress `$route` transitions, unresolved `$q` promises and + * > tasks scheduled via `$applyAsync` and `$evalAsync`. + * > + * > It is recommended to use `$verifyNoPendingTasks` instead, which additionally supports + * > verifying a specific type of tasks. For example, you can verify there are no pending + * > timeouts with `$verifyNoPendingTasks('$timeout')`. + */ verifyNoPendingTasks(): void; } @@ -71,7 +102,13 @@ declare module 'angular' { // Augments the original service /////////////////////////////////////////////////////////////////////////// interface IIntervalService { - flush(millis?: number): number; + /** + * Runs interval tasks scheduled to be run in the next `millis` milliseconds. + * + * @param millis - The maximum timeout amount to flush up until. + * @return The amount of time moved forward. + */ + flush(millis: number): number; } /////////////////////////////////////////////////////////////////////////// @@ -415,6 +452,65 @@ declare module 'angular' { whenRoute(method: string, url: string): mock.IRequestHandler; } + /////////////////////////////////////////////////////////////////////////// + // FlushPendingTasksService + // see https://docs.angularjs.org/api/ngMock/service/$flushPendingTasks + /////////////////////////////////////////////////////////////////////////// + interface IFlushPendingTasksService { + /** + * Flushes all currently pending tasks and executes the corresponding callbacks. + * + * Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be + * executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all + * other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but + * still asynchronously). + * + * If no delay is specified, it uses a delay such that all currently pending tasks are flushed. + * + * The types of tasks that are flushed include: + * + * - Pending timeouts (via `$timeout`). + * - Pending tasks scheduled via `$applyAsync`. + * - Pending tasks scheduled via `$evalAsync`. + * These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises). + * + * > Periodic tasks scheduled via `$interval` use a different queue and are not flushed by + * > `$flushPendingTasks()`. Use `$interval.flush(millis)` instead. + * + * @param millis - The number of milliseconds to flush. + */ + (delay?: number): void; + } + + /////////////////////////////////////////////////////////////////////////// + // VerifyNoPendingTasksService + // see https://docs.angularjs.org/api/ngMock/service/$verifyNoPendingTasks + /////////////////////////////////////////////////////////////////////////// + interface IVerifyNoPendingTasksService { + /** + * Verifies that there are no pending tasks that need to be flushed. It throws an error if there + * are still pending tasks. + * + * You can check for a specific type of tasks only, by specifying a `taskType`. + * + * Available task types: + * + * - `$timeout`: Pending timeouts (via `$timeout`). + * - `$http`: Pending HTTP requests (via `$http`). + * - `$route`: In-progress route transitions (via `$route`). + * - `$applyAsync`: Pending tasks scheduled via `$applyAsync`. + * - `$evalAsync`: Pending tasks scheduled via `$evalAsync`. + * These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises). + * + * > Periodic tasks scheduled via `$interval` use a different queue and are not taken into + * > account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no + * > pending `$interval` tasks. + * + * @param taskType - The type of tasks to check for. + */ + (taskType?: string): void; + } + /////////////////////////////////////////////////////////////////////////// // AnimateService // see https://docs.angularjs.org/api/ngMock/service/$animate @@ -515,6 +611,11 @@ declare module 'angular' { * for keyboard events (keydown, keypress, and keyup). */ charcode?: number; + /** + * [data](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data) for + * [CompositionEvents](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent). + */ + data?: string; /** * The elapsedTime for * [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent) @@ -568,10 +669,11 @@ declare global { * This is a global (window) function that is only available when the `ngMock` module is included. * It can be used to trigger a native browser event on an element, which is useful for unit testing. * - * @param element Either a wrapped jQuery/jqLite node or a DOM element - * @param eventType Optional event type. If none is specified, the function tries to determine - * the right event type for the element, e.g. `change` for `input[text]`. - * @param eventData An optional object which contains additional event data used when creating the event. + * @param element Either a wrapped jQuery/jqLite node or a DOM element. + * @param eventType Optional event type. If none is specified, the function tries to determine the + * right event type for the element, e.g. `change` for `input[text]`. + * @param eventData An optional object which contains additional event data used when creating the + * event. */ function browserTrigger( element: JQuery | Element, diff --git a/types/angular-route/angular-route-tests.ts b/types/angular-route/angular-route-tests.ts index 677c1589ed..e1e7bd43fd 100644 --- a/types/angular-route/angular-route-tests.ts +++ b/types/angular-route/angular-route-tests.ts @@ -39,6 +39,21 @@ $routeProvider return "I return a string" } }) + .when('/projects/:projectId/dashboard6', { + resolve: { + foo: () => 'foo', + bar: () => 'bar', + }, + resolveAs: 'baz', + resolveRedirectTo: [ + '$http', + ($http: ng.IHttpService) => $http.get('/is-admin').then(() => '/admin/lounge', () => undefined), + ], + }) + .when('/projects/:projectId/dashboard7', { + reloadOnUrl: false, + resolveRedirectTo: () => (Math.random() < 0.5) ? '/some/route' : undefined, + }) .otherwise({ redirectTo: '/' }) .otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" }) .otherwise("/"); diff --git a/types/angular-route/index.d.ts b/types/angular-route/index.d.ts index 56bd3f2263..15529f1572 100644 --- a/types/angular-route/index.d.ts +++ b/types/angular-route/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Angular JS (ngRoute module) 1.3 +// Type definitions for Angular JS (ngRoute module) 1.7 // Project: http://angularjs.org // Definitions by: Jonathan Park +// George Kalpakas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -52,7 +53,7 @@ declare module 'angular' { */ interface IRoute { /** - * {(string|function()=} + * {(string|Function)=} * Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string. */ controller?: string | InlineAnnotatedFunction; @@ -61,56 +62,122 @@ declare module 'angular' { */ controllerAs?: string; /** - * Undocumented? - */ - name?: string; - /** - * {string=|function()=} + * {(string|Function)=} * Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl. * * If template is a function, it will be called with the following parameters: * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - template?: string | { ($routeParams?: angular.route.IRouteParamsService): string; } + template?: string | { ($routeParams?: IRouteParamsService): string; } /** - * {string=|function()=} + * {(string|Function)=} * Path or function that returns a path to an html template that should be used by ngView. * * If templateUrl is a function, it will be called with the following parameters: * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - templateUrl?: string | { ($routeParams?: angular.route.IRouteParamsService): string; } + templateUrl?: string | { ($routeParams?: IRouteParamsService): string; } /** - * {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is: + * {Object.=} + * An optional map of dependencies which should be injected into the controller. If any of these + * dependencies are promises, the router will wait for them all to be resolved or one to be rejected before + * the controller is instantiated. + * If all the promises are resolved successfully, the values of the resolved promises are injected and + * `$routeChangeSuccess` event is fired. If any of the promises are rejected the `$routeChangeError` event + * is fired. + * For easier access to the resolved dependencies from the template, the `resolve` map will be available on + * the scope of the route, under `$resolve` (by default) or a custom name specified by the `resolveAs` + * property (see below). This can be particularly useful, when working with components as route templates. * - * - key - {string}: a name of a dependency to be injected into the controller. - * - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead. + * > **Note:** If your scope already contains a property with this name, it will be hidden or overwritten. + * > Make sure, you specify an appropriate name for this property, that does not collide with other + * > properties on the scope. + * + * The map object is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|Function}`: If `string` then it is an alias for a service. Otherwise if function, + * then it is called with `$injector#invoke()` and the return value is treated as the dependency. If the + * result is a promise, it is resolved before its value is injected into the controller. Be aware that + * `ngRoute.$routeParams` will still refer to the previous route within these resolve functions. Use + * `$route.current.params` to access the new route parameters, instead. */ resolve?: { [key: string]: any }; /** - * {(string|function())=} - * Value to update $location path with and trigger route redirection. - * - * If redirectTo is a function, it will be called with the following parameters: - * - * - {Object.} - route parameters extracted from the current $location.path() by applying the current route templateUrl. - * - {string} - current $location.path() - * - {Object} - current $location.search() - * - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search(). + * {string=} + * The name under which the `resolve` map will be available on the scope of the route. If omitted, defaults + * to `$resolve`. */ - redirectTo?: string | { ($routeParams?: angular.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any): string }; + resolveAs?: string; /** - * Reload route when only $location.search() or $location.hash() changes. + * {(string|Function)=} + * Value to update `$location` path with and trigger route redirection. * - * This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope. + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current `$location.path()` by applying the + * current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used to update + * `$location.url()`. If the function throws an error, no further processing will take place and the + * `$routeChangeError` event will be fired. + * + * Routes that specify `redirectTo` will not have their controllers, template functions or resolves called, + * the `$location` will be changed to the redirect url and route processing will stop. The exception to this + * is if the `redirectTo` is a function that returns `undefined`. In this case the route transition occurs + * as though there was no redirection. + */ + redirectTo?: string | { ($routeParams?: IRouteParamsService, $locationPath?: string, $locationSearch?: any): string }; + /** + * {Function=} + * A function that will (eventually) return the value to update `$location` URL with and trigger route + * redirection. In contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the + * return value can be either a string or a promise that will be resolved to a string. + * + * Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets resolved to + * `undefined`), no redirection takes place and the route transition occurs as though there was no + * redirection. + * + * If the function throws an error or the returned promise gets rejected, no further processing will take + * place and the `$routeChangeError` event will be fired. + * + * `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same route definition, + * will cause the latter to be ignored. + */ + resolveRedirectTo?: angular.Injectable<(...deps: any[]) => angular.IPromise | string | undefined>; + /** + * {boolean=true} + * Reload route when any part of the URL changes (including the path) even if the new URL maps to the same + * route. + * + * If the option is set to `false` and the URL in the browser changes, but the new URL maps to the same + * route, then a `$routeUpdate` event is broadcasted on the root scope (without reloading the route). + * + * Defaults to `true`. + */ + reloadOnUrl?: boolean; + /** + * {boolean=true} + * Reload route when only `$location.search()` or `$location.hash()` changes. + * + * If the option is set to `false` and the URL in the browser changes, then a `$routeUpdate` event is + * broadcasted on the root scope (without reloading the route). + * + * > Note: This option has no effect if `reloadOnUrl` is set to `false`. + * + * Defaults to `true`. */ reloadOnSearch?: boolean; /** - * Match routes without being case sensitive + * {boolean=false} + * Match routes without being case sensitive. + * If the option is set to `true`, then the particular route can be matched without being case sensitive. * - * This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive + * Defaults to `false`. */ caseInsensitiveMatch?: boolean; } From e4dc373d163e04a8b72091a3ce8190cd148687cd Mon Sep 17 00:00:00 2001 From: Scott Trinh Date: Fri, 27 Jul 2018 18:57:11 -0400 Subject: [PATCH 019/275] [knex] Allow Identifier Syntax in table Query Builder (#27644) --- types/knex/index.d.ts | 5 +++-- types/knex/knex-tests.ts | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 82dbb5f235..f6be274a30 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -21,9 +21,10 @@ type Value = string | number | boolean | Date | Array | Array | type ValueMap = { [key: string]: Value | Knex.QueryBuilder }; type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; type TableName = string | Knex.Raw | Knex.QueryBuilder; +type Identifier = { [alias: string]: string }; interface Knex extends Knex.QueryInterface { - (tableName?: TableName): Knex.QueryBuilder; + (tableName?: TableName | Identifier): Knex.QueryBuilder; VERSION: string; __knex__: string; @@ -179,7 +180,7 @@ declare namespace Knex { } interface Table { - (tableName: TableName): QueryBuilder; + (tableName: TableName | Identifier): QueryBuilder; (callback: Function): QueryBuilder; (raw: Raw): QueryBuilder; } diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 89a120fac1..0c04dfc918 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1103,3 +1103,23 @@ knex.schema table.decimal('dec', null); }) .dropTable('testTable'); + +// allow specifying an alias for a table name +knex.schema + .dropTableIfExists('foo') + .dropTableIfExists('bar') + .createTable('foo', function (table) { + table.uuid('id').primary(); + }) + .createTable('bar', function (table) { + table.uuid('id').primary(); + }); + +knex({ + table1: 'foo', + table2: 'bar' +}) + .select({ + table1Id: 'table1.id', + table2Id: 'table2.id' + }); From 5568145d86e98f2c27b5f66e791998eb44d06be1 Mon Sep 17 00:00:00 2001 From: Abraham Williams <4braham@gmail.com> Date: Fri, 27 Jul 2018 17:57:26 -0500 Subject: [PATCH 020/275] Follow param can be a string of user_ids. (#27643) --- types/twit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index c0367da976..9918d58470 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -262,7 +262,7 @@ declare module 'twit' { user_id?: number | string, lat?: number, long?: number, - follow?: boolean, + follow?: boolean | string, include_email?: boolean, cursor?: number | string, tweet_mode?: string, From 735b9a1cc6a9970331f263afa0d2c024685edfbd Mon Sep 17 00:00:00 2001 From: arteforme <6117939+arteforme@users.noreply.github.com> Date: Fri, 27 Jul 2018 15:57:55 -0700 Subject: [PATCH 021/275] react-bootstrap-typeahead: Added isInvalid, isValid introduced in 3.2 (#27640) --- types/react-bootstrap-typeahead/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 005a7633ed..ad64d0941a 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-bootstrap-typeahead 3.1 +// Type definitions for react-bootstrap-typeahead 3.2 // Project: https://github.com/ericgio/react-bootstrap-typeahead // Definitions by: Guymestef // Rajab Shakirov @@ -70,9 +70,15 @@ export interface TypeaheadProps { /* Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored. */ inputProps?: object; + /* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`. */ + isInvalid?: boolean; + /* Indicate whether an asynchronous data fetch is happening. */ isLoading?: boolean; + /* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`. */ + isValid?: boolean; + /* Specify which option key to use for display or a render function. By default, the selector will use the label key. */ labelKey?: string | ((option: T | string) => string); From d8814ea085ef70eb9d3c6d0f40fa0fb81eece4d1 Mon Sep 17 00:00:00 2001 From: junseok Date: Sat, 28 Jul 2018 09:12:31 +0900 Subject: [PATCH 022/275] Updates new functions in @storybook/addon-actions (#27627) * Updates new functions in @storybook/addon-actions * Fix about reviewed contents. --- types/storybook__addon-actions/index.d.ts | 12 +++++++++--- .../storybook__addon-actions-tests.tsx | 6 +++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/types/storybook__addon-actions/index.d.ts b/types/storybook__addon-actions/index.d.ts index 2d5cc73ef8..6c90ea4533 100644 --- a/types/storybook__addon-actions/index.d.ts +++ b/types/storybook__addon-actions/index.d.ts @@ -1,11 +1,17 @@ -// Type definitions for @storybook/addon-actions 3.0 +// Type definitions for @storybook/addon-actions 3.4 // Project: https://github.com/storybooks/storybook -// Definitions by: Joscha Feth +// Definitions by: Joscha Feth , June // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 export type HandlerFunction = (...args: any[]) => undefined; export type DecoratorFunction = (args: any[]) => any[]; +export interface Options { + depth?: number; + clearOnStoryChange?: boolean; + limit?: number; +} -export function decorateAction(decorators: DecoratorFunction[]): (name: string) => HandlerFunction; +export function decorateAction(decorators: DecoratorFunction[]): (name: string, options?: Options) => HandlerFunction; +export function configureActions(options: Options): undefined; export function action(name: string): HandlerFunction; diff --git a/types/storybook__addon-actions/storybook__addon-actions-tests.tsx b/types/storybook__addon-actions/storybook__addon-actions-tests.tsx index b9c9bbba7f..2011694cb7 100644 --- a/types/storybook__addon-actions/storybook__addon-actions-tests.tsx +++ b/types/storybook__addon-actions/storybook__addon-actions-tests.tsx @@ -2,7 +2,11 @@ import * as React from 'react'; import { storiesOf } from '@storybook/react'; -import { action, decorateAction } from '@storybook/addon-actions'; +import { action, decorateAction, configureActions } from '@storybook/addon-actions'; + +configureActions({ + depth: 100 +}); const firstArgAction = decorateAction([ args => args.slice(0, 1) From 8858276e3c5a2d08d99ac06d31fa1ae01ad5b208 Mon Sep 17 00:00:00 2001 From: Roman Nuritdinov Date: Sat, 28 Jul 2018 03:12:53 +0300 Subject: [PATCH 023/275] Add missing module declarations for storejs (#27601) --- types/storejs/index.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/types/storejs/index.d.ts b/types/storejs/index.d.ts index f720d33617..733c0909b7 100644 --- a/types/storejs/index.d.ts +++ b/types/storejs/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/marcuswestin/store.js/ // Definitions by: Vincent Bortone // harry0000 +// Roman Nuritdinov (Ky6uk) // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Cross-browser storage for all use cases, used across the web. @@ -28,6 +29,18 @@ declare const store: StoreJsAPI; declare module 'store' { export = store; } +declare module 'store/dist/store.legacy' { + export = store; +} +declare module 'store/dist/store.legacy.min' { + export = store; +} +declare module 'store/dist/store.modern' { + export = store; +} +declare module 'store/dist/store.modern.min' { + export = store; +} declare const engine: StoreJsEngine; declare module 'store/src/store-engine' { From 4483a90ef235e21b2150fd0a2e93992c9d3d0428 Mon Sep 17 00:00:00 2001 From: Fabio Berta Date: Sat, 28 Jul 2018 02:13:09 +0200 Subject: [PATCH 024/275] bounds takes object or array for viewport (#27606) --- types/mapbox__geo-viewport/index.d.ts | 2 +- types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/mapbox__geo-viewport/index.d.ts b/types/mapbox__geo-viewport/index.d.ts index 9193e891ec..6cfa8638f8 100644 --- a/types/mapbox__geo-viewport/index.d.ts +++ b/types/mapbox__geo-viewport/index.d.ts @@ -12,4 +12,4 @@ export type BoundingBox = [number, number, number, number]; export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number): GeoViewport; -export function bounds(viewport: { lon: number; lat: number }, zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox; +export function bounds(viewport: { lon: number; lat: number } | [number, number], zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox; diff --git a/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts b/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts index c5349ac782..7a8ac93fea 100644 --- a/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts +++ b/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts @@ -11,3 +11,5 @@ const boundingBox = bounds({ lon: 100, lat: 200, }, 14, [640, 480]); + +const boundingBox2 = bounds([100, 200], 14, [640, 480]); From fb0db288951c2a87391063eb1a191e4fe260ff51 Mon Sep 17 00:00:00 2001 From: Michael Lumish Date: Fri, 27 Jul 2018 17:13:59 -0700 Subject: [PATCH 025/275] @types/node: add missing properties to Http2Session (#27588) * node types: add missing properties to Http2Session Add "connecting" and "ping" properties to Http2Session * Add NodeJS.TypedArray --- types/node/index.d.ts | 3 +++ types/node/node-tests.ts | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 2dcf9e6165..43d4f25cc9 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -7181,6 +7181,7 @@ declare module "http2" { readonly alpnProtocol?: string; close(callback?: () => void): void; readonly closed: boolean; + readonly connecting: boolean; destroy(error?: Error, code?: number): void; readonly destroyed: boolean; readonly encrypted?: boolean; @@ -7188,6 +7189,8 @@ declare module "http2" { readonly localSettings: Settings; readonly originSet?: string[]; readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; ref(): void; readonly remoteSettings: Settings; rstStream(stream: Http2Stream, code?: number): void; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 0ffd7b2eee..c3a23dc094 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -3630,6 +3630,7 @@ namespace http2_tests { let pendingSettingsAck: boolean = http2Session.pendingSettingsAck; let settings: http2.Settings = http2Session.localSettings; let closed: boolean = http2Session.closed; + let connecting: boolean = http2Session.connecting; settings = http2Session.remoteSettings; http2Session.ref(); @@ -3676,6 +3677,10 @@ namespace http2_tests { }); http2Session.settings(settings); + + http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); } // Http2Stream From 5b715ad1e9111c9ca06860abe0b58c2ad1efb15b Mon Sep 17 00:00:00 2001 From: golyalpha Date: Sat, 28 Jul 2018 02:14:23 +0200 Subject: [PATCH 026/275] Fix typing error in PolygonGraphics [Cesium] (#27563) * Fix typing error in PolygonGraphics The property outlineColor of PolygonGraphics can accept both Property and Color types. [Discussion on AnalyticalGraphicsInc/cesium](https://github.com/AnalyticalGraphicsInc/cesium/issues/6831) * Update version * Removed the Color type from outlineColor typedef. --- types/cesium/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index 967c124bac..f2bb11479c 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for cesium 1.46 +// Type definitions for cesium 1.47 // Project: http://cesiumjs.org // Definitions by: Aigars Zeiza // Harry Nicholls // Jared Szechy +// Radek Goláň jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -2370,7 +2371,7 @@ declare namespace Cesium { stRotation: Property; fill: Property; outline: Property; - outlineColor: Property; + outlineColor: Color; outlineWidth: Property; perPositionHeight: Property; constructor(options?: { From fc53fb37abe9991438ba32043406d940d4107a01 Mon Sep 17 00:00:00 2001 From: David Weinberg Date: Sat, 28 Jul 2018 01:18:00 +0100 Subject: [PATCH 027/275] @types/leaflet: Add property zoomControl to class Map (#27460) * Add property zoomControl to class Map Leaflet has a map property called zoomControl. This is useful for setting the position on these controls for the map. This is not available via the typings. Example usage: map.zoomControl.setPosition('topright'); * Leaflet: Map.zoomControl property Specify Map.zoomControl type more precisely as Control.Zoom --- types/leaflet/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 47b2ebc515..89c9cbd9b9 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -1406,6 +1406,7 @@ export class Map extends Evented { scrollWheelZoom: Handler; tap?: Handler; touchZoom: Handler; + zoomControl: Control.Zoom; options: MapOptions; } From 62533f96192e2fecf0e388fa6d0ed3f3dd9eba76 Mon Sep 17 00:00:00 2001 From: Mengjo Rodrick Nfinyoh Date: Sat, 28 Jul 2018 01:19:20 +0100 Subject: [PATCH 028/275] UpdateType(mongoose): make `plugin` function generic (#27456) --- types/mongoose/index.d.ts | 4 ++-- types/mongoose/mongoose-tests.ts | 24 ++++++++++++++++++++++++ types/mongoose/v3/index.d.ts | 6 +++--- types/mongoose/v3/mongoose-tests.ts | 25 ++++++++++++++++++++++++- types/mongoose/v4/index.d.ts | 4 ++-- types/mongoose/v4/mongoose-tests.ts | 23 +++++++++++++++++++++++ 6 files changed, 78 insertions(+), 8 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 6933a916f2..1beed12c69 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -151,7 +151,7 @@ declare module "mongoose" { * @param fn plugin callback * @param opts optional options */ - export function plugin(fn: Function, opts?: any): typeof mongoose; + export function plugin(fn: Function, opts?: T): typeof mongoose; /** Sets mongoose options */ export function set(key: string, value: any): void; @@ -655,7 +655,7 @@ declare module "mongoose" { * Registers a plugin for this schema. * @param plugin callback */ - plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; + plugin(plugin: (schema: Schema, options?: T) => void, opts?: T): this; /** * Defines a post hook for the document diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index c9d9c9266a..cadc7d9a83 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -592,6 +592,30 @@ export default function(schema: mongoose.Schema) { }); } +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + + /* * section document.js * http://mongoosejs.com/docs/api.html#document-js diff --git a/types/mongoose/v3/index.d.ts b/types/mongoose/v3/index.d.ts index 805f3f1de2..b38a20179c 100644 --- a/types/mongoose/v3/index.d.ts +++ b/types/mongoose/v3/index.d.ts @@ -14,7 +14,7 @@ declare module "mongoose" { function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; function modelNames(): string[]; - function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + function plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Mongoose; function get(key: string): any; function set(key: string, value: any): void; @@ -33,7 +33,7 @@ declare module "mongoose" { get(key: string): any; model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; modelNames(): string[]; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Mongoose; set(key: string, value: any): void; mongo: any; @@ -273,7 +273,7 @@ declare module "mongoose" { path(path: string): any; path(path: string, constructor: any): Schema; pathType(path: string): string; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Schema; pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; diff --git a/types/mongoose/v3/mongoose-tests.ts b/types/mongoose/v3/mongoose-tests.ts index ee56b9cc1b..4659348fd7 100644 --- a/types/mongoose/v3/mongoose-tests.ts +++ b/types/mongoose/v3/mongoose-tests.ts @@ -387,4 +387,27 @@ var eq = id.equals(id2); var kitty1 = new Kitty({}); var kitty2 = new Kitty({}); -var kittyEq = kitty1._id.equals(kitty2._id); \ No newline at end of file +var kittyEq = kitty1._id.equals(kitty2._id); + +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index a09aefa8e2..6dfd75308a 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -173,7 +173,7 @@ declare module "mongoose" { * @param fn plugin callback * @param opts optional options */ - export function plugin(fn: Function, opts?: any): typeof mongoose; + export function plugin(fn: Function, opts?: T): typeof mongoose; /** Sets mongoose options */ export function set(key: string, value: any): void; @@ -678,7 +678,7 @@ declare module "mongoose" { * Registers a plugin for this schema. * @param plugin callback */ - plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; + plugin(plugin: (schema: Schema, options?: T) => void, opts?: T): this; /** * Defines a post hook for the document diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index 82f92ec9ad..ddf96848b9 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -426,6 +426,29 @@ new mongoose.Schema({ } }); +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + export default function(schema: mongoose.Schema) { schema.pre('init', function(this: mongoose.Document, next: (err?: Error) => void, data: any): void { data.name = 'Hello world'; From a5784023cd62380407d1d3581c3c6650cc684fa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Tr=C3=A9ny?= Date: Sat, 28 Jul 2018 02:20:30 +0200 Subject: [PATCH 029/275] Add missing useTextureView props (#27439) --- types/react-native-video/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 25a58a3e00..d4ba6900f8 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -67,6 +67,7 @@ export interface VideoProperties extends ViewProps { controls?: boolean; currentTime?: number; progressUpdateInterval?: number; + useTextureView?: boolean; onLoadStart?(): void; onLoad?(data: OnLoadData): void; onBuffer?(): void; From bf1d71284db2ac644f252dc07aecb31d53ac6242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment?= Date: Sat, 28 Jul 2018 02:20:40 +0200 Subject: [PATCH 030/275] [auth0-js] Add language value in AuthorizeOptions (#27438) * Add language value to AuthorizeOptions * Update test --- types/auth0-js/auth0-js-tests.ts | 3 ++- types/auth0-js/index.d.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index d05ee2251e..79277e04c9 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -9,7 +9,8 @@ webAuth.authorize({ audience: 'https://mystore.com/api/v2', scope: 'read:order write:order', responseType: 'token', - redirectUri: 'https://example.com/auth/callback' + redirectUri: 'https://example.com/auth/callback', + language: 'en' }); webAuth.parseHash((err, authResult) => { diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index c7224599bd..62047bae71 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -760,6 +760,7 @@ export interface AuthorizeOptions { nonce?: string; scope?: string; audience?: string; + language?: string; } export interface CheckSessionOptions extends AuthorizeOptions { From 6a9c511193f27a46c64de11399f51105cedae07b Mon Sep 17 00:00:00 2001 From: Ivan Kurnosov Date: Sat, 28 Jul 2018 12:21:06 +1200 Subject: [PATCH 031/275] Replace multiple transition* with a single transition in reactstrap (#27434) --- types/reactstrap/lib/Alert.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/types/reactstrap/lib/Alert.d.ts b/types/reactstrap/lib/Alert.d.ts index edfd5303e0..5aa58f862a 100644 --- a/types/reactstrap/lib/Alert.d.ts +++ b/types/reactstrap/lib/Alert.d.ts @@ -1,14 +1,13 @@ import * as React from 'react'; import { CSSModule } from '../index'; +import { FadeProps } from './Fade'; export type UncontrolledProps = React.HTMLAttributes & { className?: string; cssModule?: CSSModule; color?: string; tag?: React.ReactType; - transitionAppearTimeout?: number; - transitionEnterTimeout?: number; - transitionLeaveTimeout?: number; + transition?: FadeProps; } & T; export type UncontrolledAlertProps = UncontrolledProps; From 1a1c9299a65cfe8279ee02069cb784fc5bc4b4c3 Mon Sep 17 00:00:00 2001 From: Louis Larry Date: Sat, 28 Jul 2018 07:21:28 +0700 Subject: [PATCH 032/275] update aws-lambda cloudfront (#27407) --- types/aws-lambda/aws-lambda-tests.ts | 4 ++++ types/aws-lambda/index.d.ts | 3 +++ 2 files changed, 7 insertions(+) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 1c90bb1c72..b0dea303cd 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -585,7 +585,9 @@ const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { { cf: { config: { + distributionDomainName: "d123.cloudfront.net", distributionId: "EDFDVBD6EXAMPLE", + eventType: "viewer-request", requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" }, request: { @@ -654,7 +656,9 @@ const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { { cf: { config: { + distributionDomainName: "d123.cloudfront.net", distributionId: "EDFDVBD6EXAMPLE", + eventType: "viewer-response", requestId: "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" }, request: { diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index aafdf4a0a0..e124f98f75 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -19,6 +19,7 @@ // Chris Redekop // Aneil Mallavarapu // Jeremy Nagel +// Louis Larry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -582,7 +583,9 @@ export interface CloudFrontRequest { export interface CloudFrontEvent { config: { + distributionDomainName: string; distributionId: string; + eventType: 'origin-request' | 'origin-response' | 'viewer-request' | 'viewer-response'; requestId: string; }; } From 2eda9e3a6f28e670348c35c96c1a9513c0c16a39 Mon Sep 17 00:00:00 2001 From: whatasoda Date: Sat, 28 Jul 2018 09:22:03 +0900 Subject: [PATCH 033/275] Added declaration of tweetdeck/valiant (#27385) * Added declaration of tweetdeck/valiant * fixed version notation and miss typo. --- types/valiant/index.d.ts | 51 ++++++++++++++++++++++++++++++++ types/valiant/tsconfig.json | 23 +++++++++++++++ types/valiant/tslint.json | 1 + types/valiant/valiant-tests.ts | 53 ++++++++++++++++++++++++++++++++++ 4 files changed, 128 insertions(+) create mode 100644 types/valiant/index.d.ts create mode 100644 types/valiant/tsconfig.json create mode 100644 types/valiant/tslint.json create mode 100644 types/valiant/valiant-tests.ts diff --git a/types/valiant/index.d.ts b/types/valiant/index.d.ts new file mode 100644 index 0000000000..d63aff72c5 --- /dev/null +++ b/types/valiant/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for valiant 2.0 +// Project: https://github.com/tweetdeck/valiant#readme +// Definitions by: whatasoda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export as namespace Valiant; + +export function createInterval(compareValues?: IntervalConstructor['compareValues']): IntervalConstructor; + +export interface IntervalConstructor { + new (from: Endpoint, to: Endpoint): Interval; + prototype: Interval; + empty: Interval; + whole: Interval; + negInf: Endpoint; + posInf: Endpoint; + negativeInfinity: Endpoint; + positiveInfinity: Endpoint; + adjacentEndpoint(endpoint: Endpoint): Endpoint; + compareEndpoints(a: Endpoint, b: Endpoint): number; + compareValues(a: T, b: T): number; + excEnd(value: T): Endpoint; + exclusiveEndpoint(value: T): Endpoint; + incEnd(value: T): Endpoint; + inclusiveEndpoint(value: T): Endpoint; + singleton(value: T): Interval; +} + +export interface Interval { + constructor: IntervalConstructor; + empty: boolean; + from: Endpoint; + to: Endpoint; + hull(interval: Interval): Interval; + unify(interval: Interval): Interval; + isEmpty(): boolean; + equalTo(interval: Interval): boolean; + contains(value: T): boolean; + isSubsetOf(interval: Interval): boolean; + intersection(interval: Interval): boolean; + contiguousWith(interval: Interval): boolean; + fromComparator(a: Endpoint, b: Endpoint): number; + toComparator(a: Endpoint, b: Endpoint): number; +} + +export interface Endpoint { + finite: boolean; + inclusive: boolean; + value: T; +} diff --git a/types/valiant/tsconfig.json b/types/valiant/tsconfig.json new file mode 100644 index 0000000000..8cac2a107b --- /dev/null +++ b/types/valiant/tsconfig.json @@ -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", + "valiant-tests.ts" + ] +} diff --git a/types/valiant/tslint.json b/types/valiant/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/valiant/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/valiant/valiant-tests.ts b/types/valiant/valiant-tests.ts new file mode 100644 index 0000000000..ff0383cb09 --- /dev/null +++ b/types/valiant/valiant-tests.ts @@ -0,0 +1,53 @@ +import { createInterval } from "valiant"; + +// To make an Interval, you need to create a constructor: +const Interval = createInterval(); + +// By default it will manage integers: +// (0,100] — the numbers 0 to 100, excluding 0 +new Interval( + Interval.exclusiveEndpoint(0), + Interval.inclusiveEndpoint(100) +); + +// You can provide a custom sort function to support a different data type: +const DateInterval = createInterval(function sortDates(a, b) { + return a.getTime() - b.getTime(); +}); + +// [12 hours ago,now] — 12 hours ago until now +new DateInterval( + DateInterval.incEnd( + new Date(Date.now() - (1000 * 60 * 60 * 12)) + ), + DateInterval.incEnd( + new Date(Date.now()) + ) +); + +// You can do calculations with two intervals: +const i = new Interval(Interval.incEnd(1), Interval.incEnd(3)); +const j = new Interval(Interval.incEnd(2), Interval.incEnd(4)); +const k = new Interval(Interval.incEnd(5), Interval.incEnd(6)); + +i.intersection(j); // 2, 3 +i.hull(j); // 1, 4 +i.contiguousWith(j); // true +i.unify(j); // 1, 4 + +i.intersection(k); // Interval.empty +i.hull(k); // 1, 6 +i.contiguousWith(k); // false +i.unify(k); // Interval.empty + +i.equalTo(j); // false +i.contains(2); // true +i.isSubsetOf(j); // false + +// If there is no possible unification, the empty set (Interval.empty) results. +// There are two special intervals: +Interval.empty; // {} +Interval.whole; // -Infinity, Infinity + +// You can also create an interval of value: +Interval.singleton(5); // [5,5] From 46356052281b869c51e3e2d94a194262ab84322e Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Mon, 30 Jul 2018 14:34:34 +0200 Subject: [PATCH 034/275] mapbox.Marker is evented and has the draggable option --- types/mapbox-gl/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 5f64b7470b..f52ac4ed98 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -752,7 +752,7 @@ declare namespace mapboxgl { /** * Marker */ - export class Marker { + export class Marker extends Evented { constructor(options?: mapboxgl.MarkerOptions); constructor(element?: HTMLElement, options?: mapboxgl.MarkerOptions); @@ -784,6 +784,8 @@ declare namespace mapboxgl { anchor?: Anchor; color?: string + + draggable?: boolean; } /** From 9079b29eb4c833ff7dea4fb09b22ea9052b001f7 Mon Sep 17 00:00:00 2001 From: Jason Unger Date: Mon, 30 Jul 2018 11:37:42 -0400 Subject: [PATCH 035/275] Updates for react-toggle V2 types (#27552) * Updates for react-toggle V2 types * Bump minimum TypeScript version * Fix contributor url formatting --- types/react-toggle/v2/index.d.ts | 26 +++++++++++--------- types/react-toggle/v2/react-toggle-tests.tsx | 12 +++++++++ types/react-toggle/v2/tsconfig.json | 5 ++-- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/types/react-toggle/v2/index.d.ts b/types/react-toggle/v2/index.d.ts index 2b0774de2d..e2d2d5f0b2 100644 --- a/types/react-toggle/v2/index.d.ts +++ b/types/react-toggle/v2/index.d.ts @@ -1,20 +1,24 @@ // Type definitions for react-toggle 2.2 // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst +// Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.7 -import { Component, HTMLAttributes, ReactNode } from "react"; +import { ComponentClass, InputHTMLAttributes, ReactNode } from "react"; -export interface ToggleIcons { - checked?: ReactNode; - unchecked?: ReactNode; +declare namespace Toggle { + interface ToggleIcons { + checked?: ReactNode; + unchecked?: ReactNode; + } + + interface ToggleProps extends InputHTMLAttributes { + icons?: boolean | ToggleIcons; + defaultChecked?: boolean; + } } -export interface ToggleProps extends HTMLAttributes { - "aria-labelledby"?: string; - "aria-label"?: string; - icons?: boolean | ToggleIcons; -} +declare const Toggle: ComponentClass; -export default class Toggle extends Component {} +export = Toggle; diff --git a/types/react-toggle/v2/react-toggle-tests.tsx b/types/react-toggle/v2/react-toggle-tests.tsx index f02cf447e4..ac86a3ea7e 100644 --- a/types/react-toggle/v2/react-toggle-tests.tsx +++ b/types/react-toggle/v2/react-toggle-tests.tsx @@ -8,3 +8,15 @@ class Test extends React.Component { ); } } + +class TestControlled extends React.Component<{}, {checked: boolean}> { + state = { + checked: false + }; + + render() { + return ( + this.setState({ checked: e.target.checked })} /> + ); + } +} diff --git a/types/react-toggle/v2/tsconfig.json b/types/react-toggle/v2/tsconfig.json index 996290fe7b..122fd7a4b3 100644 --- a/types/react-toggle/v2/tsconfig.json +++ b/types/react-toggle/v2/tsconfig.json @@ -21,10 +21,11 @@ }, "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "esModuleInterop": true }, "files": [ "index.d.ts", "react-toggle-tests.tsx" ] -} \ No newline at end of file +} From fc1247301cec087154d3f7f6dc5a6e53fb1cd570 Mon Sep 17 00:00:00 2001 From: JFGHT Date: Mon, 30 Jul 2018 17:38:45 +0200 Subject: [PATCH 036/275] Updated Keypair (#27574) * Updated Keypair https://stellar.github.io/js-stellar-sdk/Keypair.html#rawPublicKey * Updated xdr and Transaction https://github.com/stellar/js-stellar-base/blob/master/src/generated/stellar-xdr_generated.js * Fixed signatures signatures is an array of DecoratedSignatures not Signatures --- types/stellar-sdk/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d07309eae5..3f963ab18d 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -825,6 +825,7 @@ export class Transaction { fee: number; source: string; memo: Memo; + signatures: xdr.DecoratedSignature[]; } export class TransactionBuilder { @@ -862,9 +863,11 @@ export class Keypair { publicKey(): string; secret(): string; + rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; sign(data: Buffer): Buffer; + signatureHint(): xdr.SignatureHint; verify(data: Buffer, signature: Buffer): boolean; } @@ -876,4 +879,9 @@ export namespace xdr { class Asset extends XDRStruct { } class Memo extends XDRStruct { } class TransactionEnvelope extends XDRStruct { } + class DecoratedSignature extends XDRStruct { + constructor(keys: { hint: SignatureHint, signature: Signature }) + } + class SignatureHint { } + class Signature { } } From e4902dd43e6c917b992540a2b770828b6a60d930 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Mon, 30 Jul 2018 18:40:28 +0300 Subject: [PATCH 037/275] [web3] Updated `web3.utils.toWei()` Unit list and added default Unit value (#27528) * Updated `web3.utils.toWei()` Unit list and added default Unit value * edit tests for tslint * web3: reordered ether Unit list to match official docs * web3 tests improvement --- types/web3/index.d.ts | 1 + types/web3/utils.d.ts | 22 ++++++++++++++-------- types/web3/web3-tests.ts | 4 ++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 7d3797873e..c93e9c2ebd 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -13,6 +13,7 @@ // Baris Gumustas // André Vitor de Lima Matos // Levin Keller +// Dmitry Radkovskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import BigNumber = require("bn.js"); diff --git a/types/web3/utils.d.ts b/types/web3/utils.d.ts index 61869e327a..659110faa6 100644 --- a/types/web3/utils.d.ts +++ b/types/web3/utils.d.ts @@ -2,21 +2,26 @@ import BigNumber = require("bn.js"); import * as us from "underscore"; type Unit = + | "noether" + | "wei" | "kwei" - | "femtoether" + | "Kwei" | "babbage" + | "femtoether" | "mwei" - | "picoether" + | "Mwei" | "lovelace" - | "qwei" - | "nanoether" + | "picoether" + | "gwei" + | "Gwei" | "shannon" - | "microether" - | "szabo" + | "nanoether" | "nano" + | "szabo" + | "microether" | "micro" - | "milliether" | "finney" + | "milliether" | "milli" | "ether" | "kether" @@ -66,6 +71,7 @@ export default interface Utils { toDecimal(val: any): number; toHex(val: any): string; toUtf8(val: any): string; - toWei(val: string | number | BigNumber, unit: Unit): string | BigNumber; + toWei(val: string | number, unit?: Unit): string; + toWei(val: BigNumber, unit?: Unit): BigNumber; unitMap: any; } diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index 88e05028dd..85e4bc9b0a 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -1,4 +1,5 @@ import Web3 = require("web3"); +import BigNumber = require("bn.js"); const web3 = new Web3(); const myProvider = new web3.providers.HttpProvider("http://localhost:5454"); web3.setProvider(myProvider); @@ -16,3 +17,6 @@ const myContract = new web3.eth.Contract( myContract.options.from = "0x1234567890123456789012345678901234567891"; myContract.options.gasPrice = "20000000000000"; myContract.options.gas = 5000000; + +const weiStr: string = web3.utils.toWei("100", "gwei"); +const weiBn: BigNumber = web3.utils.toWei(web3.utils.toBN("1")); From 34dd46de385b62c3000881914ed78dac2524ddb8 Mon Sep 17 00:00:00 2001 From: bryanjjohnson Date: Mon, 30 Jul 2018 09:46:35 -0600 Subject: [PATCH 038/275] update mapbox-gl typings to 0.47.0 (#27548) --- types/mapbox-gl/index.d.ts | 114 +++++++++++++++++++++++++++++-------- 1 file changed, 89 insertions(+), 25 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 5f64b7470b..d85af4fd5a 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.45.0 +// Type definitions for Mapbox GL JS v0.47.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,17 +26,15 @@ declare namespace mapboxgl { export class Map extends Evented { constructor(options?: MapboxOptions); - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + addControl(control: Control | IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + removeControl(control: Control | IControl): this; - removeControl(control: Control): this; + resize(eventData?: EventData): this; - removeControl(control: IControl): this; + getBounds(): LngLatBounds; - resize(): this; - - getBounds(): mapboxgl.LngLatBounds; + getMaxBounds(): LngLatBounds; setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; @@ -48,6 +46,10 @@ declare namespace mapboxgl { getMaxZoom(): number; + getRenderWorldCopies(): boolean; + + setRenderWorldCopies(renderWorldCopies?: boolean): this; + project(lnglat: LngLatLike): mapboxgl.Point; unproject(point: PointLike): mapboxgl.LngLat; @@ -62,13 +64,13 @@ declare namespace mapboxgl { querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - setStyle(style: mapboxgl.Style | string): this; + setStyle(style: mapboxgl.Style | string, options?: { diff?: boolean, localIdeographFontFamily?: string }): this; getStyle(): mapboxgl.Style; isStyleLoaded(): boolean; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + addSource(id: string, source: VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; isSourceLoaded(id: string): boolean; @@ -76,9 +78,9 @@ declare namespace mapboxgl { removeSource(id: string): this; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + getSource(id: string): VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView | { width: number, height: number, data: Uint8Array | Uint8ClampedArray } | ImageData, options?: { pixelRatio?: number, sdf?: any }): this; hasImage(name: string): boolean; @@ -86,6 +88,8 @@ declare namespace mapboxgl { loadImage(url: string, callback: Function): this; + listImages(): string[]; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -96,7 +100,7 @@ declare namespace mapboxgl { setFilter(layer: string, filter?: any[]): this; - setLayerZoomRange(layerId: string, minzoom?: number, maxzoom?: number): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; getFilter(layer: string): any[]; @@ -108,10 +112,14 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLight(options: mapboxgl.Light, lightOptions?: any): this; getLight(): mapboxgl.Light; + setFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}, state: any): void; + + getFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}): any; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +142,7 @@ declare namespace mapboxgl { setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + panBy(offset: PointLike, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; @@ -162,6 +170,8 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; + cameraForBounds(bounds: LngLatBoundsLike, options?: {padding?: number | PaddingOptions, offset?: PointLike, maxZoom?: number}): CameraOptions; + fitBounds(bounds: LngLatBoundsLike, options?: mapboxgl.FitBoundsOptions, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -204,6 +214,12 @@ declare namespace mapboxgl { /** initial map center */ center?: LngLatLike; + clickTolerance?: number; + + collectResourceTiming?: boolean; + + crossSourceCollisions?: boolean; + /** ID of the container element */ container?: string | Element; @@ -219,6 +235,8 @@ declare namespace mapboxgl { /** If true, the map will track and update the page URL according to map position */ hash?: boolean; + fadeDuration?: number; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ failIfMajorPerformanceCaveat?: boolean; @@ -228,6 +246,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + localIdeographFontFamily?: string; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** If set, the map is constrained to the given bounds. */ @@ -244,6 +264,8 @@ declare namespace mapboxgl { pitch?: number; + pitchWithRotate?: boolean; + refreshExpiredTiles?: boolean; renderWorldCopies?: boolean; @@ -257,6 +279,8 @@ declare namespace mapboxgl { /** If true, the map will automatically resize when the browser window resizes */ trackResize?: boolean; + transformRequest?: Function; + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ touchZoomRotate?: boolean; @@ -500,7 +524,7 @@ declare namespace mapboxgl { } export interface Source { - type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } export type GeoJSONGeometry = GeoJSON.Point | GeoJSON.LineString | GeoJSON.MultiPoint | GeoJSON.Polygon | GeoJSON.MultiLineString | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection; @@ -519,6 +543,12 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + + getClusterExpansionZoom(clusterId: number, callback: (error: any, zoom: number) => void): this; + + getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + + getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; } export interface GeoJSONSourceOptions { @@ -526,6 +556,8 @@ declare namespace mapboxgl { maxzoom?: number; + attribution?: string; + buffer?: number; tolerance?: number; @@ -591,6 +623,10 @@ declare namespace mapboxgl { canvas: string | HTMLCanvasElement; + play(): void; + + pause(): void; + getCanvas(): HTMLCanvasElement; setCoordinates(coordinates: number[][]): this; @@ -608,17 +644,35 @@ declare namespace mapboxgl { type: 'vector'; url?: string; tiles?: string[]; + bounds?: number[]; + scheme?: 'xyz' | 'tms'; minzoom?: number; maxzoom?: number; + attribution?: string; } interface RasterSource extends Source { type: 'raster'; url?: string; tiles?: string[]; + bounds?: number[]; minzoom?: number; maxzoom?: number; tileSize?: number; + scheme?: 'xyz' | 'tms'; + attribution?: string; + } + + interface RasterDemSource extends Source { + type: 'raster-dem'; + url?: string; + tiles?: string[]; + bounds?: number[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + attribution?: string; + encoding?: 'terrarium' | 'mapbox'; } /** @@ -752,7 +806,7 @@ declare namespace mapboxgl { /** * Marker */ - export class Marker { + export class Marker extends Evented { constructor(options?: mapboxgl.MarkerOptions); constructor(element?: HTMLElement, options?: mapboxgl.MarkerOptions); @@ -765,15 +819,21 @@ declare namespace mapboxgl { setLngLat(lngLat: LngLatLike): this; + getElement(): HTMLElement; + setPopup(popup?: Popup): this; getPopup(): Popup; + togglePopup(): this; + getOffset(): PointLike; setOffset(offset: PointLike): this; - togglePopup(): this; + setDraggable(shouldBeDraggable: boolean): this; + + isDraggable(): boolean; } export interface MarkerOptions { @@ -784,6 +844,8 @@ declare namespace mapboxgl { anchor?: Anchor; color?: string + + draggable?: boolean; } /** @@ -831,6 +893,7 @@ declare namespace mapboxgl { export class MapTouchEvent { type: string; + target: Map; map: Map; originalEvent: TouchEvent; point: mapboxgl.Point; @@ -967,7 +1030,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + source?: string | VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; 'source-layer'?: string; @@ -1008,14 +1071,14 @@ declare namespace mapboxgl { } export interface FillPaint { - 'fill-antialias'?: boolean; + 'fill-antialias'?: boolean | Expression; 'fill-opacity'?: number | StyleFunction | Expression; 'fill-opacity-transition'?: Transition; 'fill-color'?: string | StyleFunction | Expression; 'fill-color-transition'?: Transition; 'fill-outline-color'?: string | StyleFunction | Expression; 'fill-outline-color-transition'?: Transition; - 'fill-translate'?: number[] | Expression; + 'fill-translate'?: number[]; 'fill-translate-transition'?: Transition; 'fill-translate-anchor'?: 'map' | 'viewport'; 'fill-pattern'?: string; @@ -1046,7 +1109,7 @@ declare namespace mapboxgl { visibility?: 'visible' | 'none'; 'line-cap'?: 'butt' | 'round' | 'square'; - 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-join'?: 'bevel' | 'round' | 'miter' | Expression; 'line-miter-limit'?: number | Expression; 'line-round-limit'?: number | Expression; } @@ -1077,7 +1140,7 @@ declare namespace mapboxgl { export interface SymbolLayout { visibility?: 'visible' | 'none'; - 'symbol-placement'?: 'point' | 'line'; + 'symbol-placement'?: 'point' | 'line' | 'line-center'; 'symbol-spacing'?: number | Expression; 'symbol-avoid-edges'?: boolean; 'icon-allow-overlap'?: boolean | StyleFunction; @@ -1092,7 +1155,7 @@ declare namespace mapboxgl { 'icon-padding'?: number | Expression; 'icon-keep-upright'?: boolean; 'icon-offset'?: number[] | StyleFunction | Expression; - 'icon-anchor'?: Anchor; + 'icon-anchor'?: Anchor | StyleFunction | Expression; 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; @@ -1103,7 +1166,7 @@ declare namespace mapboxgl { 'text-line-height'?: number | Expression; 'text-letter-spacing'?: number | Expression; 'text-justify'?: 'left' | 'center' | 'right'; - 'text-anchor'?: Anchor; + 'text-anchor'?: Anchor | StyleFunction | Expression; 'text-max-angle'?: number | Expression; 'text-rotate'?: number | StyleFunction | Expression; 'text-padding'?: number | Expression; @@ -1162,6 +1225,7 @@ declare namespace mapboxgl { 'raster-contrast'?: number | Expression; 'raster-contrast-transition'?: Transition; 'raster-fade-duration'?: number | Expression; + 'raster-resample'?: 'linear' | 'nearest'; } export interface CircleLayout { From 3d30be9059159b1a2e357cdb30bdcaada0aa7aa9 Mon Sep 17 00:00:00 2001 From: Ferdy Budhidharma Date: Mon, 30 Jul 2018 10:47:27 -0500 Subject: [PATCH 039/275] fix(find): fix typos in exported functions (#27538) --- types/find/find-tests.ts | 12 ++++++------ types/find/index.d.ts | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/types/find/find-tests.ts b/types/find/find-tests.ts index c6c1cd04f5..3ca401f69a 100644 --- a/types/find/find-tests.ts +++ b/types/find/find-tests.ts @@ -16,9 +16,9 @@ find.file(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); find.fileSync(rootDir); // $ExpectType string[] find.fileSync(stringPattern, rootDir); // $ExpectType string[] find.fileSync(regexPattern, rootDir); // $ExpectType string[] -find.eachFile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void @@ -27,6 +27,6 @@ find.dir(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType find.dirSync(rootDir); // $ExpectType string[] find.dirSync(stringPattern, rootDir); // $ExpectType string[] find.dirSync(regexPattern, rootDir); // $ExpectType string[] -find.eachDir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream diff --git a/types/find/index.d.ts b/types/find/index.d.ts index 61166669db..1ffb2f8aee 100644 --- a/types/find/index.d.ts +++ b/types/find/index.d.ts @@ -45,7 +45,7 @@ export function file(pattern: string | RegExp, root: string, callback: (files: s * @param root The root directory * @param callback A callback that accepts each file separately */ -export function eachFile(root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(root: string, callback: (file: string) => void): FindEachStream; /** * Find all files that match a glob pattern in a given directory asynchronously. @@ -53,7 +53,7 @@ export function eachFile(root: string, callback: (file: string) => void): FindEa * @param root The root directory * @param callback A callback that accepts an array of the found files */ -export function eachFile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; /** * Find all files in a given directory synchronously. @@ -105,7 +105,7 @@ export function dirSync(pattern: string | RegExp, root: string): string[]; * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(root: string, callback: (directory: string) => void): FindEachStream; /** * Find all directories that match a glob pattern in a given directory asynchronously. @@ -113,4 +113,4 @@ export function eachDir(root: string, callback: (directory: string) => void): Fi * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; From f1fc698b58bd5b3d5d91fdcda61a7b137fa1acf3 Mon Sep 17 00:00:00 2001 From: Adrien Samson Date: Mon, 30 Jul 2018 17:49:58 +0200 Subject: [PATCH 040/275] Luxon: Interval.set allows partial object (#27526) * luxon: Interval.set allows partial object * luxon: fix Interval.merge/xor array notation --- types/luxon/index.d.ts | 8 ++++---- types/luxon/luxon-tests.ts | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 17706a9002..e96e389894 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -319,8 +319,8 @@ declare module 'luxon' { } type IntervalObject = { - start: DateTime; - end: DateTime; + start?: DateTime; + end?: DateTime; }; class Interval { @@ -338,8 +338,8 @@ declare module 'luxon' { ): Interval; static fromISO(string: string, options?: DateTimeOptions): Interval; static invalid(reason?: string): Interval; - static merge(intervals: Interval[]): [Interval]; - static xor(intervals: Interval[]): [Interval]; + static merge(intervals: Interval[]): Interval[]; + static xor(intervals: Interval[]): Interval[]; end: DateTime; invalidReason: string; isValid: boolean; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index de0aca9bfd..017f07b0c6 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -78,6 +78,7 @@ const i = Interval.fromDateTimes(now, later); i.length(); i.length('years'); i.contains(DateTime.local(2019)); +i.set({end: DateTime.local(2020)}); i.toISO(); i.toString(); From b9578b93cbae32ea2f1a8ec5cfde0bcf9435cc92 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Mon, 30 Jul 2018 16:50:48 +0100 Subject: [PATCH 041/275] Recompose: fix `...WithConfig` module locations (#27530) --- types/recompose/index.d.ts | 21 +++------------------ types/recompose/recompose-tests.tsx | 9 +++------ 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 0c893486c3..e202e85d44 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -661,39 +661,24 @@ declare module 'recompose/hoistStatics' { // https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstream declare module 'recompose/componentFromStream' { import { componentFromStream } from 'recompose'; + export { componentFromStreamWithConfig } from 'recompose'; export default componentFromStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstreamwithconfig -declare module 'recompose/componentFromStreamWithConfig' { - import { componentFromStreamWithConfig } from 'recompose'; - export default componentFromStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstream declare module 'recompose/mapPropsStream' { import { mapPropsStream } from 'recompose'; + export { mapPropsStreamWithConfig } from 'recompose'; export default mapPropsStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstreamwithconfig -declare module 'recompose/mapPropsStreamWithConfig' { - import { mapPropsStreamWithConfig } from 'recompose'; - export default mapPropsStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandler declare module 'recompose/createEventHandler' { import { createEventHandler } from 'recompose'; + export { createEventHandlerWithConfig } from 'recompose'; export default createEventHandler; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandlerwithconfig -declare module 'recompose/createEventHandlerWithConfig' { - import { createEventHandlerWithConfig } from 'recompose'; - export default createEventHandlerWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#setobservableconfig declare module 'recompose/setObservableConfig' { import { setObservableConfig } from 'recompose'; diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index c30f5fb8f9..b89bd5e2c9 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -62,12 +62,9 @@ import createSinkStandalone from "recompose/createSink"; import componentFromPropStandalone from "recompose/componentFromProp"; import nestStandalone from "recompose/nest"; import hoistStaticsStandalone from "recompose/hoistStatics"; -import componentFromStreamStandalone from "recompose/componentFromStream"; -import componentFromStreamWithConfigStandalone from "recompose/componentFromStreamWithConfig"; -import mapPropsStreamStandalone from "recompose/mapPropsStream"; -import mapPropsStreamWithConfigStandalone from "recompose/mapPropsStreamWithConfig"; -import createEventHandlerStandalone from "recompose/createEventHandler"; -import createEventHandlerWithConfigStandalone from "recompose/createEventHandlerWithConfig"; +import componentFromStreamStandalone, { componentFromStreamWithConfig as componentFromStreamWithConfigStandalone } from "recompose/componentFromStream"; +import mapPropsStreamStandalone, { mapPropsStreamWithConfig as mapPropsStreamWithConfigStandalone } from "recompose/mapPropsStream"; +import createEventHandlerStandalone, { createEventHandlerWithConfig as createEventHandlerWithConfigStandalone } from "recompose/createEventHandler"; import setObservableConfigStandalone from "recompose/setObservableConfig"; function testMapProps() { From 6aacac05323d9378a144b23bd98f6a1a736391b9 Mon Sep 17 00:00:00 2001 From: Simon Werner Date: Tue, 31 Jul 2018 03:52:05 +1200 Subject: [PATCH 042/275] `setDefault()` actually returns a MomentTimezone object (#27518) --- types/moment-timezone/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index fac79f728f..395ab77c82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -53,7 +53,7 @@ declare module "moment" { names(): string[]; guess(ignoreCache?: boolean): string; - setDefault(timezone: string): void; + setDefault(timezone: string): MomentTimezone; } interface Moment { From 7f40149f8d61bee99b79742734484edb0985afcb Mon Sep 17 00:00:00 2001 From: Ali Mavrakis Date: Mon, 30 Jul 2018 12:24:44 -0400 Subject: [PATCH 043/275] Select2: added nextSearchTerm to Select2Options v3 (#27534) --- types/select2/v3/index.d.ts | 1 + types/select2/v3/select2-tests.ts | 3 +++ 2 files changed, 4 insertions(+) diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 21bb2611c7..771d997384 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -75,6 +75,7 @@ interface Select2Options { dropdownCss?: any; dropdownCssClass?: any; escapeMarkup?: (markup: string) => string; + nextSearchTerm?: (selectedObject: object, currentSearchTerm: string) => string; } interface Select2JQueryEventObject extends JQueryEventObject { diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index 3b331cec3b..2d5a400352 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -210,6 +210,9 @@ $("#e17_2").select2({ }); $("#e18,#e18_2").select2(); alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); +$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { + return currentSearchTerm; +}}); $("#e8").select2("val"); $("#e8").select2("val", "CA"); From 439099c83c4c02855591572401bd73ed8761a955 Mon Sep 17 00:00:00 2001 From: James Jensen Date: Mon, 30 Jul 2018 10:25:24 -0600 Subject: [PATCH 044/275] Added the container property to clipboardjs options. (#27514) Per https://github.com/zenorocha/clipboard.js/#advanced-options --- types/clipboard/clipboard-tests.ts | 6 ++++++ types/clipboard/index.d.ts | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/types/clipboard/clipboard-tests.ts b/types/clipboard/clipboard-tests.ts index a2ae8f9354..1a9a170087 100644 --- a/types/clipboard/clipboard-tests.ts +++ b/types/clipboard/clipboard-tests.ts @@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", { action: elem => "copy", target: elem => null }); +const cb6 = new ClipboardJS(".btn", { + action: elem => "copy", + text: trigger => trigger.getAttribute('aria-label'), + target: trigger => trigger.nextElementSibling, + container: document.getElementById('modal') +}); cb1.destroy(); ClipboardJS.isSupported(); diff --git a/types/clipboard/index.d.ts b/types/clipboard/index.d.ts index 2405c0c6f0..ceb15b885b 100644 --- a/types/clipboard/index.d.ts +++ b/types/clipboard/index.d.ts @@ -49,6 +49,14 @@ declare namespace ClipboardJS { * @returns Text to be copied. */ text?(elem: Element): string; + + /** + * For use in Bootstrap Modals or with any + * other library that changes the focus + * you'll want to set the focused element + * as the container value. + */ + container?: Element; } interface Event { From 8b576a265db0be388c521c5143fe7f39ea4b0989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20=28Netux=29=20Rodr=C3=ADguez?= Date: Mon, 30 Jul 2018 13:33:21 -0300 Subject: [PATCH 045/275] simple-oauth2: Update typings to 1.6 and add 2.2 typings (#27458) * simple-oauth2: updated typings to 1.6 and added v2 (2.2) typings * simple-oauth2: swapped version folders --- types/simple-oauth2/index.d.ts | 62 +++--- types/simple-oauth2/simple-oauth2-tests.ts | 146 ++++++-------- types/simple-oauth2/v1/index.d.ts | 133 +++++++++++++ types/simple-oauth2/v1/simple-oauth2-tests.ts | 188 ++++++++++++++++++ types/simple-oauth2/v1/tsconfig.json | 32 +++ types/simple-oauth2/v1/tslint.json | 1 + 6 files changed, 452 insertions(+), 110 deletions(-) create mode 100644 types/simple-oauth2/v1/index.d.ts create mode 100644 types/simple-oauth2/v1/simple-oauth2-tests.ts create mode 100644 types/simple-oauth2/v1/tsconfig.json create mode 100644 types/simple-oauth2/v1/tslint.json diff --git a/types/simple-oauth2/index.d.ts b/types/simple-oauth2/index.d.ts index 21718c0722..19a1ff2698 100644 --- a/types/simple-oauth2/index.d.ts +++ b/types/simple-oauth2/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for simple-oauth2 1.1 +// Type definitions for simple-oauth2 2.2 // Project: https://github.com/lelylan/simple-oauth2 // Definitions by: Michael Müller , // Troy Lamerton +// Martín Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import Bluebird = require("bluebird"); +// TypeScript Version: 2.9 /** Creates a new simple-oauth2 client with the passed configuration */ export function create(options: ModuleOptions): OAuthClient; @@ -33,13 +32,21 @@ export interface ModuleOptions { /** String path to request an authorization code. Default to /oauth/authorize. */ authorizePath?: string }; - /** optional object used to set global options to the internal http library (request-js). */ + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ http?: {}; options?: { - /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ - useBodyAuth?: boolean, - /** Whether or not the Basic Authorization header should be sent at the token request. */ - useBasicAuthorizationHeader?: boolean + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header + */ + authorizationMethod?: "header" | "body" }; } @@ -55,17 +62,19 @@ export interface AccessToken { /** Check if the access token is expired or not */ expired(): boolean; /** Refresh the access token */ - refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; - refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + refresh(params?: {}): Promise; /** Revoke access or refresh token */ - revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; + revoke(tokenType: TokenType): Promise; + /** Revoke both the existing access and refresh tokens */ + revokeAll(): Promise; } export type AuthorizationCode = string; export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ code: AuthorizationCode; + /** A string that represents the callback uri */ redirect_uri: string; - scope?: string | string[]; } export interface PasswordTokenConfig { @@ -88,27 +97,32 @@ export interface OAuthClient { * Redirect the user to the autorization page * @return the absolute authorization url */ - authorizeURL(params?: { - /** A string that represents the registered application URI where the user is redirected after authentication */ - redirect_uri?: string, - /** A string or array of strings that represents the application privileges */ - scope?: string | string[], - /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ - state?: string - }): string, + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, /** Returns the Access Token object */ - getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: AuthorizationTokenConfig): Promise; }; ownerPassword: { /** Returns the Access Token Object */ - getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: PasswordTokenConfig): Promise; }; clientCredentials: { /** Returns the Access Token Object */ - getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: ClientCredentialTokenConfig): Promise; }; accessToken: { diff --git a/types/simple-oauth2/simple-oauth2-tests.ts b/types/simple-oauth2/simple-oauth2-tests.ts index f83a616681..e066ad41c0 100644 --- a/types/simple-oauth2/simple-oauth2-tests.ts +++ b/types/simple-oauth2/simple-oauth2-tests.ts @@ -1,8 +1,11 @@ // off https://github.com/lelylan/simple-oauth2/blob/master/README.md // slightly changed to remove external dependencies +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + // Set the configuration settings -const credentials = { +const credentials: oauth2lib.ModuleOptions = { client: { id: '', secret: '' @@ -12,13 +15,10 @@ const credentials = { } }; -// Initialize the OAuth2 Library -// const oauth2 = require('simple-oauth2').create(credentials); -import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(() => { +(async () => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: 'http://localhost:3000/callback', @@ -36,57 +36,47 @@ const oauth2 = oauth2lib.create(credentials); scope: ['', ''] }; - // Callbacks // Save the access token - oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } + try { + const result = await oauth2.authorizationCode.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } +})(); - const token = oauth2.accessToken.create(result); - }); +// #Password Credentials Flow +(async () => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; - // Promises // Save the access token - oauth2.authorizationCode.getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token Error', error.message); - }); + try { + const result = await oauth2.ownerPassword.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } })(); // #Client Credentials Flow -(() => { +(async () => { const tokenConfig = {}; - // Callbacks // Get the access token object for the client - oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } - - const token = oauth2.accessToken.create(result); - }); - - // Promises - // Get the access token object for the client - oauth2.clientCredentials - .getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token error', error.message); - }); + try { + const result = await oauth2.clientCredentials.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token error', error.message); + } })(); // #Access Token object -(() => { +(async () => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { access_token: '', @@ -95,62 +85,46 @@ const oauth2 = oauth2lib.create(credentials); }; // Create the access token wrapper - let token = oauth2.accessToken.create(tokenObject); + let accessToken = oauth2.accessToken.create(tokenObject); // Check if the token is expired. If expired it is refreshed. - if (token.expired()) { - // Callbacks - token.refresh((error, result) => { - token = result; - }); - - // Promises - token.refresh() - .then((result) => { - token = result; - }); + if (accessToken.expired()) { + try { + accessToken = await accessToken.refresh(); + } catch (error) { + console.log('Error refreshing access token: ', error.message); + } } - // Callbacks - // Revoke only the access token - token.revoke('access_token', (error) => { + // Revoke both access and refresh tokens + try { + // Revoke only the access token + await accessToken.revoke('access_token'); + // Session ended. But the refresh_token is still valid. + // Revoke the refresh token + await accessToken.revoke('refresh_token'); - // Revoke the refresh_token - token.revoke('refresh_token', (error) => { - console.log('token revoked.'); - }); - }); + console.log('Token revoked'); + } catch (error) { + console.log('Error revoking token: ', error.message); + } - // Promises - // Revoke only the access token - token.revoke('access_token') - .then(() => { - // Revoke the refresh token - return token.revoke('refresh_token'); - }) - .then(() => { - console.log('Token revoked'); - }) - .catch((error) => { - console.log('Error revoking token.', error.message); - }); + // or... + + try { + // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked + await accessToken.revokeAll(); + } catch (error) { + console.log('Error revoking token: ', error.message); + } })(); // #Errors // not applicable, as those errors about missing authentication codes are already found by the typescript compiler // (function () { -// // Callbacks -// oauth2.authorizationCode.getToken({}, (error, token) => { -// if (error) { -// return console.log(error.message); -// } -// }); - -// // Promises -// oauth2.authorizationCode -// .getToken({}) +// oauth2.authorizationCode.getToken({}) // .catch((error) => { // console.log(error.message); // }); diff --git a/types/simple-oauth2/v1/index.d.ts b/types/simple-oauth2/v1/index.d.ts new file mode 100644 index 0000000000..30b1a72d98 --- /dev/null +++ b/types/simple-oauth2/v1/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for simple-oauth2 1.6 +// Project: https://github.com/lelylan/simple-oauth2 +// Definitions by: Michael Müller , +// Troy Lamerton +// Martín Rodriguez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import Bluebird = require("bluebird"); + +/** Creates a new simple-oauth2 client with the passed configuration */ +export function create(options: ModuleOptions): OAuthClient; + +export interface ModuleOptions { + client: { + /** Service registered client id. Required. */ + id: string, + /** Service registered client secret. Required. */ + secret: string, + /** Parameter name used to send the client secret. Default to client_secret. */ + secretParamName?: string, + /** Parameter name used to send the client id. Default to client_id. */ + idParamName?: string + }; + auth: { + /** String used to set the host to request the tokens to. Required. */ + tokenHost: string, + /** String path to request an access token. Default to /oauth/token. */ + tokenPath?: string, + /** String path to revoke an access token. Default to /oauth/revoke. */ + revokePath?: string, + /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ + authorizeHost?: string, + /** String path to request an authorization code. Default to /oauth/authorize. */ + authorizePath?: string + }; + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ + http?: {}; + options?: { + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header. + */ + authorizationMethod?: "header" | "body" + }; +} + +export type TokenType = "access_token" | "refresh_token"; + +export interface Token { + [x: string]: any; +} + +export interface AccessToken { + token: Token; + + /** Check if the access token is expired or not */ + expired(): boolean; + /** Refresh the access token */ + refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; + refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + /** Revoke access or refresh token */ + revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; +} + +export type AuthorizationCode = string; +export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ + code: AuthorizationCode; + /** A string that represents the callback uri */ + redirect_uri: string; +} + +export interface PasswordTokenConfig { + /** A string that represents the registered username */ + username: string; + /** A string that represents the registered password. */ + password: string; + /** A string or array of strings that represents the application privileges */ + scope: string | string[]; +} + +export interface ClientCredentialTokenConfig { + /** A string that represents the application privileges */ + scope?: string | string[]; +} + +export interface OAuthClient { + authorizationCode: { + /** + * Redirect the user to the autorization page + * @return the absolute authorization url + */ + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, + + /** Returns the Access Token object */ + getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + ownerPassword: { + /** Returns the Access Token Object */ + getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + clientCredentials: { + /** Returns the Access Token Object */ + getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + accessToken: { + /** Creates an OAuth2.AccessToken instance */ + create(tokenToUse: Token): AccessToken; + }; +} diff --git a/types/simple-oauth2/v1/simple-oauth2-tests.ts b/types/simple-oauth2/v1/simple-oauth2-tests.ts new file mode 100644 index 0000000000..b3a8b2f952 --- /dev/null +++ b/types/simple-oauth2/v1/simple-oauth2-tests.ts @@ -0,0 +1,188 @@ +// off https://github.com/lelylan/simple-oauth2/blob/master/README.md +// slightly changed to remove external dependencies + +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + +// Set the configuration settings +const credentials: oauth2lib.ModuleOptions = { + client: { + id: '', + secret: '' + }, + auth: { + tokenHost: 'https://api.oauth.com' + } +}; + +const oauth2 = oauth2lib.create(credentials); + +// #Authorization Code flow +(() => { + // Authorization oauth2 URI + const authorizationUri = oauth2.authorizationCode.authorizeURL({ + redirect_uri: 'http://localhost:3000/callback', + scope: '', + state: '' + }); + + // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) + // res.redirect(authorizationUri); + + // Get the access token object (the authorization code is given from the previous step). + const tokenConfig = { + code: '', + redirect_uri: 'http://localhost:3000/callback', + scope: ['', ''] + }; + + // Callbacks + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Password Credentials Flow +(() => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; + + // Callbacks + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Client Credentials Flow +(() => { + const tokenConfig = {}; + + // Callbacks + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token error', error.message); + }); +})(); + +// #Access Token object +(() => { + // Sample of a JSON access token (you got it through previous steps) + const tokenObject = { + access_token: '', + refresh_token: '', + expires_in: '7200' + }; + + // Create the access token wrapper + let accessToken = oauth2.accessToken.create(tokenObject); + + // Check if the token is expired. If expired it is refreshed. + if (accessToken.expired()) { + // Callbacks + accessToken.refresh((error, result) => { + accessToken = result; + }); + + // Promises + accessToken.refresh() + .then((result) => { + accessToken = result; + }); + } + + // Callbacks + // Revoke only the access token + accessToken.revoke('access_token', (error) => { + // Session ended. But the refresh_token is still valid. + + // Revoke the refresh_token + accessToken.revoke('refresh_token', (error) => { + console.log('token revoked.'); + }); + }); + + // Promises + // Revoke only the access token + accessToken.revoke('access_token') + .then(() => { + // Revoke the refresh token + return accessToken.revoke('refresh_token'); + }) + .then(() => { + console.log('Token revoked'); + }) + .catch((error) => { + console.log('Error revoking token.', error.message); + }); +})(); + +// #Errors +// not applicable, as those errors about missing authentication codes are already found by the typescript compiler + +// (function () { +// // Callbacks +// oauth2.authorizationCode.getToken({}, (error, token) => { +// if (error) { +// return console.log(error.message); +// } +// }); + +// // Promises +// oauth2.authorizationCode +// .getToken({}) +// .catch((error) => { +// console.log(error.message); +// }); + +// // => { "status": "401", "message": "Unauthorized" } +// })(); diff --git a/types/simple-oauth2/v1/tsconfig.json b/types/simple-oauth2/v1/tsconfig.json new file mode 100644 index 0000000000..f19c003707 --- /dev/null +++ b/types/simple-oauth2/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "simple-oauth2": [ + "simple-oauth2/v1" + ], + "simple-oauth2/*": [ + "simple-oauth2/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-oauth2-tests.ts" + ] +} diff --git a/types/simple-oauth2/v1/tslint.json b/types/simple-oauth2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/simple-oauth2/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3228beff2ff519e85e16c0a9d6933ba8bffe58f9 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Tue, 31 Jul 2018 01:34:35 +0900 Subject: [PATCH 046/275] Update url-regex for strict option. (#27487) * Update url-regex/index.d.ts * Add my name as comment * Increase the version number * Remove patch version --- types/url-regex/index.d.ts | 5 ++++- types/url-regex/url-regex-tests.ts | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/types/url-regex/index.d.ts b/types/url-regex/index.d.ts index ed51c6e34d..58f3793baa 100644 --- a/types/url-regex/index.d.ts +++ b/types/url-regex/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for url-regex 4.0 +// Type definitions for url-regex 4.1 // Project: https://github.com/kevva/url-regex // Definitions by: Daniel Perez Alvarez +// sosukesuzuki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Regular expression for matching URLs. */ declare function urlRegex(options?: { /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ exact?: boolean; + /** Force URLs to start with a valid protocol or www. If set to false it'll match the TLD against a list of valid TLDs(https://github.com/stephenmathieson/node-tlds). */ + strict?: boolean; }): RegExp; export = urlRegex; diff --git a/types/url-regex/url-regex-tests.ts b/types/url-regex/url-regex-tests.ts index 2a2db45a28..de62d9a796 100644 --- a/types/url-regex/url-regex-tests.ts +++ b/types/url-regex/url-regex-tests.ts @@ -8,4 +8,6 @@ urlRegex({exact: true}).test('https://github.com foo bar'); urlRegex({exact: true}).test('https://github.com'); +urlRegex({exact: true, strict: false}).test('github.com'); + 'foo https://github.com bar //google.com'.match(urlRegex()); From 451ab05774ad35e2e4eee6666eba8b9999a01e21 Mon Sep 17 00:00:00 2001 From: Igor Babkin Date: Mon, 30 Jul 2018 19:35:06 +0300 Subject: [PATCH 047/275] Remove recalc function (it's private) and add getCentroid() (#27488) --- types/sat/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/sat/index.d.ts b/types/sat/index.d.ts index 538228049c..901c0814f2 100644 --- a/types/sat/index.d.ts +++ b/types/sat/index.d.ts @@ -59,10 +59,10 @@ declare namespace SAT { setPoints(points: Vector[]): Polygon; setAngle(angle: number): Polygon; setOffset(offset: Vector): Polygon; - recalc(): Polygon; rotate(angle: number): Polygon; translate(x: number, y: number): Polygon; getAABB(): Polygon; + getCentroid(): Vector; } export class Box { From 0e67e6c7827c13658790b1de087bbe7514e787b0 Mon Sep 17 00:00:00 2001 From: Art Date: Mon, 30 Jul 2018 17:35:46 +0100 Subject: [PATCH 048/275] Add node-zopfli-es types (#27634) * Add node-zopfli-es types * Set typescript version * Replace index.d.ts with actual type definition instead of an export * Update index.d.ts --- types/node-zopfli-es/index.d.ts | 69 ++++++++++++++++++++ types/node-zopfli-es/node-zopfli-es-tests.ts | 51 +++++++++++++++ types/node-zopfli-es/tsconfig.json | 23 +++++++ types/node-zopfli-es/tslint.json | 1 + 4 files changed, 144 insertions(+) create mode 100644 types/node-zopfli-es/index.d.ts create mode 100644 types/node-zopfli-es/node-zopfli-es-tests.ts create mode 100644 types/node-zopfli-es/tsconfig.json create mode 100644 types/node-zopfli-es/tslint.json diff --git a/types/node-zopfli-es/index.d.ts b/types/node-zopfli-es/index.d.ts new file mode 100644 index 0000000000..e015655d8b --- /dev/null +++ b/types/node-zopfli-es/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for node-zopfli-es 0.0 +// Project: https://github.com/jaeh/node-zopfli-es +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Transform } from 'stream'; + +declare class Zopfli extends Transform { + constructor(format?: Zopfli.Format, options?: Zopfli.Options); + + static createGzip(options?: Zopfli.Options): Zopfli; + static createDeflate(options?: Zopfli.Options): Zopfli; + static createZlib(options?: Zopfli.Options): Zopfli; + + static gzipSync(options?: Zopfli.Options): Buffer; + static deflateSync(options?: Zopfli.Options): Buffer; + static zlibSync(options?: Zopfli.Options): Buffer; + + static deflate(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, options?: Zopfli.Options): Promise; + + static gzip(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, options?: Zopfli.Options): Promise; + + static zlib(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, options?: Zopfli.Options): Promise; + + static compress(input: Buffer, format: Zopfli.Format, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, options?: Zopfli.Options): Promise; +} + +declare namespace Zopfli { + type Format = 'deflate' | 'gzip' | 'zlib'; + + interface Options { + verbose?: boolean; + verbose_more?: boolean; + /** + * Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. + * Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. + */ + numiterations?: number; + /** + * If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. + * Block splitting gives better compression. + */ + blocksplitting?: boolean; + /** + * If true, chooses the optimal block split points only after doing the iterative LZ77 compression. + * If false, chooses the block split points first, then does iterative LZ77 on each individual block. + * Depending on the file, either first or last gives the best compression. + */ + blocksplittinglast?: boolean; + /** + * Maximum amount of blocks to split into (0 for unlimited, + * but this can give extreme results that hurt compression on some files). + */ + blocksplittingmax?: number; + } +} + +export = Zopfli; diff --git a/types/node-zopfli-es/node-zopfli-es-tests.ts b/types/node-zopfli-es/node-zopfli-es-tests.ts new file mode 100644 index 0000000000..3f3294cf3f --- /dev/null +++ b/types/node-zopfli-es/node-zopfli-es-tests.ts @@ -0,0 +1,51 @@ +import * as Zopfli from 'node-zopfli-es'; +import * as fs from 'fs'; + +const opts: Zopfli.Options = { + verbose: true, + numiterations: 1 +}; +let input: Buffer = Buffer.from('foo'); +const read = fs.createReadStream('foo'); +const write = fs.createWriteStream('foo'); + +function cb(e: Error, b: Buffer): void {} +function then(b: Buffer): void {} + +Zopfli.zlib(input, cb); +Zopfli.zlib(input, opts, cb); +Zopfli.zlib(input, opts).then(then); +Zopfli.zlib(input).then(then); + +Zopfli.gzip(input, cb); +Zopfli.gzip(input, opts, cb); +Zopfli.gzip(input, opts).then(then); +Zopfli.gzip(input).then(then); + +Zopfli.deflate(input, cb); +Zopfli.deflate(input, opts, cb); +Zopfli.deflate(input, opts).then(then); +Zopfli.deflate(input).then(then); + +Zopfli.compress(input, 'zlib', cb); +Zopfli.compress(input, 'zlib', opts, cb); +Zopfli.compress(input, 'zlib', opts).then(then); +Zopfli.compress(input, 'zlib').then(then); + +input = Zopfli.gzipSync(); +input = Zopfli.gzipSync(opts); + +input = Zopfli.deflateSync(); +input = Zopfli.deflateSync(opts); + +input = Zopfli.zlibSync(); +input = Zopfli.zlibSync(opts); + +read.pipe(Zopfli.createGzip()).pipe(write); +read.pipe(Zopfli.createGzip(opts)).pipe(write); + +read.pipe(Zopfli.createDeflate()).pipe(write); +read.pipe(Zopfli.createDeflate(opts)).pipe(write); + +read.pipe(Zopfli.createZlib()).pipe(write); +read.pipe(Zopfli.createZlib(opts)).pipe(write); diff --git a/types/node-zopfli-es/tsconfig.json b/types/node-zopfli-es/tsconfig.json new file mode 100644 index 0000000000..bbd6de30e8 --- /dev/null +++ b/types/node-zopfli-es/tsconfig.json @@ -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", + "node-zopfli-es-tests.ts" + ] +} diff --git a/types/node-zopfli-es/tslint.json b/types/node-zopfli-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-zopfli-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From aa115293b8dd2540fd3a4b6871b68375840c007a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 30 Jul 2018 11:00:29 -0700 Subject: [PATCH 049/275] Make `Props` default to `never` in 'moonjs'. (#27667) * Make `Props` default to `never` in 'moonjs'. * Update test for missing props. --- types/moonjs/index.d.ts | 4 ++-- types/moonjs/moonjs-tests.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/moonjs/index.d.ts b/types/moonjs/index.d.ts index 13dcbbe04e..c003f7ad58 100644 --- a/types/moonjs/index.d.ts +++ b/types/moonjs/index.d.ts @@ -22,11 +22,11 @@ declare namespace Moon { } interface MoonConstructor { - new (options?: ConstructorOptions): Instance>; + new (options?: ConstructorOptions): Instance>; } interface MoonStatic extends MoonConstructor { - component(name: string, options: ComponentOptions): MoonConstructor; + component(name: string, options: ComponentOptions): MoonConstructor; config: MoonConfig; use(plugin: object): void; compile(template: string): void; diff --git a/types/moonjs/moonjs-tests.ts b/types/moonjs/moonjs-tests.ts index aa6527ea82..34d1d8d359 100644 --- a/types/moonjs/moonjs-tests.ts +++ b/types/moonjs/moonjs-tests.ts @@ -17,6 +17,7 @@ const count = app.get("count"); count; // $ExpectType number app.get("increment")(); // $ExpectType void app.callMethod("increment"); // $ExpectType any +app.get("blahblahblah"); // $ExpectError app.destroy(); From 5c0fd82860b50651004c9e632e4a080e59edafba Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 30 Jul 2018 20:02:05 +0200 Subject: [PATCH 050/275] stylelint: update to v9.4 (#27659) * stylelint: update to v9.4 * styleline: add `compact` to `formatters` --- types/stylelint/index.d.ts | 5 +- types/stylelint/tslint.json | 78 +-------------------------- types/stylelint/v7/index.d.ts | 51 ++++++++++++++++++ types/stylelint/v7/stylelint-tests.ts | 24 +++++++++ types/stylelint/v7/tsconfig.json | 29 ++++++++++ types/stylelint/v7/tslint.json | 3 ++ 6 files changed, 111 insertions(+), 79 deletions(-) create mode 100644 types/stylelint/v7/index.d.ts create mode 100644 types/stylelint/v7/stylelint-tests.ts create mode 100644 types/stylelint/v7/tsconfig.json create mode 100644 types/stylelint/v7/tslint.json diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 67316843a9..2068aff709 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for stylelint 7.11 +// Type definitions for stylelint 9.4 // Project: https://github.com/stylelint/stylelint // Definitions by: Alan Agius // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type FormatterType = "json" | "string" | "verbose"; +export type FormatterType = "json" | "string" | "verbose" | "compact"; export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; @@ -45,6 +45,7 @@ export interface LintResult { export namespace formatters { function json(results: LintResult[]): string; function string(results: LintResult[]): string; + function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; } diff --git a/types/stylelint/tslint.json b/types/stylelint/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/stylelint/tslint.json +++ b/types/stylelint/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/stylelint/v7/index.d.ts b/types/stylelint/v7/index.d.ts new file mode 100644 index 0000000000..67316843a9 --- /dev/null +++ b/types/stylelint/v7/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for stylelint 7.11 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FormatterType = "json" | "string" | "verbose"; + +export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + cache?: boolean; + cacheLocation?: string; + files?: string | string[]; + fix?: boolean; + formatter?: FormatterType; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: SyntaxType; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/types/stylelint/v7/stylelint-tests.ts b/types/stylelint/v7/stylelint-tests.ts new file mode 100644 index 0000000000..785eb2e425 --- /dev/null +++ b/types/stylelint/v7/stylelint-tests.ts @@ -0,0 +1,24 @@ +import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + cache: true, + cacheLocation: "./stylelint.cache.json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); + +const formatter: FormatterType = "json"; + +const syntax: SyntaxType = "scss"; diff --git a/types/stylelint/v7/tsconfig.json b/types/stylelint/v7/tsconfig.json new file mode 100644 index 0000000000..b6f6796252 --- /dev/null +++ b/types/stylelint/v7/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stylelint": [ + "stylelint/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/types/stylelint/v7/tslint.json b/types/stylelint/v7/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/stylelint/v7/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ba36179b1921bd3ee3682e2af3c121f0f16b5f46 Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 11:02:15 -0700 Subject: [PATCH 051/275] Allow non-factories to be registered with .register (#27661) --- types/ember/index.d.ts | 4 ++-- types/ember/test/application-instance.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 3583889a74..babca01879 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -328,11 +328,11 @@ declare module 'ember' { */ resolveRegistration(fullName: string): Function; /** - * Registers a factory that can be used for dependency injection (with + * Registers a factory or value that can be used for dependency injection (with * `inject`) or for service lookup. Each factory is registered with * a full name including two parts: `type:name`. */ - register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any; + register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any; /** * Unregister a factory. */ diff --git a/types/ember/test/application-instance.ts b/types/ember/test/application-instance.ts index 9881e4815a..9ae22e5f26 100644 --- a/types/ember/test/application-instance.ts +++ b/types/ember/test/application-instance.ts @@ -1,4 +1,5 @@ import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; const appInstance = ApplicationInstance.create(); appInstance.register('some:injection', class Foo {}); @@ -11,6 +12,8 @@ appInstance.register('some:injection', class Foo {}, { instantiate: false, }); +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + appInstance.register('some:injection', class Foo {}, { singleton: false, instantiate: true, From ab5b7b9449657620af7faab06e1caff3540eb1a7 Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Mon, 30 Jul 2018 20:03:01 +0200 Subject: [PATCH 052/275] [react-big-calendar] add definitions for header component (#27655) --- types/react-big-calendar/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index b73ffcc0d9..9275511fc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -86,11 +86,23 @@ export interface Format { eventTimeRangeEndFormat?: string; } +export interface HeaderProps { + culture: BigCalendarProps['culture']; + date: Date; + format: string; + label: string; + localizer: object; +} + export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + /** + * component used as a header for each column in the TimeGridHeader + */ + header?: React.ComponentType; toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; From 0dcfb2b4836606bf3bdace6ce688a8883cb0af7d Mon Sep 17 00:00:00 2001 From: Matthew Gabeler-Lee Date: Mon, 30 Jul 2018 14:04:48 -0400 Subject: [PATCH 053/275] pino accepts NodeJS.WritableStream streams too (#27635) --- types/pino/index.d.ts | 4 ++-- types/pino/pino-tests.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 0f98e0a622..27d0f51fc6 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -19,7 +19,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; /** * @param [options]: an options object @@ -27,7 +27,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; declare namespace P { /** diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 6d226a1d92..6959a6cd97 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -93,3 +93,6 @@ log.level = 'info'; pino.levels.values.error === 50; pino.levels.labels[50] === 'error'; + +const logstderr: pino.Logger = pino(process.stderr); +logstderr.error('on stderr instead of stdout'); From e0bc7a1f62b32963a5e29e514aee39d949a595ad Mon Sep 17 00:00:00 2001 From: lsg-braymon <40968250+lsg-braymon@users.noreply.github.com> Date: Tue, 31 Jul 2018 06:05:40 +1200 Subject: [PATCH 054/275] [@types/ember] Add `currentRouteName` to Ember RouterService (#27590) * Add currentRouteName property * Fix placement of RouterService property. Add test. --- types/ember/index.d.ts | 48 +++++++++++++++++++++++++++++++++++++- types/ember/test/router.ts | 7 ++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index babca01879..93babaa0a7 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -3372,7 +3372,48 @@ declare module 'ember' { /** * The Router service is the public API that provides component/view layer access to the router. */ - class RouterService extends Ember.Service { + export class RouterService extends Ember.Service { + // + /** + Name of the current route. + This property represent the logical name of the route, + which is comma separated. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `index` when you visit `/` + * `about` when you visit `/about` + * `blog.index` when you visit `/blog` + * `blog.post` when you visit `/blog/some-post-id` + */ + readonly currentRouteName: string; + // + /** + Current URL for the application. + This property represent the URL path for this route. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `/` when you visit `/` + * `/about` when you visit `/about` + * `/blog` when you visit `/blog` + * `/blog/some-post-id` when you visit `/blog/some-post-id` + */ + readonly currentURL: string; // /** * Determines whether a route is active. @@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' { export default class EmberRouter extends Ember.Router { } } +declare module '@ember/routing/router-service' { + import { RouterService } from 'ember'; + export default class extends RouterService { } +} + declare module '@ember/runloop' { import Ember from 'ember'; export const begin: typeof Ember.run.begin; diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index ff5f4c554f..760e9ed5bc 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { assertType } from './lib/assert'; const AppRouter = Ember.Router.extend({ }); @@ -25,6 +26,12 @@ AppRouter.map(function() { const RouterServiceConsumer = Ember.Service.extend({ router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, transitionWithoutModel() { Ember.get(this, 'router') .transitionTo('some-route'); From 1922994873e2af17a2937453aa7ef2cae65aa737 Mon Sep 17 00:00:00 2001 From: process-execution Date: Tue, 31 Jul 2018 02:06:00 +0800 Subject: [PATCH 055/275] Fix Primitive constructor (#27668) Made shadows property optional in Primitive constructor config object. --- types/cesium/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index f2bb11479c..6c34023eae 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -3593,7 +3593,7 @@ declare namespace Cesium { cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; - shadows: ShadowMode + shadows?: ShadowMode }); destroy(): void; getGeometryInstanceAttributes(id: any): any; From 15ec8386fcceabe6df0bd421463f5ac5c88f1751 Mon Sep 17 00:00:00 2001 From: Paul-Louis HERY Date: Mon, 30 Jul 2018 20:07:49 +0200 Subject: [PATCH 056/275] add params include_user_entities and stringify_ids (#27678) --- types/twit/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index 9918d58470..ce8484bbe1 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -4,6 +4,7 @@ // sapphiredev // abraham // siwalik +// plhery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -271,6 +272,8 @@ declare module 'twit' { include_rts?: boolean, skip_status?: boolean, url?: string, + include_user_entities?: boolean, + stringify_ids?: boolean, } export interface PromiseResponse { data: Response, From d0bd4443df62dc038f61624fb2a2c7f6951b1441 Mon Sep 17 00:00:00 2001 From: Rinze Date: Mon, 30 Jul 2018 20:07:58 +0200 Subject: [PATCH 057/275] Updated sanitize-html type definitions for version 1.18.2 (#27676) * Updated sanitize-html type definitions for version 1.18.2 * Augemented sanitize-html test file --- types/sanitize-html/index.d.ts | 6 +++++- types/sanitize-html/sanitize-html-tests.ts | 11 ++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index bdd70f956a..2e7527e3fc 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for sanitize-html 1.14.1 +// Type definitions for sanitize-html 1.18.2 // Project: https://github.com/punkave/sanitize-html // Definitions by: Rogier Schouten // Afshin Darian // BehindTheMath +// Rinze de Laat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = sanitize; @@ -38,9 +39,12 @@ declare namespace sanitize { interface IOptions { allowedAttributes?: { [index: string]: string[] } | boolean; + allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }; allowedClasses?: { [index: string]: string[] } | boolean; + allowedIframeHostnames?: string[]; allowedSchemes?: string[] | boolean; allowedSchemesByTag?: { [index: string]: string[] } | boolean; + allowedSchemesAppliedToAttributes?: string[]; allowProtocolRelative?: boolean; allowedTags?: string[] | boolean; exclusiveFilter?: (frame: IFrame) => boolean; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index cc43d64fcb..b02a5a6653 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -4,8 +4,17 @@ let options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), - 'img': ['src', 'height', 'width', 'alt'] + 'img': ['src', 'height', 'width', 'alt', 'style'] }, + allowedStyles: { + '*': { + color: [/^red$/], + background: [/^green$/], + 'background-color': [/^#0000FF$/] + } + }, + allowedIframeHostnames: ['www.youtube.com'], + allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], transformTags: { 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }), 'img': (tagName: string, attribs: sanitize.Attributes) => { From 43de02ea1d87534427c0b1ae95e13a26d11e4e42 Mon Sep 17 00:00:00 2001 From: error Date: Mon, 30 Jul 2018 13:08:07 -0500 Subject: [PATCH 058/275] add bson/Int32 to exports (#27662) --- types/mongodb/v2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/v2/index.d.ts b/types/mongodb/v2/index.d.ts index 4c26149d81..a7d45ac2d0 100644 --- a/types/mongodb/v2/index.d.ts +++ b/types/mongodb/v2/index.d.ts @@ -22,7 +22,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; +export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef, Int32 } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { From 3e8a84c2818c917619f313846358d9c2ebd977d2 Mon Sep 17 00:00:00 2001 From: slyrz Date: Mon, 30 Jul 2018 20:10:22 +0200 Subject: [PATCH 059/275] Update API to version 1.6 (#27658) --- types/puppeteer/index.d.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 4859b86fc1..a5e85f802e 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.5 +// Type definitions for puppeteer 1.6 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -727,6 +727,10 @@ export interface ElementHandle extends JSHandle, Ev * If the element is detached from DOM, the method throws an error. */ hover(): Promise; + /** + * Resolves to true if the element is visible in the current viewport. + */ + isIntersectingViewport(): Promise; /** * Focuses the element, and then uses keyboard.down and keyboard.up. * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. @@ -860,6 +864,8 @@ export type ErrorCode = | "aborted" | "accessdenied" | "addressunreachable" + | "blockedbyclient" + | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" @@ -1107,16 +1113,6 @@ export interface FrameBase extends Evalable { ...args: any[] ): Promise; - waitForRequest( - urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } - ): Promise; - - waitForResponse( - urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } - ): Promise; - waitForSelector( selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } @@ -1447,6 +1443,16 @@ export interface Page extends EventEmitter, FrameBase { */ waitForNavigation(options?: NavigationOptions): Promise; + waitForRequest( + urlOrPredicate: string | ((req: Request) => boolean), + options?: { timeout?: number } + ): Promise; + + waitForResponse( + urlOrPredicate: string | ((res: Response) => boolean), + options?: { timeout?: number } + ): Promise; + /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } @@ -1705,6 +1711,8 @@ export interface Coverage { export interface StartCoverageOptions { /** Whether to reset coverage on every navigation. Defaults to `true`. */ resetOnNavigation?: boolean; + /** Whether anonymous scripts generated by the page should be reported. Defaults to `false`. */ + reportAnonymousScripts?: boolean; } export interface CoverageEntry { From 9e7f1e9d6fb81e236403242704016259baa7e82b Mon Sep 17 00:00:00 2001 From: Vinay Raikar Date: Mon, 30 Jul 2018 23:41:25 +0530 Subject: [PATCH 060/275] Correct the promise resolution type for jobs method (#27649) --- types/agenda/agenda-tests.ts | 3 +++ types/agenda/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index e4de026c0e..2c011efaf7 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda"; await job.save(); const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }); + jobs.forEach((job) => { + job.save(); + }); let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' }); diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d728a76032..be07b84aaf 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter { * Find all Jobs matching `query` and pass same back in cb(). * @param query */ - jobs(query: any): Promise; + jobs(query: any): Promise[]>; /** * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want From 16b85f0e2f623fd107ccf55edbac1e0558b97e48 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Mon, 30 Jul 2018 20:19:01 +0200 Subject: [PATCH 061/275] [@types/gulp-imagemin] Add type definitions (#27692) * Add koa-router's Router to koa's Context * [@types/gulp-imagemin] Add type definitions --- types/gulp-imagemin/gulp-imagemin-tests.ts | 20 ++++++++++++++++ types/gulp-imagemin/index.d.ts | 27 ++++++++++++++++++++++ types/gulp-imagemin/tsconfig.json | 23 ++++++++++++++++++ types/gulp-imagemin/tslint.json | 1 + 4 files changed, 71 insertions(+) create mode 100644 types/gulp-imagemin/gulp-imagemin-tests.ts create mode 100644 types/gulp-imagemin/index.d.ts create mode 100644 types/gulp-imagemin/tsconfig.json create mode 100644 types/gulp-imagemin/tslint.json diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts new file mode 100644 index 0000000000..7fc1d86311 --- /dev/null +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -0,0 +1,20 @@ +import * as GulpImagemin from 'gulp-imagemin'; + +GulpImagemin(); + +GulpImagemin([ + GulpImagemin.gifsicle({ interlaced: true }), + GulpImagemin.jpegtran({ progressive: true }), + GulpImagemin.optipng({ optimizationLevel: 5 }), + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }, { cleanupIDs: false }] + }) +]); + +GulpImagemin({ verbose: true }); + +GulpImagemin([ + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }] + }) +], { verbose: true }); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts new file mode 100644 index 0000000000..42c1ef8d5c --- /dev/null +++ b/types/gulp-imagemin/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-imagemin 4.1 +// Project: https://github.com/sindresorhus/gulp-imagemin#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; +declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; + +declare namespace imagemin { + interface Options { + verbose?: boolean; + } + + type Plugin = (input: any) => Promise; + type PluginFactory = (options?: any) => Plugin; + + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; +} + +export = imagemin; diff --git a/types/gulp-imagemin/tsconfig.json b/types/gulp-imagemin/tsconfig.json new file mode 100644 index 0000000000..1b35a74382 --- /dev/null +++ b/types/gulp-imagemin/tsconfig.json @@ -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", + "gulp-imagemin-tests.ts" + ] +} diff --git a/types/gulp-imagemin/tslint.json b/types/gulp-imagemin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-imagemin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 057310a95d998b7d238ffe73c0cb082c782dac5c Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Tue, 31 Jul 2018 02:20:51 +0800 Subject: [PATCH 062/275] addint definitions for @tinajs/tina-redux (#27231) --- .github/CODEOWNERS | 1 + types/tinajs__tina-redux/index.d.ts | 23 +++++++++ types/tinajs__tina-redux/package.json | 6 +++ .../tinajs__tina-redux-tests.ts | 51 +++++++++++++++++++ types/tinajs__tina-redux/tsconfig.json | 21 ++++++++ types/tinajs__tina-redux/tslint.json | 3 ++ 6 files changed, 105 insertions(+) create mode 100644 types/tinajs__tina-redux/index.d.ts create mode 100644 types/tinajs__tina-redux/package.json create mode 100644 types/tinajs__tina-redux/tinajs__tina-redux-tests.ts create mode 100644 types/tinajs__tina-redux/tsconfig.json create mode 100644 types/tinajs__tina-redux/tslint.json diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0380b02e1e..8c7f823a07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4293,6 +4293,7 @@ /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici /types/tinajs__tina/ @Jimexist +/types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh diff --git a/types/tinajs__tina-redux/index.d.ts b/types/tinajs__tina-redux/index.d.ts new file mode 100644 index 0000000000..e48665e696 --- /dev/null +++ b/types/tinajs__tina-redux/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for @tinajs/tina-redux 1.4 +// Project: https://github.com/tinajs/tina-redux +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tinajs__tina-redux +// TypeScript Version: 2.3 + +import { Store, Dispatch } from "redux"; + +type MapStateToProps = (state: any) => any; +type mapDispatchToProps = (dispatch: Dispatch) => any; + +interface HOC { + onLoad: () => void; + onUnload: () => void; + methods: object; +} + +declare class TinaRedux { + constructor(reduxStore: Store); + connect(mapState?: MapStateToProps, mapDispatch?: mapDispatchToProps): HOC; +} + +export = TinaRedux; diff --git a/types/tinajs__tina-redux/package.json b/types/tinajs__tina-redux/package.json new file mode 100644 index 0000000000..7f5b19d45b --- /dev/null +++ b/types/tinajs__tina-redux/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.0" + } +} diff --git a/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts new file mode 100644 index 0000000000..d4a7c2225f --- /dev/null +++ b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts @@ -0,0 +1,51 @@ +import { createStore, combineReducers, Action } from "redux"; +import TinaRedux from "@tinajs/tina-redux"; + +interface Todo { + id: number; + text: string; + completed: boolean; +} + +interface TodoAction extends Action, Todo {} + +const intialState: Todo[] = [ + { id: 1, text: "Star Tina.js", completed: false }, + { id: 2, text: "Star Tina-Redux", completed: true }, + { id: 3, text: "Build a mini-program with Tina.js", completed: false }, + { id: 4, text: "Add to Showcase of Tina.js", completed: false } +]; + +const todos = (state = intialState, action: TodoAction) => { + switch (action.type) { + case "ADD_TODO": + return [ + ...state, + { + id: action.id, + text: action.text, + completed: false + } + ]; + case "TOGGLE_TODO": + return state.map( + todo => + todo.id === action.id + ? { ...todo, completed: !todo.completed } + : todo + ); + case "CLEAR_COMPLETED_TODOS": + return state.filter(todo => !todo.completed); + default: + return state; + } +}; + +const todoApp = combineReducers({ + todos +}); + +const reduxStore = createStore(todoApp); +const store = new TinaRedux(reduxStore); + +export default store; diff --git a/types/tinajs__tina-redux/tsconfig.json b/types/tinajs__tina-redux/tsconfig.json new file mode 100644 index 0000000000..c3b4905b15 --- /dev/null +++ b/types/tinajs__tina-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@tinajs/tina": ["tinajs__tina"], + "@tinajs/tina-redux": ["tinajs__tina-redux"] + } + }, + "files": ["index.d.ts", "tinajs__tina-redux-tests.ts"] +} diff --git a/types/tinajs__tina-redux/tslint.json b/types/tinajs__tina-redux/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinajs__tina-redux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 46ef7e1ffc4cdd0f7b96f4a72a0290592c8738f8 Mon Sep 17 00:00:00 2001 From: Endurance Idehen <40364466+ls-endurance@users.noreply.github.com> Date: Mon, 30 Jul 2018 13:22:32 -0500 Subject: [PATCH 063/275] @types/React-Select: Add ability for arrow renderer prop to be set to null (#27342) * Add ability for arrow renderer prop to be set to null In this issue, arrow rendering would keep the functionality even if no arrow was being rendered. The PR below fixed the issue. https://github.com/JedWatson/react-select/pull/1761 In this PR, the guys added the ability to set the arrowRenderer option to null, which disables all arrow related operation. The types repo needs to reflect this change. Thanks! * Add my name to list --- types/react-select/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index bde3c3c6a0..b3d5490d9f 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -13,6 +13,7 @@ // David Schkalee // Arthur Udalov // Sebastian Silbermann +// Endurance Idehen // Guillaume Chartier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -241,7 +242,7 @@ export interface ReactSelectProps extends React.Props Date: Tue, 31 Jul 2018 01:24:58 +0700 Subject: [PATCH 064/275] [slack-mock] New typings for slack-mock (#27440) * Add types for slack-mock * Add library specific types * Fix lint * Reorganize imports --- types/slack-mock/index.d.ts | 200 +++++++++++++++++++++++++++ types/slack-mock/slack-mock-tests.ts | 103 ++++++++++++++ types/slack-mock/tsconfig.json | 23 +++ types/slack-mock/tslint.json | 3 + 4 files changed, 329 insertions(+) create mode 100644 types/slack-mock/index.d.ts create mode 100644 types/slack-mock/slack-mock-tests.ts create mode 100644 types/slack-mock/tsconfig.json create mode 100644 types/slack-mock/tslint.json diff --git a/types/slack-mock/index.d.ts b/types/slack-mock/index.d.ts new file mode 100644 index 0000000000..2289e554b4 --- /dev/null +++ b/types/slack-mock/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for slack-mock 1.1 +// Project: https://github.com/Skellington-Closet/slack-mock +// Definitions by: Kris Kalavantavanich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { IncomingHttpHeaders } from "http"; +import * as nock from "nock"; +import { Url } from "url"; +import * as WebSocket from "ws"; + +export = SlackMock; + +declare function SlackMock(config?: SlackMock.ConfigOptions): SlackMock.Instance; + +declare namespace SlackMock { + let instance: Instance; + + interface Instance { + events: Events; + incomingWebhooks: IncomingWebhooks; + interactiveButtons: InteractiveButtons; + outgoingWebhooks: OutgoingWebhooks; + rtm: Rtm; + slashCommands: SlashCommands; + web: Web; + + reset: () => void; + } + + interface ConfigOptions { + rtmPort?: number; + logLevel?: string; + } + + // Events + + type EventUrl = string | Url; + type EventHttpHeaders = IncomingHttpHeaders; + + interface Events { + send: (targetUrl: EventUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface EventCall { + url: EventUrl; + params: T; + headers: EventHttpHeaders; + statusCode: number; + } + + // Incoming Webhooks + + type IncomingWebhookUrl = string; + type IncomingWebhookHttpHeaders = nock.HttpHeaders; + + interface IncomingWebhooks { + addResponse: (opts: IncomingWebhookOptions) => void; + reset: () => void; + calls: Array>; + } + + interface IncomingWebhookOptions { + url?: IncomingWebhookUrl; + statusCode ?: number; + body ?: T; + headers ?: IncomingWebhookHttpHeaders; + } + + interface IncomingWebhookCall { + url: IncomingWebhookUrl; + params: T; + headers: IncomingWebhookHttpHeaders; + } + + // Interactive Buttons + + type InteractiveButtonUrl = string | Url; + type InteractiveButtonHttpHeaders = nock.HttpHeaders; + + interface InteractiveButtons { + send: (targetUrl: InteractiveButtonUrl, body: T) => Promise; + addResponse: (opts: InteractiveButtonOptions) => void; + reset: () => void; + calls: Array>; + } + + interface InteractiveButtonOptions { + url?: InteractiveButtonUrl; + statusCode ?: number; + body ?: T; + headers ?: InteractiveButtonHttpHeaders; + } + + interface InteractiveButtonCall { + url: InteractiveButtonUrl; + params: T; + headers: InteractiveButtonHttpHeaders; + statusCode: number; + type: InteractiveButtonCallType; + } + + enum InteractiveButtonCallType { + response = 'response', + response_url = 'response_url' + } + + // Outgoing Webhooks + + type OutgoingWebhookUrl = string | Url; + type OutgoingWebhookHttpHeaders = IncomingHttpHeaders; + + interface OutgoingWebhooks { + send: (targetUrl: OutgoingWebhookUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface OutgoingWebhookCall { + url: OutgoingWebhookUrl; + params: T; + headers: OutgoingWebhookHttpHeaders; + statusCode: number; + } + + // RTM + + interface Rtm { + clients: WebSocket[]; + send: (token: string, message: T) => Promise; + reset: () => void; + calls: Array>; + startServer: (token: string) => void; + stopServer: (token: string) => void; + } + + interface RtmCall { + message: T; + token: string; + rawMessage: WebSocket.Data; + } + + // Slash Commands + + type SlashCommandUrl = string | Url; + type SlashCommandHttpHeaders = IncomingHttpHeaders; + + interface SlashCommands { + send: (targetUrl: SlashCommandUrl, body: T) => Promise; + addResponse: (opts: SlashCommandOptions) => void; + reset: () => void; + calls: Array>; + } + + interface SlashCommandOptions { + url?: SlashCommandUrl; + statusCode ?: number; + body ?: T; + headers ?: SlashCommandHttpHeaders; + } + + interface SlashCommandCall { + url: SlashCommandUrl; + params: T; + headers: SlashCommandHttpHeaders; + statusCode: number; + type: SlashCommandCallType; + } + + enum SlashCommandCallType { + response = 'response', + response_url = 'response_url' + } + + // Web + + type WebUrl = string; + type WebHttpHeaders = nock.HttpHeaders; + + interface Web { + addResponse: (opts: WebOptions) => void; + reset: () => void; + calls: Array>; + } + + interface WebOptions { + url?: WebUrl; + statusCode ?: number; + body ?: T; + headers ?: WebHttpHeaders; + } + + interface WebCall { + url: WebUrl; + params: T; + headers: WebHttpHeaders; + } +} diff --git a/types/slack-mock/slack-mock-tests.ts b/types/slack-mock/slack-mock-tests.ts new file mode 100644 index 0000000000..5b5dabb9c1 --- /dev/null +++ b/types/slack-mock/slack-mock-tests.ts @@ -0,0 +1,103 @@ +import SlackMock = require("slack-mock"); + +// Initialization + +const slackMock = SlackMock.instance; +SlackMock({ + logLevel: "error", + rtmPort: 9090 +}); +SlackMock(); + +// Events +const eventPayload = { }; +slackMock.events.send('http://localhost:9000/event', eventPayload) + .then(() => { + slackMock.events.calls.length; + slackMock.events.calls[0].statusCode; + slackMock.events.calls[0].headers; + slackMock.events.calls[0].params; + slackMock.events.calls[0].url; + }); + +slackMock.events.reset(); + +// Incoming Webhooks +slackMock.incomingWebhooks.calls.length; +slackMock.incomingWebhooks.calls[0].params.text; + +// Interactive Buttons +slackMock.interactiveButtons.addResponse({ + statusCode: 201 +}); + +const interactiveButtonPayload = {text: 'abc'}; +slackMock.interactiveButtons.send('http://localhost:9000/button', interactiveButtonPayload) + .then(() => { + slackMock.interactiveButtons.calls.length; + slackMock.interactiveButtons.calls[0].params.text; + }); + +// Outgoing Webhooks +const outgoingWebhookPayload = {text: 'abc'}; +slackMock.outgoingWebhooks.send('http://localhost:9000/outgoing', outgoingWebhookPayload) + .then(() => { + slackMock.outgoingWebhooks.calls.length; + slackMock.outgoingWebhooks.calls[0].params.text; + }); + +// RTM +slackMock.rtm.send('1234', { + type: 'message', + channel: 'mockChannel', + user: 'usr', + text: 'hello'}) + .then(() => { + slackMock.rtm.calls.length; + slackMock.rtm.calls[0].message.text; + }); +slackMock.rtm.startServer('1234'); +slackMock.rtm.stopServer('1234'); + +// Slash Commands +const slashCommandPayload = { }; +slackMock.slashCommands.send('http://localhost:9000/slash', slashCommandPayload) + .then(() => { + slackMock.slashCommands.calls.length; + slackMock.slashCommands.calls[0].params.text; + slackMock.slashCommands.calls[0].params.response_type; + }); + +// Web (OAuth Example) + +const botToken = 'xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT'; +slackMock.web.addResponse({ + url: 'https://slack.com/api/oauth.access', + statusCode: 200, + body: { + access_token: 'xoxp-XXXXXXXX-XXXXXXXX-XXXXX', + scope: 'incoming-webhook,commands,bot', + team_name: 'mockTeam', + team_id: 'Tmock', + bot: { + bot_user_id: 'Bmock', + bot_access_token: botToken + } + } +}); + +slackMock.web.addResponse({ + url: 'https://slack.com/api/rtm.start', + statusCode: 200, + body: { + ok: true, + self: { + name: 'mockSelf', + id: 'Bmock' + }, + team: { + name: 'mockTeam', + id: 'Tmock' + } + } +}); diff --git a/types/slack-mock/tsconfig.json b/types/slack-mock/tsconfig.json new file mode 100644 index 0000000000..e012cc79b1 --- /dev/null +++ b/types/slack-mock/tsconfig.json @@ -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", + "slack-mock-tests.ts" + ] +} \ No newline at end of file diff --git a/types/slack-mock/tslint.json b/types/slack-mock/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/slack-mock/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From bbd49ba4ed08cf2778dc7d10410f918f7ed2c593 Mon Sep 17 00:00:00 2001 From: confususs Date: Mon, 30 Jul 2018 20:26:04 +0200 Subject: [PATCH 065/275] [backbone.marionette] Added parameter for model to childview function of CollectionView (#27441) * Added model param to childview function of CollectionView * Added private property to MyOtherView to ensure type difference --- .../backbone.marionette-tests.ts | 23 +++++++++++++++++-- types/backbone.marionette/index.d.ts | 7 +++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index c6400b2672..2b86849622 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -135,6 +135,15 @@ class MyView extends Marionette.View { } } +class MyOtherView extends MyView { + private readonly foo: string; + + constructor(model: MyModel) { + super(model); + this.foo = 'bar'; + } +} + class MainRegion extends Marionette.Region { constructor() { super(); @@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region { } } -class MyCollectionView extends Marionette.CollectionView { +class MyCollectionView extends Marionette.CollectionView { constructor() { super(); + + this.childView = (model: MyModel) => { + if (model.get('isFoo')) { + return MyView; + } + + return MyOtherView; + }; + this.childView = MyView; + this.childViewEvents = { render() { console.log('a childView has been rendered'); @@ -282,7 +301,7 @@ function CollectionViewTests() { cv.collection.add(new MyModel()); app.mainRegion.show(cv); cv.emptyView = MyView; - const view: Marionette.CollectionView = cv.destroy(); + const view: Marionette.CollectionView = cv.destroy(); } class MyController { diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 0b717c9bb1..bacd045ba1 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zeeshan Hamid , // Natan Vivo , // Sven Tschui , -// Volker Nauruhn +// Volker Nauruhn , +// Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1157,7 +1158,7 @@ export interface CollectionViewOptions< /** * Specify a child view to use. */ - childView?: (() => typeof Backbone.View) | typeof Backbone.View; + childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View; /** * Define options to pass to the childView constructor. @@ -1219,7 +1220,7 @@ export class CollectionView { new(...args: any[]): TView }) | { new(...args: any[]): TView }; + childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView }; /** * Define options to pass to the childView constructor. From 8b490c354b69f4771f57f657ba4ba0142a829363 Mon Sep 17 00:00:00 2001 From: Roger Date: Mon, 30 Jul 2018 20:32:49 +0200 Subject: [PATCH 066/275] Less - add refresh, importManager, sheets, modifyVars callback. (#27443) * Add refresh method, importManager, sheets and modifyVars method callback. * Add a few less tests for their new methods. --- types/less/index.d.ts | 25 +++++++++++++++++++++---- types/less/less-tests.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/types/less/index.d.ts b/types/less/index.d.ts index bca5c21c33..7d69273a52 100644 --- a/types/less/index.d.ts +++ b/types/less/index.d.ts @@ -52,6 +52,11 @@ declare namespace Less { interface StaticOptions { async: boolean; fileAsync: boolean; + modifyVars: { [variable: string]: string }; + } + + interface ImportManager { + contents: { [fileName: string]: string }; } interface Options { @@ -76,21 +81,33 @@ declare namespace Less { map: string; imports: string[]; } + + interface RefreshOutput { + endTime: Date; + startTime: Date; + sheets: number; + totalMilliseconds: number; + } } interface LessStatic { options: Less.StaticOptions; - - modifyVars(vars: { [name: string]: string }): void; - + + importManager?: Less.ImportManager; + sheets: HTMLLinkElement[]; + + modifyVars(vars: { [name: string]: string }): Promise; + refreshStyles(): void; - + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string): Promise; render(input: string, options: Less.Options): Promise; + refresh(reload?: boolean, modifyVars?: { [variable: string]: string }, clearFileCache?: boolean): Promise; + version: number[]; watch(): void; diff --git a/types/less/less-tests.ts b/types/less/less-tests.ts index 5d0029475a..20a1f587a9 100644 --- a/types/less/less-tests.ts +++ b/types/less/less-tests.ts @@ -39,8 +39,22 @@ less.render("h1 { background: red; }", options); less.modifyVars({ '@buttonFace': '#5B83AD', '@buttonText': '#D9EEF2' +}).then((output) => { + console.log('Successfully modified vars.'); }); less.refreshStyles(); less.watch(); + +less.refresh(true, { + '@buttonFace': '#5B83AD' +}, true).then((output) => { + console.log('successfully refreshed less files'); +}); + +if (less.importManager) { + for (let fileName in less.importManager.contents) { + let fileContents = less.importManager.contents[fileName]; + } +} \ No newline at end of file From 7d909e1f5650a74f6902e55d87d9f89ab8369d88 Mon Sep 17 00:00:00 2001 From: Tim Hwang Date: Mon, 30 Jul 2018 14:37:38 -0400 Subject: [PATCH 067/275] redux-form: Remove `label` from Field interface (#27502) This was added to DefinitelyTyped in PRs #21204 and #24041. However, both reasons given are incorrect: this prop is indeed featured in the examples, but only used for a sample component also defined for demo purposes. `props.label` is not a part of the `redux-form` `` API, and as such shouldn't be included. One reason is because `props.label` should be up to users to implement. If a user wants `props.label` to support React nodes instead of just strings, they can no longer just extend DefinitelyTyped interfaces because this causes an incompatibility with the set string type. I realize this change might cause backwards compatibility issues for users who are already using a `label` prop, as it's a ubiquitous pattern. Looking for input on how to properly proceed with this. Thanks! ------ Please fill in this template. - [x] Use a meaningful title for the pull request. Include the name of the package modified. - [x] Test the change in your own code. (Compile and run.) - [x] Add or edit tests to reflect the change. (Run with `npm test`.) *NOTE: I am getting `File name must be camelCase` both before and after my change* - [x] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request). - [x] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes). - [x] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present). Select one of these and delete the others: If changing an existing definition: - [x] Provide a URL to documentation or source code which provides context for the suggested changes: https://github.com/erikras/redux-form/blob/master/src/createField.js ctrl-F label; no result - [ ] Increase the version number in the header if appropriate. - [x] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`. --- types/redux-form/lib/Field.d.ts | 2 -- types/redux-form/redux-form-tests.tsx | 1 - 2 files changed, 3 deletions(-) diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index d27a10ce47..c303f0d5c3 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -37,7 +37,6 @@ export interface CommonFieldProps extends CommonFieldInputProps { export interface BaseFieldProps

extends Partial { name: string; - label?: string; component?: ComponentType | "input" | "select" | "textarea"; format?: Formatter | null; normalize?: Normalizer; @@ -73,7 +72,6 @@ export class Field

extends Comp export interface WrappedFieldProps { input: WrappedFieldInputProps; meta: WrappedFieldMetaProps; - label?: string; } export interface WrappedFieldInputProps extends CommonFieldInputProps { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 06344b54c5..ea13a9618f 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -110,7 +110,6 @@ interface MyFieldCustomProps { type MyFieldProps = MyFieldCustomProps & WrappedFieldProps; const MyField: React.StatelessComponent = ({ children, - label, input, meta, foo From 039caf4113d624977763d32e1f0d15153991149b Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 11:48:14 -0700 Subject: [PATCH 068/275] QUnit assert.step and assert.verifySteps (#27558) --- types/qunit/index.d.ts | 27 +++++++++++++++++++++++++++ types/qunit/qunit-tests.ts | 8 ++++++++ 2 files changed, 35 insertions(+) diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 2b7eb586ff..973a3b00a0 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for QUnit v2.5.0 // Project: http://qunitjs.com/ // Definitions by: James Bracy +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Assert { @@ -234,6 +235,32 @@ interface Assert { */ throws(block: () => void, expected?: any, message?: any): void; raises(block: () => void, expected?: any, message?: any): void; + + /** + * A marker for progress in a given test. + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * + * Together with the `verifySteps()` method, `step()` assertions give you an easy way + * to verify both the count and order of code execution. + * + * @param message Message to display for the step + */ + step(message: string): void; + + /** + * A helper assertion to verify the order and number of steps in a test. + * + * The assert.verifySteps() assertion compares a given array of string values (representing steps) + * with the order and values of previous step() calls. This assertion is helpful for verifying + * the order and count of portions of code paths, especially asynchronous ones. + * + * @param steps Array of strings representing steps to verify + * @param message A short description of the assertion + */ + verifySteps(steps: string[], message?: string): void; } diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index e726113604..d475805cb0 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -562,3 +562,11 @@ equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); + + +QUnit.test('steps', assert => { + assert.step('one'); + assert.step('two'); + assert.step('three'); + assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); +}); From d4b5c5d41199e87f882ab4207948dffbd17662f0 Mon Sep 17 00:00:00 2001 From: S McDowall Date: Mon, 30 Jul 2018 14:59:05 -0400 Subject: [PATCH 069/275] Fix problem in definition when passing a function in the origin: option field. (#27576) * Fixed type for function passing to cors() origin If you look at the actual code within @koa/cors and where it invokes any passed function within the origin: option, it invokes it with ctx, the standard Koa context, NOT the Request. Here is the code fragment.. https://github.com/koajs/cors/blob/b5a937fc24666761c61b1ac633f49f54612d1315/index.js#L58 Thus changed the signature of the origin option to reflect this. * Revert back to single quotes -- stupid prettier Fixed type for function passing to cors() origin If you look at the actual code within @koa/cors and where it invokes any passed function within the origin: option, it invokes it with ctx, the standard Koa context, NOT the Request. Here is the code fragment.. https://github.com/koajs/cors/blob/b5a937fc24666761c61b1ac633f49f54612d1315/index.js#L58 Thus changed the signature of the origin option to reflect this. --- types/koa__cors/index.d.ts | 9 ++++++--- types/koa__cors/koa__cors-tests.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index 25d337716e..da58136652 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for @koa/cors 2.2 // Project: https://github.com/koajs/cors -// Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell +// Definitions by: Xavier Stouder +// Izayoi Ko +// Steve Hipwell +// Steven McDowall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from "koa"; +import * as Koa from 'koa'; export = cors; @@ -12,7 +15,7 @@ declare function cors(options?: cors.Options): Koa.Middleware; declare namespace cors { interface Options { - origin?: ((req: Koa.Request) => string) | string; + origin?: ((ctx: Koa.Context) => string) | string; allowMethods?: string[] | string; exposeHeaders?: string[] | string; allowHeaders?: string[] | string; diff --git a/types/koa__cors/koa__cors-tests.ts b/types/koa__cors/koa__cors-tests.ts index 135845f205..25f068eb13 100644 --- a/types/koa__cors/koa__cors-tests.ts +++ b/types/koa__cors/koa__cors-tests.ts @@ -3,3 +3,11 @@ import cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); + +// Trying using cors() passing in a function .. +function testCorsFunction(ctx: Koa.Context) { + const requestOrigin = ctx.request.origin; + return requestOrigin; +} + +app.use(cors({ origin: testCorsFunction })); From d738494b0898da6e5092660b7951ea969013ce4b Mon Sep 17 00:00:00 2001 From: Resi Respati Date: Tue, 31 Jul 2018 02:00:41 +0700 Subject: [PATCH 070/275] [next] recover old router events APIs (#27695) --- types/next/router.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 74aafd4a33..fe3563d473 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -62,7 +62,16 @@ export interface RouterProps { options?: EventChangeOptions, ): Promise; - // events + // events (deprecated soonish) + onAppUpdated?(nextRoute: string): void; + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) readonly events: { on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; off: (eventName: EventName, handler: (url: string) => any) => void; From f8485f63111d3fc453fa367c6aa961cdfe4b8e1f Mon Sep 17 00:00:00 2001 From: Jurand Niemczycki <32194442+createdbyjurand@users.noreply.github.com> Date: Mon, 30 Jul 2018 21:00:47 +0200 Subject: [PATCH 071/275] espruino: added boolean to digitalwrite (#27577) * espruino added type for wifi module for access point * espruino added myself to definitions * changed tabsize to 4 * espruino: added boolean to digitalwrite --- types/espruino/espruino-tests.ts | 3 +++ types/espruino/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/espruino/espruino-tests.ts b/types/espruino/espruino-tests.ts index 32f044796d..c1bafc9048 100644 --- a/types/espruino/espruino-tests.ts +++ b/types/espruino/espruino-tests.ts @@ -10,5 +10,8 @@ wifi.startAP('ssid', { password: 'pass', authMode: 'wpa_wpa2' }, err => { console.log("created"); }); +digitalWrite(D2, false); +digitalWrite(D2, true); + I2C1.setup({ scl: D4, sda: D0 }); Serial2.setup(9600, { rx: D16, tx: D17 }); diff --git a/types/espruino/index.d.ts b/types/espruino/index.d.ts index 61cf72f173..cb6151e85a 100644 --- a/types/espruino/index.d.ts +++ b/types/espruino/index.d.ts @@ -3600,7 +3600,7 @@ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; * @param value * @url http://www.espruino.com/Reference#l__global_digitalWrite */ -declare function digitalWrite(pin: Pin, value: number): void; +declare function digitalWrite(pin: Pin, value: number | boolean): void; /** *

Get the digital value of the given pin.

From bee839cc6d9f2b0b382ff68708a584049e901a6e Mon Sep 17 00:00:00 2001 From: Tomas Brambora Date: Tue, 31 Jul 2018 05:08:10 +1000 Subject: [PATCH 072/275] Remove unused template type (#27589) --- types/react-measure/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c61b22b187..241d482a53 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -46,7 +46,7 @@ export interface MeasuredComponentProps { type MeasuredComponent = React.ComponentType; -export interface MeasureProps { +export interface MeasureProps { client?: boolean; offset?: boolean; scroll?: boolean; @@ -60,5 +60,5 @@ export interface MeasureProps { export declare function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; -declare class Measure extends React.Component> {} +declare class Measure extends React.Component {} export default Measure; From 37ee427df7c9efb12fa8885a37e8a710ffcd7f50 Mon Sep 17 00:00:00 2001 From: Melvin Groenhoff Date: Mon, 30 Jul 2018 21:10:18 +0200 Subject: [PATCH 073/275] Depend on @babel/parser instead of babylon (#27596) --- types/babel__core/index.d.ts | 6 +++--- types/babel__core/tsconfig.json | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 84f49c20fc..277228341b 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { BabylonOptions } from "babylon"; +import { ParseOptions } from "@babel/parser"; export { - BabylonOptions, + ParseOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: BabylonOptions | null; + parserOpts?: ParseOptions | null; /** * List of plugins to load and use diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 22eb208383..2f96e019cb 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,6 +22,9 @@ "@babel/generator": [ "babel__generator" ], + "@babel/parser": [ + "babel__parser" + ], "@babel/template": [ "babel__template" ], From 7f59e2096edb77eb00281f6b75a52fa7da0a0301 Mon Sep 17 00:00:00 2001 From: Max Loeb Date: Mon, 30 Jul 2018 12:13:46 -0700 Subject: [PATCH 074/275] [jquery.fileupload] fix add signature (#27653) * fix add args * simplify * ws * ws * update version number --- types/jquery.fileupload/index.d.ts | 50 +++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/types/jquery.fileupload/index.d.ts b/types/jquery.fileupload/index.d.ts index 6ca998d41a..28bbf3c969 100644 --- a/types/jquery.fileupload/index.d.ts +++ b/types/jquery.fileupload/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery File Upload Plugin 5.40.1 +// Type definitions for jQuery File Upload Plugin 9.22.0 // Project: https://github.com/blueimp/jQuery-File-Upload // Definitions by: Rob Alarcon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /// -// Interface options for the plugin +// Interface options for the plugin interface JQueryFileInputOptions { /** @@ -106,8 +106,8 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; - // The HTTP request method must be "POST" or "PUT" - type?: string, + // The HTTP request method must be "POST" or "PUT" + type?: string, /** * Set the following option to the location of a postMessage window, @@ -199,7 +199,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + add?: (e: JQueryEventObject, data: JqueryFileUploadAddObject) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -209,7 +209,7 @@ interface JQueryFileInputOptions { cache?: boolean; timeout?: number; - + active?: Function; progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; @@ -217,13 +217,13 @@ interface JQueryFileInputOptions { // Validation /** - * The maximum allowed file size in bytes. - * Type: integer - * Default: undefined - * Example: 10000000 // 10 MB - * Note: This option has only an effect for browsers supporting the File API. - * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize - */ + * The maximum allowed file size in bytes. + * Type: integer + * Default: undefined + * Example: 10000000 // 10 MB + * Note: This option has only an effect for browsers supporting the File API. + * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize + */ maxFileSize?: number; // Other callbacks: @@ -243,7 +243,7 @@ interface JQueryFileInputOptions { chunkfail?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; chunkalways?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; - // Others + // Others url?: string; files?: any; @@ -263,6 +263,12 @@ interface JQuery { fileupload(action: string, message:string, settings: JQueryFileInputOptions | string): JQueryFileUpload; } +interface JqueryFileUploadEnhancedPromise extends JQueryPromise{ + success: JQueryPromise['done'], + error: JQueryPromise['fail'], + complete: JQueryPromise['always'], +} + interface JQuerySupport { fileInput?: boolean; } @@ -275,6 +281,20 @@ interface JQueryFileUploadChangeObject { originalFiles: File[]; } +interface JqueryFileUploadConvenienceObject { + abort: () => JqueryFileUploadEnhancedPromise; + process: (resolveFunc?: Function, rejectFunc?: Function) => JqueryFileUploadEnhancedPromise; + processing: () => JqueryFileUploadEnhancedPromise; + progress: () => JqueryFileUploadEnhancedPromise; + response: () => JqueryFileUploadEnhancedPromise; + submit(): JqueryFileUploadEnhancedPromise; + state: () => JqueryFileUploadEnhancedPromise; +} + +interface JqueryFileUploadAddObject extends JQueryFileUploadChangeObject, JqueryFileUploadConvenienceObject { + paramName?: string | string[]; +} + interface JQueryFileUploadProgressAllObject { loaded?: number; total?: number; @@ -304,4 +324,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF } interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr { -} +} \ No newline at end of file From 56325613eef6f5e27155d314432c2b53440418d0 Mon Sep 17 00:00:00 2001 From: Tyler Zhang Date: Mon, 30 Jul 2018 12:15:15 -0700 Subject: [PATCH 075/275] Add react-native-calendars typings (#27654) * initial type definitions * space out comments more * match pros to be closer to documented proptypes * indent tetss using 4 spaces * fix specs --- types/react-native-calendars/index.d.ts | 418 ++++++++++++++++++ .../react-native-calendars-tests.tsx | 374 ++++++++++++++++ types/react-native-calendars/tsconfig.json | 24 + types/react-native-calendars/tslint.json | 1 + 4 files changed, 817 insertions(+) create mode 100644 types/react-native-calendars/index.d.ts create mode 100644 types/react-native-calendars/react-native-calendars-tests.tsx create mode 100644 types/react-native-calendars/tsconfig.json create mode 100644 types/react-native-calendars/tslint.json diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts new file mode 100644 index 0000000000..6294af4682 --- /dev/null +++ b/types/react-native-calendars/index.d.ts @@ -0,0 +1,418 @@ +// Type definitions for react-native-calendars 1.20 +// Project: https://github.com/wix/react-native-calendars#readme +// Definitions by: Tyler Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import { ViewProps, StyleProp } from 'react-native'; + +export interface DateObject { + year: number; + month: number; + day: number; + timestamp: number; + dateString: string; +} + +export interface CalendarTheme { + backgroundColor?: string; + calendarBackground?: string; + textSectionTitleColor?: string; + selectedDayBackgroundColor?: string; + selectedDayTextColor?: string; + todayTextColor?: string; + dayTextColor?: string; + textDisabledColor?: string; + dotColor?: string; + selectedDotColor?: string; + arrowColor?: string; + monthTextColor?: string; + textDayFontFamily?: string; + textMonthFontFamily?: string; + textDayHeaderFontFamily?: string; + textMonthFontWeight?: string; + textDayFontSize?: number; + textMonthFontSize?: number; + textDayHeaderFontSize?: number; +} + +export interface DayComponentProps { + state: '' | 'selected' | 'disabled' | 'today'; + theme: CalendarTheme; + onPress: () => any; + onLongPress: () => any; + date: DateObject; + marking: false | Marking[]; +} + +export interface CalendarBaseProps { + /** + * Styles for the view + */ + style?: StyleProp; + + /** + * Specify theme properties to override specific styles for calendar parts. Default = {} + */ + theme?: CalendarTheme; + + /** + * Initially visible month. Default = Date() + */ + current?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Handler which gets executed on day press. Default = undefined + */ + onDayPress?: (day: number) => void; + + /** + * Handler which gets executed on day long press. Default = undefined + */ + onDayLongPress?: (day: number) => void; + + /** + * Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + */ + monthFormat?: string; + + /** + * Handler which gets executed when visible month changes in calendar. Default = undefined + */ + onMonthChange?: (month: number) => void; + + /** + * Hide month navigation arrows. Default = false + */ + hideArrows?: boolean; + + /** + * Replace default arrows with custom ones (direction can be 'left' or 'right') + */ + renderArrow?: (direction: 'left' | 'right') => React.ReactNode; + + /** + * Do not show days of other months in month page. Default = false + */ + hideExtraDays?: boolean; + + /** + * If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + * day from another month that is visible in calendar page. Default = false + */ + disableMonthChange?: boolean; + + /** + * If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + */ + firstDay?: number; + + /** + * Hide day names. Default = false + */ + hideDayNames?: boolean; + + /** + * Show week numbers to the left. Default = false + */ + showWeekNumbers?: boolean; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go back month + */ + onPressArrowLeft?: (month: number) => void; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go next month + */ + onPressArrowRight?: (month: number) => void; + + /** + * Custom day renderer + */ + dayComponent?: React.Component | React.SFC; +} + +export interface DotForMultiDot { + key: string; + color: string; + selectedDotColor?: string; +} + +export interface MultiDotMarking { + dots: DotForMultiDot[]; + selected?: boolean; + selectedColor?: string; + disabled?: boolean; +} + +export interface DotMarking { + selected?: boolean; + marked?: boolean; + selectedColor?: string; + dotColor?: string; + activeOpacity?: number; + disabled?: boolean; + disableTouchEvent?: boolean; +} + +export interface PeriodMarking { + textColor?: string; + startingDay?: boolean; + color?: string; + selected?: boolean; + endingDay?: boolean; + disabled?: boolean; +} + +export interface MultiPeriodMarking { + periods: Array<{ + startingDay?: boolean; + endingDay?: boolean; + color?: string; + }>; +} + +export interface CustomMarking { + customStyles: any; +} + +export type Marking = + MultiDotMarking | + DotMarking | + PeriodMarking | + MultiPeriodMarking | + CustomMarking; + +export interface MultiDotMarkingProps { + markingType: 'multi-dot'; + markedDates: { + [date: string]: MultiDotMarking; + }; +} + +export interface DotMarkingProps { + markingType?: 'simple'; + markedDates: { + [date: string]: DotMarking; + }; +} + +export interface PeriodMarkingProps { + markingType: 'period'; + markedDates: { + [date: string]: PeriodMarking; + }; +} + +export interface CustomMarkingProps { + markingType: 'custom'; + markedDates: { + [date: string]: CustomMarking; + }; +} + +/** + * This type of marking is only fully supported by as it will expand the height + * of the component + */ +export interface MultiPeriodMarkingProps { + markingType: 'multi-period'; + markedDates: { + [date: string]: MultiPeriodMarking + }; +} + +export type CalendarMarkingProps = + MultiDotMarkingProps | + DotMarkingProps | + PeriodMarkingProps | + MultiPeriodMarkingProps | + CustomMarkingProps | + {}; + +export class Calendar extends React.Component {} + +export interface CalendarListBaseProps extends CalendarBaseProps { + /** + * Callback which gets executed when visible months change in scroll view. Default = undefined + */ + onVisibleMonthsChange?: (months: number) => void; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * Enable or disable scrolling of calendar list + */ + scrollEnabled?: boolean; + + /** + * Enable or disable vertical scroll indicator. Default = false + */ + showScrollIndicator?: boolean; + + /** + * Enable horizontal scrolling, default = false + */ + horizontal?: boolean; + + /** + * Enable paging on horizontal, default = false + */ + pagingEnabled?: boolean; + + /** + * Set custom calendarWidth. + */ + calendarWidth?: boolean; +} + +export class CalendarList extends React.Component {} + +export interface AgendaProps { + /** + * the list of items that have to be displayed in agenda. If you want to render item as empty date + * the value of date key kas to be an empty array []. If there exists no value for date key it is + * considered that the date in question is not yet loaded + */ + items: { + [key: string]: T[]; + }; + + /** + * callback that gets called when items for a certain month should be loaded (month became visible) + */ + loadItemsForMonth?: (date: DateObject) => void; + + /** + * callback that fires when the calendar is opened or closed + */ + onCalendarToggled?: (calendarOpened: boolean) => void; + + /** + * callback that gets called on day press + */ + onDayPress?: (day: number) => void; + + /** + * callback that gets called when day changes while scrolling agenda list + */ + onDayChange?: (day: number) => void; + + /** + * initially selected day + */ + selected?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * specify how each item should be rendered in agenda + */ + renderItem: (item: T, firstItemInDay?: T) => React.ReactNode; + + /** + * specify how each date should be rendered. day can be undefined if the item is not first in that day. + */ + renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode; + + /** + * specify how empty date content with no items should be rendered + */ + renderEmptyDate?: () => React.ReactNode; + + /** + * specify how agenda knob should look like + */ + renderKnob?: () => React.ReactNode; + + /** + * specify what should be rendered instead of ActivityIndicator + */ + renderEmptyData?: () => React.ReactNode; + + /** + * specify your item comparison function for increased performance + */ + rowHasChanged?: (r1: any, r2: any) => boolean; + + /** + * Hide knob button. Default = false + */ + hideKnob?: boolean; + + /** + * A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView + */ + refreshControl?: React.ReactNode; + + /** + * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. + * Make sure to also set the refreshing prop correctly. + */ + onRefresh?: () => any; + + /** + * Set this true while waiting for new data from a refresh + */ + refreshing?: boolean; + + /** + * Display loading indicator. Default = false + */ + displayLoadingIndicator?: boolean; + + /** + * agenda theme + */ + theme?: { + agendaDayTextColor?: string; + agendaDayNumColor?: string; + agendaTodayColor?: string; + agendaKnobColor?: string; + } & CalendarTheme; + + /** + * agenda container style + */ + style?: StyleProp; +} + +export class Agenda extends React.Component & CalendarMarkingProps> {} diff --git a/types/react-native-calendars/react-native-calendars-tests.tsx b/types/react-native-calendars/react-native-calendars-tests.tsx new file mode 100644 index 0000000000..5b438937e1 --- /dev/null +++ b/types/react-native-calendars/react-native-calendars-tests.tsx @@ -0,0 +1,374 @@ +import * as React from "react"; +import { Text, View } from "react-native"; +import { Calendar, CalendarList, Agenda } from "react-native-calendars"; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} + markedDates={{ + "2012-05-16": { selected: true, marked: true, selectedColor: "blue" }, + "2012-05-17": { marked: true }, + "2012-05-18": { marked: true, dotColor: "red", activeOpacity: 0 }, + "2012-05-19": { disabled: true, disableTouchEvent: true } + }} +/>; + +const vacation = { key: "vacation", color: "red", selectedDotColor: "blue" }; +const massage = { key: "massage", color: "blue", selectedDotColor: "blue" }; +const workout = { key: "workout", color: "green" }; + +; + +; + +; + +; + +; + + { + return ( + + + {date.day} + + + ); + }} +/>; + + { + console.log("now these months are visible", months); + }} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Horizontal + horizontal={true} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // Enable or disable scrolling of calendar list + scrollEnabled={true} + // Enable or disable vertical scroll indicator. Default = false + showScrollIndicator={true} + // Initially visible month. Default = Date() + current={"2012-03-01"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Handler which gets executed on day press. Default = undefined + onDayPress={day => { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("trigger items loading"); + }} + // callback that fires when the calendar is opened or closed + onCalendarToggled={calendarOpened => { + console.log(calendarOpened); + }} + // callback that gets called on day press + onDayPress={day => { + console.log("day pressed"); + }} + // callback that gets called when day changes while scrolling agenda list + onDayChange={day => { + console.log("day changed"); + }} + // initially selected day + selected={"2012-05-16"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // specify how each item should be rendered in agenda + renderItem={(item, firstItemInDay) => { + return ; + }} + // specify how each date should be rendered. day can be undefined if the item is not first in that day. + renderDay={(day, item) => { + return ; + }} + // specify how empty date content with no items should be rendered + renderEmptyDate={() => { + return ; + }} + // specify how agenda knob should look like + renderKnob={() => { + return ; + }} + // specify what should be rendered instead of ActivityIndicator + renderEmptyData={() => { + return ; + }} + // specify your item comparison function for increased performance + rowHasChanged={(r1, r2) => { + return r1.text !== r2.text; + }} + // Hide knob button. Default = false + hideKnob={true} + // By default, agenda dates are marked if they have at least one item, but you can override this if needed + markedDates={{ + "2012-05-16": { selected: true, marked: true }, + "2012-05-17": { marked: true }, + "2012-05-18": { disabled: true } + }} + // If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly. + onRefresh={() => console.log("refreshing...")} + // Set this true while waiting for new data from a refresh + refreshing={false} + // Add a custom RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. + refreshControl={null} + // agenda theme + theme={{ + agendaDayTextColor: "yellow", + agendaDayNumColor: "green", + agendaTodayColor: "red", + agendaKnobColor: "blue" + }} + // agenda container style + style={{}} +/>; diff --git a/types/react-native-calendars/tsconfig.json b/types/react-native-calendars/tsconfig.json new file mode 100644 index 0000000000..e13f60597a --- /dev/null +++ b/types/react-native-calendars/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-native-calendars-tests.tsx" + ] +} diff --git a/types/react-native-calendars/tslint.json b/types/react-native-calendars/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-calendars/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7f227d28c934dc33bb91d750271c61293e9ce0bc Mon Sep 17 00:00:00 2001 From: Johannes Henninger Date: Mon, 30 Jul 2018 21:15:37 +0200 Subject: [PATCH 076/275] Add type definitions for the WebAssembly Web API (#27663) --- types/webassembly-web-api/index.d.ts | 17 +++++++++++++ types/webassembly-web-api/tsconfig.json | 24 +++++++++++++++++++ types/webassembly-web-api/tslint.json | 6 +++++ .../webassembly-web-api-tests.ts | 18 ++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 types/webassembly-web-api/index.d.ts create mode 100644 types/webassembly-web-api/tsconfig.json create mode 100644 types/webassembly-web-api/tslint.json create mode 100644 types/webassembly-web-api/webassembly-web-api-tests.ts diff --git a/types/webassembly-web-api/index.d.ts b/types/webassembly-web-api/index.d.ts new file mode 100644 index 0000000000..fd53e094b2 --- /dev/null +++ b/types/webassembly-web-api/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for the WebAssembly Web API v1 +// Project: https://webassembly.org/ +// Definitions by: Johannes Henninger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +/** + * The WebAssembly Web API defines extensions to the JavaScript API made + * available specifically in web browsers. See [WebAssembly Web + * API](https://www.w3.org/TR/wasm-web-api-1/) for more information. + */ +declare namespace WebAssembly { + function compileStreaming(source: Response | Promise): Promise; + function instantiateStreaming(source: Response | Promise, importObject?: any): Promise; +} diff --git a/types/webassembly-web-api/tsconfig.json b/types/webassembly-web-api/tsconfig.json new file mode 100644 index 0000000000..eb9891f0e0 --- /dev/null +++ b/types/webassembly-web-api/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "webassembly-web-api-tests.ts" + ] +} diff --git a/types/webassembly-web-api/tslint.json b/types/webassembly-web-api/tslint.json new file mode 100644 index 0000000000..65c83fb1e3 --- /dev/null +++ b/types/webassembly-web-api/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/webassembly-web-api/webassembly-web-api-tests.ts b/types/webassembly-web-api/webassembly-web-api-tests.ts new file mode 100644 index 0000000000..5c35d1362b --- /dev/null +++ b/types/webassembly-web-api/webassembly-web-api-tests.ts @@ -0,0 +1,18 @@ +const response: Response = new Response(); +const promise: Promise = Promise.resolve(response); + +// CompileStreaming - taking Response +// $ExpectType Promise +WebAssembly.compileStreaming(response); + +// CompileStreaming - taking Promise +// $ExpectType Promise +WebAssembly.compileStreaming(promise); + +// InstantiateStreaming - taking Response +// $ExpectType Promise +WebAssembly.instantiateStreaming(response); + +// InstantiateStreaming - taking Promise +// $ExpectType Promise +WebAssembly.instantiateStreaming(promise); From 9a8bb65edb5c07917626b4b011641033a8b2bd1e Mon Sep 17 00:00:00 2001 From: Michael Zlatkovsky Date: Mon, 30 Jul 2018 12:17:18 -0700 Subject: [PATCH 077/275] Fix erroneous typings for "charts.add" and "chart.setData" (#27694) * Add empty placeholder for host-specific powerpoint APIs (for use with our d.ts publishing toolchain) * Add extra separator * Fix erroneous typings for "charts.add" and chart.setData It erroneously said "Range | string", but it can only be a Range. --- types/office-js/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 36c659a7b2..7521381cbf 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -18430,7 +18430,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: Excel.ChartType, sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; + add(type: Excel.ChartType, sourceData: Range, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; /** * * Creates a new chart. @@ -18441,7 +18441,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; + add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; /** * * Returns the number of charts in the worksheet. @@ -18663,7 +18663,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): void; + setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void; /** * * Resets the source data for the chart. @@ -18673,7 +18673,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): void; + setData(sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): void; /** * * Positions the chart relative to cells on the worksheet. From 7d44adf2119f49c0536f574e2bde6cf94052bc12 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 30 Jul 2018 12:18:16 -0700 Subject: [PATCH 078/275] bull: make backoffStrategies optional (#27697) --- types/bull/bull-tests.tsx | 5 ++++- types/bull/index.d.ts | 2 +- types/bull/tsconfig.json | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index c2e0d3161f..a8c7f403a7 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -6,7 +6,10 @@ import Redis = require("ioredis"); import Queue = require("bull"); const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379'); -const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object +const audioQueue = new Queue('audio transcoding', { + redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object + settings: {}, +}); const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding'); videoQueue.process((job, done) => { diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 6ed6fa88e7..a11ae0257a 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -88,7 +88,7 @@ declare namespace Bull { /** * Define a custom backoff strategy */ - backoffStrategies: { + backoffStrategies?: { [key: string]: (attemptsMade: number, err: typeof Error) => number; }; } diff --git a/types/bull/tsconfig.json b/types/bull/tsconfig.json index 3ce6f08792..7dbd4e7b61 100644 --- a/types/bull/tsconfig.json +++ b/types/bull/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ From 31c4ba6176f65cd23dfd25e94990a663687a9e17 Mon Sep 17 00:00:00 2001 From: Bond Date: Mon, 30 Jul 2018 20:36:23 +0100 Subject: [PATCH 079/275] Make custom backoff strategies optional (#27698) From 84b265e5b91ee54c23314fa7c1dc50c1a844bd3b Mon Sep 17 00:00:00 2001 From: JounQin Date: Tue, 31 Jul 2018 03:36:31 +0800 Subject: [PATCH 080/275] feat: add declarations for hoist-non-react-statics (#27673) --- .../hoist-non-react-statics-tests.ts | 31 +++++++++++++++++++ types/hoist-non-react-statics/index.d.ts | 28 +++++++++++++++++ types/hoist-non-react-statics/tsconfig.json | 23 ++++++++++++++ types/hoist-non-react-statics/tslint.json | 1 + 4 files changed, 83 insertions(+) create mode 100644 types/hoist-non-react-statics/hoist-non-react-statics-tests.ts create mode 100644 types/hoist-non-react-statics/index.d.ts create mode 100644 types/hoist-non-react-statics/tsconfig.json create mode 100644 types/hoist-non-react-statics/tslint.json diff --git a/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts new file mode 100644 index 0000000000..7065c47410 --- /dev/null +++ b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import hoistNonReactStatics = require('hoist-non-react-statics'); + +class A extends React.Component { + static a = 'a'; + + getA() { + return A.a; + } +} + +class B extends React.Component { + static b = 'b'; + + getB() { + return B.b; + } +} + +const C = hoistNonReactStatics(A, B); + +C.a !== C.b; + +C.prototype.getA(); // should work +// C.prototype.getB(); // should emit an error + +const D = hoistNonReactStatics(A, B, { b: true }); + +D.a; +// D.b; // should emit an error diff --git a/types/hoist-non-react-statics/index.d.ts b/types/hoist-non-react-statics/index.d.ts new file mode 100644 index 0000000000..f55fb92b6d --- /dev/null +++ b/types/hoist-non-react-statics/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for hoist-non-react-statics 3.0 +// Project: https://github.com/mridgway/hoist-non-react-statics#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +declare function hoistNonReactStatics< + T extends React.ComponentType, + S extends React.ComponentType, + C extends { + [key: string]: true + } = {} +>( + TargetComponent: T, + SourceComponent: S, + customStatic?: C, +): T & + { + [key in Exclude< + keyof S, + // only extends static properties, exclude instance properties + 'prototype' | keyof C + >]: S[key] + }; + +export = hoistNonReactStatics; diff --git a/types/hoist-non-react-statics/tsconfig.json b/types/hoist-non-react-statics/tsconfig.json new file mode 100644 index 0000000000..61c70382e5 --- /dev/null +++ b/types/hoist-non-react-statics/tsconfig.json @@ -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", + "hoist-non-react-statics-tests.ts" + ] +} diff --git a/types/hoist-non-react-statics/tslint.json b/types/hoist-non-react-statics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hoist-non-react-statics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cca37a570aecfd6af85c4586f3c0e993a1e537dc Mon Sep 17 00:00:00 2001 From: Garrett McCullough Date: Mon, 30 Jul 2018 12:38:55 -0700 Subject: [PATCH 081/275] Add location state as an optional parameter for Location types in History and React Router (#27699) * Add optional location state parameter to Location types * Revert styling changes * Revert styling changes * Missing quote mark * Revert some other changes * update TS version on qhistory --- types/history/index.d.ts | 15 ++++++++------- types/qhistory/index.d.ts | 2 +- types/react-router/index.d.ts | 4 ++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eb15aaa0fc..1c7b35b8f2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for history 4.6.2 +// Type definitions for history 4.7.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; @@ -23,24 +24,24 @@ export interface History { createHref(location: LocationDescriptorObject): Href; } -export interface Location { +export interface Location { pathname: Pathname; search: Search; - state: LocationState; + state: S; hash: Hash; key?: LocationKey; } -export interface LocationDescriptorObject { +export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; - state?: LocationState; + state?: S; hash?: Hash; key?: LocationKey; } export namespace History { - export type LocationDescriptor = Path | LocationDescriptorObject; + export type LocationDescriptor = Path | LocationDescriptorObject; export type LocationKey = string; export type LocationListener = (location: Location, action: Action) => void; export type LocationState = any; @@ -53,7 +54,7 @@ export namespace History { export type Href = string; } -export type LocationDescriptor = History.LocationDescriptor; +export type LocationDescriptor = History.LocationDescriptor; export type LocationKey = History.LocationKey; export type LocationListener = History.LocationListener; export type LocationState = History.LocationState; diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 301f6b4391..84bd4e6d83 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pshrmn/qhistory#readme // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export as namespace qhistory; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 05d5fe30bb..6814ecf19f 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,9 +64,9 @@ export interface StaticContext { statusCode?: number; } -export interface RouteComponentProps { +export interface RouteComponentProps { history: H.History; - location: H.Location; + location: H.Location; match: match

; staticContext?: C; } From 5ecc5c6e55fdb345d9c94d0fc346e3db81b55cb1 Mon Sep 17 00:00:00 2001 From: dkorolev1 <40392622+dkorolev1@users.noreply.github.com> Date: Mon, 30 Jul 2018 22:49:39 +0300 Subject: [PATCH 082/275] react-adal (#27675) * Definitions for react-adal * empty line remove * ts version --- types/react-adal/index.d.ts | 411 ++++++++++++++++++++++++++ types/react-adal/react-adal-tests.tsx | 75 +++++ types/react-adal/tsconfig.json | 24 ++ types/react-adal/tslint.json | 1 + 4 files changed, 511 insertions(+) create mode 100644 types/react-adal/index.d.ts create mode 100644 types/react-adal/react-adal-tests.tsx create mode 100644 types/react-adal/tsconfig.json create mode 100644 types/react-adal/tslint.json diff --git a/types/react-adal/index.d.ts b/types/react-adal/index.d.ts new file mode 100644 index 0000000000..9f3cd9bef2 --- /dev/null +++ b/types/react-adal/index.d.ts @@ -0,0 +1,411 @@ +// Type definitions for react-adal 0.4 +// Project: https://github.com/salvoravida/react-adal#readme +// Definitions by: Dmitry Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export type TokenCallback = ( + errorDesc: string | null, + token: string | null, + error: any +) => void; + +export type UserCallback = ( + errorDesc: string | null, + user: UserInfo | null +) => void; + +export interface AdalConfig { + /** + * Client ID assigned to your app by Azure Active Directory. + */ + clientId: string; + /** + * Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. + */ + redirectUri?: string; + /** + * Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`. + */ + instance?: string; + /** + * Your target tenant. Defaults to `common`. + */ + tenant?: string; + /** + * Query parameters to add to the authentication request. + */ + extraQueryParameter?: string; + /** + * Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). + */ + correlationId?: string; + /** + * User defined function of handling the navigation to Azure AD authorization endpoint in case of login. + */ + displayCall?: (url: string) => void; + /** + * Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`. + */ + popUp?: boolean; + /** + * Set this to the resource to request on login. Defaults to `clientId`. + */ + loginResource?: string; + /** + * Set this to redirect the user to a custom login page. + */ + localLoginUrl?: string; + /** + * Redirects to start page after login. Defaults to `true`. + */ + navigateToLoginRequestUrl?: boolean; + /** + * Set this to redirect the user to a custom logout page. + */ + logOutUri?: string; + /** + * Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`. + */ + postLogoutRedirectUri?: string; + /** + * Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`. + */ + cacheLocation?: "localStorage" | "sessionStorage"; + /** + * Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs. + */ + endpoints?: { [resource: string]: string }; + /** + * Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs. + */ + anonymousEndpoints?: string[]; + /** + * If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds. + */ + expireOffsetSeconds?: number; + /** + * The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds. + */ + loadFrameTimeout?: number; + /** + * Callback to be invoked when a token is acquired. + */ + callback?: TokenCallback; +} + +export type LoggingLevel = 0 | 1 | 2 | 3; + +export interface RequestInfo { + /** + * Object comprising of fields such as id_token/error, session_state, state, e.t.c. + */ + parameters: any; + /** + * Request type. + */ + requestType: RequestType; + /** + * Whether state is valid. + */ + stateMatch: boolean; + /** + * Unique guid used to match the response with the request. + */ + stateResponse: string; + /** + * Whether `requestType` contains `id_token`, `access_token` or error. + */ + valid: boolean; +} + +export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN"; + +export type ResponseType = "id_token token" | "token"; + +export interface UserInfo { + /** + * Username assigned from UPN or email. + */ + userName: string; + /** + * Properties parsed from `id_token`. + */ + profile: any; +} + +export interface Constants { + ACCESS_TOKEN: 'access_token'; + EXPIRES_IN: 'expires_in'; + ID_TOKEN: 'id_token'; + ERROR_DESCRIPTION: 'error_description'; + SESSION_STATE: 'session_state'; + STORAGE: { + TOKEN_KEYS: 'adal.token.keys'; + ACCESS_TOKEN_KEY: 'adal.access.token.key'; + EXPIRATION_KEY: 'adal.expiration.key'; + STATE_LOGIN: 'adal.state.login'; + STATE_RENEW: 'adal.state.renew'; + NONCE_IDTOKEN: 'adal.nonce.idtoken'; + SESSION_STATE: 'adal.session.state'; + USERNAME: 'adal.username'; + IDTOKEN: 'adal.idtoken'; + ERROR: 'adal.error'; + ERROR_DESCRIPTION: 'adal.error.description'; + LOGIN_REQUEST: 'adal.login.request'; + LOGIN_ERROR: 'adal.login.error'; + RENEW_STATUS: 'adal.token.renew.status'; + }; + RESOURCE_DELIMETER: '|'; + LOADFRAME_TIMEOUT: '6000'; + TOKEN_RENEW_STATUS_CANCELED: 'Canceled'; + TOKEN_RENEW_STATUS_COMPLETED: 'Completed'; + TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress'; + LOGGING_LEVEL: { + ERROR: 0; + WARN: 1; + INFO: 2; + VERBOSE: 3; + }; + LEVEL_STRING_MAP: { + 0: 'ERROR:'; + 1: 'WARNING:'; + 2: 'INFO:'; + 3: 'VERBOSE:'; + }; + POPUP_WIDTH: 483; + POPUP_HEIGHT: 600; +} + +export class AuthenticationContext { + instance: string; + config: AdalConfig; + callback: TokenCallback; + popUp: boolean; + isAngular: boolean; + + /** + * Enum for request type + */ + REQUEST_TYPE: RequestType; + RESPONSE_TYPE: ResponseType; + CONSTANTS: Constants; + + constructor(options: AdalConfig); + /** + * Initiates the login process by redirecting the user to Azure AD authorization endpoint. + */ + login(): void; + /** + * Returns whether a login is in progress. + */ + loginInProgress(): boolean; + /** + * Gets token for the specified resource from the cache. + * @param resource A URI that identifies the resource for which the token is requested. + */ + getCachedToken(resource: string): string; + /** + * If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache. + */ + getCachedUser(): UserInfo; + /** + * Adds the passed callback to the array of callbacks for the specified resource. + * @param resource A URI that identifies the resource for which the token is requested. + * @param expectedState A unique identifier (guid). + * @param callback The callback provided by the caller. It will be called with token or error. + */ + registerCallback( + expectedState: string, + resource: string, + callback: TokenCallback + ): void; + /** + * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireToken(resource: string, callback: TokenCallback): void; + /** + * Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireTokenPopup( + resource: string, + extraQueryParameters: string | null | undefined, + claims: string | null | undefined, + callback: TokenCallback + ): void; + /** + * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + */ + acquireTokenRedirect( + resource: string, + extraQueryParameters?: string | null, + claims?: string | null + ): void; + /** + * Redirects the browser to Azure AD authorization endpoint. + * @param urlNavigate URL of the authorization endpoint. + */ + promptUser(urlNavigate: string): void; + /** + * Clears cache items. + */ + clearCache(): void; + /** + * Clears cache items for a given resource. + * @param resource Resource URI identifying the target resource. + */ + clearCacheForResource(resource: string): void; + /** + * Redirects user to logout endpoint. After logout, it will redirect to `postLogoutRedirectUri` if added as a property on the config object. + */ + logOut(): void; + /** + * Calls the passed in callback with the user object or error message related to the user. + * @param callback The callback provided by the caller. It will be called with user or error. + */ + getUser(callback: UserCallback): void; + /** + * Checks if the URL fragment contains access token, id token or error description. + * @param hash Hash passed from redirect page. + */ + isCallback(hash: string): boolean; + /** + * Gets login error. + */ + getLoginError(): string; + /** + * Creates a request info object from the URL fragment and returns it. + */ + getRequestInfo(hash: string): RequestInfo; + /** + * Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object. + */ + saveTokenFromHash(requestInfo: RequestInfo): void; + /** + * Gets resource for given endpoint if mapping is provided with config. + * @param endpoint Resource URI identifying the target resource. + */ + getResourceForEndpoint(resource: string): string; + /** + * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the callbacks with the result. + * @param hash Hash fragment of URL. Defaults to `window.location.hash`. + */ + handleWindowCallback(hash?: string): void; + + /** + * Checks the logging Level, constructs the log message and logs it. Users need to implement/override this method to turn on logging. + * @param level Level can be set 0, 1, 2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. + * @param message Message to log. + * @param error Error to log. + */ + log(level: LoggingLevel, message: string, error: any): void; + /** + * Logs messages when logging level is set to 0. + * @param message Message to log. + * @param error Error to log. + */ + error(message: string, error: any): void; + /** + * Logs messages when logging level is set to 1. + * @param message Message to log. + */ + warn(message: string): void; + /** + * Logs messages when logging level is set to 2. + * @param message Message to log. + */ + info(message: string): void; + /** + * Logs messages when logging level is set to 3. + * @param message Message to log. + */ + verbose(message: string): void; + + /** + * Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + * @param error Error to log. + */ + errorPii(message: string, error: any): void; + + /** + * Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + warnPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + infoPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + verbosePii(message: string): void; +} + +/** + * Return user token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function adalGetToken( + authContext: AuthenticationContext, + resourceUrl: string +): Promise; + +/** + * Allows to make requests with adal token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + * @param fetch Fetch client + * @param url Request url + * @param options Fetch options + */ +export function adalFetch( + authContext: AuthenticationContext, + resource: string, + fetch: (input: string, init: any) => Promise, + url: string, + options: any +): Promise; + +/** + * Wrap for the app + * @param authContext Authentication context + * @param app Render app callback + * @param doNotLogin Don`t need to login? + */ +export function runWithAdal( + authContext: AuthenticationContext, + app: () => void, + doNotLogin: boolean +): void; + +/** + * Creates a HOC that can be used to manage authentication for the certain components + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function withAdalLogin( + authContext: AuthenticationContext, + resource: string +): ( + wrappedComponent: React.ComponentClass | React.StatelessComponent, + renderLoading: () => JSX.Element | null, + renderError: (error: any) => JSX.Element | null +) => React.ComponentClass; diff --git a/types/react-adal/react-adal-tests.tsx b/types/react-adal/react-adal-tests.tsx new file mode 100644 index 0000000000..961246560f --- /dev/null +++ b/types/react-adal/react-adal-tests.tsx @@ -0,0 +1,75 @@ +import * as React from 'react'; +import { AuthenticationContext, adalFetch, adalGetToken, runWithAdal, withAdalLogin, AdalConfig } from 'react-adal'; + +const resourceUrl = 'https://graph.microsoft.net'; + +const adalConfig: AdalConfig = { + cacheLocation: "localStorage", + clientId: '9ha8cqc6-4668-459a-9272-f48c80a053y5', + endpoints: { + api: resourceUrl + }, + postLogoutRedirectUri: 'https://localhost:3000', + tenant: 'tenantname.onmicrosoft.com' + }; + +const authContext = new AuthenticationContext(adalConfig); + +const adalApiFetch = (fetch: any, url: string, options: any) => { + return adalFetch(authContext, resourceUrl, fetch, url, options); +}; + +const getToken = () => adalGetToken(authContext, resourceUrl); + +class App extends React.Component { + render() { + return null; + } +} + +// user must login to use the app +runWithAdal(authContext, () => { + // ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, false); + +const withAdalLoginApi = withAdalLogin(authContext, resourceUrl); + +const Loading: React.SFC = (props) => { + return null; +}; + +const ErrorPage: React.SFC = (props) => { + return null; +}; + +class SignInPage extends React.Component { + render() { + return null; + } +} + +class ProtectedPage1 extends React.Component { + render() { + return null; + } +} + +const ProtectedPage2: React.SFC = (props) => { + return null; +}; + +const AdalProtectedPage1 = withAdalLoginApi(ProtectedPage1, () => , () => ); +const AdalProtectedPage2 = withAdalLoginApi(ProtectedPage2, () =>

loading...

, () =>

It seems something went wrong...

); + +// user must login to use only specific pages +runWithAdal(authContext, () => { + const routes =
+ // $ExpectError + // $ExpectError + // $ExpectError +
; + // $ExpectError + const App = ; + // $ExpectError + ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, true); diff --git a/types/react-adal/tsconfig.json b/types/react-adal/tsconfig.json new file mode 100644 index 0000000000..b77e4dffc1 --- /dev/null +++ b/types/react-adal/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-adal-tests.tsx" + ] +} diff --git a/types/react-adal/tslint.json b/types/react-adal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-adal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9dd304c111ab32256ad44f8d7ac0a0ddb0c245e5 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Mon, 30 Jul 2018 21:53:09 +0200 Subject: [PATCH 083/275] Add types for detect-node (#27684) --- types/detect-node/detect-node-tests.ts | 3 +++ types/detect-node/index.d.ts | 8 ++++++++ types/detect-node/tsconfig.json | 16 ++++++++++++++++ types/detect-node/tslint.json | 1 + 4 files changed, 28 insertions(+) create mode 100644 types/detect-node/detect-node-tests.ts create mode 100644 types/detect-node/index.d.ts create mode 100644 types/detect-node/tsconfig.json create mode 100644 types/detect-node/tslint.json diff --git a/types/detect-node/detect-node-tests.ts b/types/detect-node/detect-node-tests.ts new file mode 100644 index 0000000000..01a81a356b --- /dev/null +++ b/types/detect-node/detect-node-tests.ts @@ -0,0 +1,3 @@ +import isNode = require("detect-node"); + +isNode; diff --git a/types/detect-node/index.d.ts b/types/detect-node/index.d.ts new file mode 100644 index 0000000000..38fd280f1e --- /dev/null +++ b/types/detect-node/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for detect-node 2.0 +// Project: https://github.com/iliakan/detect-node +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare const isNode: boolean; +export = isNode; diff --git a/types/detect-node/tsconfig.json b/types/detect-node/tsconfig.json new file mode 100644 index 0000000000..e853bcf92c --- /dev/null +++ b/types/detect-node/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "detect-node-tests.ts"] +} diff --git a/types/detect-node/tslint.json b/types/detect-node/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-node/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f20b7f5323c7193e5a391eab22890a85cf5483e3 Mon Sep 17 00:00:00 2001 From: Art Date: Mon, 30 Jul 2018 21:05:46 +0100 Subject: [PATCH 084/275] Add: req-cwd types (#27674) * add req-cwd types * Set typescript version to 2.3 * Fix lint issues --- types/req-cwd/index.d.ts | 15 +++++++++++++++ types/req-cwd/req-cwd-tests.ts | 9 +++++++++ types/req-cwd/tsconfig.json | 23 +++++++++++++++++++++++ types/req-cwd/tslint.json | 1 + 4 files changed, 48 insertions(+) create mode 100644 types/req-cwd/index.d.ts create mode 100644 types/req-cwd/req-cwd-tests.ts create mode 100644 types/req-cwd/tsconfig.json create mode 100644 types/req-cwd/tslint.json diff --git a/types/req-cwd/index.d.ts b/types/req-cwd/index.d.ts new file mode 100644 index 0000000000..56ca4f0786 --- /dev/null +++ b/types/req-cwd/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for req-cwd 2.0 +// Project: https://github.com/sindresorhus/req-cwd +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** Like require(), throws when the module can't be found. */ +declare function reqCwd(moduleId: string): any; + +declare namespace reqCwd { + /** Returns null instead of throwing when the module can't be found. */ + function silent(moduleId: string): any; +} + +export = reqCwd; diff --git a/types/req-cwd/req-cwd-tests.ts b/types/req-cwd/req-cwd-tests.ts new file mode 100644 index 0000000000..df95f8161f --- /dev/null +++ b/types/req-cwd/req-cwd-tests.ts @@ -0,0 +1,9 @@ +import * as reqCwd from 'req-cwd'; + +const r1: string = reqCwd('./foo'); +const r2: number = reqCwd('./foo'); +const r3: {foo: string} = reqCwd('./foo'); + +const s1: string | null = reqCwd.silent('./foo'); +const s2: number | null = reqCwd.silent('./foo'); +const s3: {foo: string} | null = reqCwd.silent('./foo'); diff --git a/types/req-cwd/tsconfig.json b/types/req-cwd/tsconfig.json new file mode 100644 index 0000000000..648ca4cf75 --- /dev/null +++ b/types/req-cwd/tsconfig.json @@ -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", + "req-cwd-tests.ts" + ] +} diff --git a/types/req-cwd/tslint.json b/types/req-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/req-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bb6b63a59b2741f1a05b206aa974125272dbdcd1 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Mon, 30 Jul 2018 22:08:58 +0200 Subject: [PATCH 085/275] [@types/koa-html-minifier] Add type definitions (#27691) * Add koa-router's Router to koa's Context * [@types/koa-html-minifier] Add type definitions * Fix incorrect TypeScript version --- types/koa-html-minifier/index.d.ts | 14 +++++++++++ .../koa-html-minifier-tests.ts | 8 +++++++ types/koa-html-minifier/tsconfig.json | 23 +++++++++++++++++++ types/koa-html-minifier/tslint.json | 1 + 4 files changed, 46 insertions(+) create mode 100644 types/koa-html-minifier/index.d.ts create mode 100644 types/koa-html-minifier/koa-html-minifier-tests.ts create mode 100644 types/koa-html-minifier/tsconfig.json create mode 100644 types/koa-html-minifier/tslint.json diff --git a/types/koa-html-minifier/index.d.ts b/types/koa-html-minifier/index.d.ts new file mode 100644 index 0000000000..5343257116 --- /dev/null +++ b/types/koa-html-minifier/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for koa-html-minifier 1.0 +// Project: https://github.com/koajs/html-minifier +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; +import { Options } from 'html-minifier'; + +declare function minifier(options?: Options): Middleware; + +declare namespace minifier {} + +export = minifier; diff --git a/types/koa-html-minifier/koa-html-minifier-tests.ts b/types/koa-html-minifier/koa-html-minifier-tests.ts new file mode 100644 index 0000000000..c068d303af --- /dev/null +++ b/types/koa-html-minifier/koa-html-minifier-tests.ts @@ -0,0 +1,8 @@ +import * as Koa from 'koa'; +import * as KoaHtmlMinifier from 'koa-html-minifier'; + +const app = new Koa() + .use(KoaHtmlMinifier()) + .use(KoaHtmlMinifier({ + collapseWhitespace: true + })); diff --git a/types/koa-html-minifier/tsconfig.json b/types/koa-html-minifier/tsconfig.json new file mode 100644 index 0000000000..9a46770f6f --- /dev/null +++ b/types/koa-html-minifier/tsconfig.json @@ -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", + "koa-html-minifier-tests.ts" + ] +} diff --git a/types/koa-html-minifier/tslint.json b/types/koa-html-minifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-html-minifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b80b4b5e943c2189a13b9dcd4810192e67bd97ea Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 14:29:18 -0700 Subject: [PATCH 086/275] [@types/qunit] extract callback argument types to interfaces (#27616) * fix: extract QUnit callback argument types to interfaces * move event callback interfaces into QUnit namespace * Combine function argument type assertions into function declarations --- types/qunit/index.d.ts | 59 ++++++++++++++++++++++++-------------- types/qunit/qunit-tests.ts | 26 +++++++++++++++-- 2 files changed, 61 insertions(+), 24 deletions(-) diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 973a3b00a0..c5e677d187 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -340,6 +340,38 @@ interface NestedHooks { } +declare namespace QUnit { + interface BeginDetails { totalTests: number } + interface DoneDetails { failed: number, passed: number, total: number, runtime: number } + interface LogDetails { + result: boolean, + actual: any; + expected: any; + message: string; + source: string; + module: string; + name: string; + runtime: number; + } + interface ModuleDoneDetails { + name: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface ModuleStartDetails { name: string } + interface TestDoneDetails { + name: string; + module: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface TestStartDetails { name: string; module: string; } +} + interface QUnit { /** @@ -360,7 +392,7 @@ interface QUnit { * * @callback callback Callback to execute. */ - begin(callback: (details: { totalTests: number }) => void): void; + begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit @@ -375,7 +407,7 @@ interface QUnit { * * @param callback Callback to execute */ - done(callback: (details: { failed: number, passed: number, total: number, runtime: number }) => void): void; + done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. @@ -419,16 +451,7 @@ interface QUnit { * * @param callback Callback to execute */ - log(callback: (details: { - result: boolean, - actual: any; - expected: any; - message: string; - source: string; - module: string; - name: string; - runtime: number; - }) => void): void; + log(callback: (details: QUnit.LogDetails) => void): void; /** * Group related tests under a single label. @@ -476,20 +499,14 @@ interface QUnit { * * @param callback Callback to execute */ - moduleDone(callback: (details: { - name: string; - failed: number; - passed: number; - total: number; - runtime: number; - }) => void): void; + moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. * * @param callback Callback to execute */ - moduleStart(callback: (details: { name: string }) => void): void; + moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. @@ -605,7 +622,7 @@ interface QUnit { * * @param callback Callback to execute */ - testStart(callback: (details: { name: string; module: string;}) => void): void; + testStart(callback: (details: QUnit.TestStartDetails) => void): void; /** * Adds a test which expects at least one failing assertion during its run. diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index d475805cb0..ae519cd0bc 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -214,13 +214,33 @@ QUnit.log(function( details ) { console.log( output ); }); -QUnit.moduleDone(function( details ) { - console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total ); +QUnit.log(function( details: QUnit.LogDetails ) { + let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; + x = details; }); -QUnit.moduleStart(function( details ) { +QUnit.begin(function( details: QUnit.BeginDetails ) { + console.log( "Total tests running: ", details.totalTests); +}); + +QUnit.done(function( details: QUnit.DoneDetails ) { + console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); +QUnit.testDone(function( details: QUnit.TestDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); +}); + +QUnit.testStart(function( details: QUnit.TestStartDetails ) { + console.log( "Now running: ", details.name, ' from module ', details.module ); +}); let Robot: any = () => {}; From d621d5c0fcb8af0040b83bdb29979f55ec4f5063 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Mon, 30 Jul 2018 23:33:35 +0200 Subject: [PATCH 087/275] Add types for web3-provider-engine (#27707) --- types/web3-provider-engine/index.d.ts | 38 +++++++++++++++++++ types/web3-provider-engine/tsconfig.json | 16 ++++++++ types/web3-provider-engine/tslint.json | 1 + .../web3-provider-engine-tests.ts | 3 ++ 4 files changed, 58 insertions(+) create mode 100644 types/web3-provider-engine/index.d.ts create mode 100644 types/web3-provider-engine/tsconfig.json create mode 100644 types/web3-provider-engine/tslint.json create mode 100644 types/web3-provider-engine/web3-provider-engine-tests.ts diff --git a/types/web3-provider-engine/index.d.ts b/types/web3-provider-engine/index.d.ts new file mode 100644 index 0000000000..d5ba233b18 --- /dev/null +++ b/types/web3-provider-engine/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for web3-provider-engine 14.0 +// Project: https://github.com/MetaMask/provider-engine#readme +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { + Provider, + JSONRPCRequestPayload, + JSONRPCResponsePayload +} from "ethereum-protocol"; +interface Web3ProviderEngineOptions { + pollingInterval?: number; + blockTracker?: any; + blockTrackerProvider?: any; +} +declare class Web3ProviderEngine implements Provider { + constructor(options?: Web3ProviderEngineOptions); + on(event: string, handler: () => void): void; + send(payload: JSONRPCRequestPayload): void; + sendAsync( + payload: JSONRPCRequestPayload, + callback: ( + error: null | Error, + response: JSONRPCResponsePayload + ) => void + ): void; + addProvider(provider: any): void; + // start block polling + start(callback?: () => void): void; + // stop block polling + stop(): void; +} +export = Web3ProviderEngine; + +// declare module "web3-provider-engine/subproviders/nonce-tracker"; +// declare module "web3-provider-engine/subproviders/hooked-wallet"; +// declare module "web3-provider-engine/subproviders/filters"; diff --git a/types/web3-provider-engine/tsconfig.json b/types/web3-provider-engine/tsconfig.json new file mode 100644 index 0000000000..2caa7bbf7b --- /dev/null +++ b/types/web3-provider-engine/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "web3-provider-engine-tests.ts"] +} diff --git a/types/web3-provider-engine/tslint.json b/types/web3-provider-engine/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/web3-provider-engine/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/web3-provider-engine/web3-provider-engine-tests.ts b/types/web3-provider-engine/web3-provider-engine-tests.ts new file mode 100644 index 0000000000..d783728a1b --- /dev/null +++ b/types/web3-provider-engine/web3-provider-engine-tests.ts @@ -0,0 +1,3 @@ +import ProviderEngine = require("web3-provider-engine"); + +new ProviderEngine(); From 593d4f04314a5f41a03b7722c53a9d168be1876b Mon Sep 17 00:00:00 2001 From: Jack Sorrell Date: Mon, 30 Jul 2018 18:55:48 -0400 Subject: [PATCH 088/275] Add typings for thepiratebay (#27709) --- types/thepiratebay/index.d.ts | 69 +++++++++++++++ types/thepiratebay/thepiratebay-tests.ts | 104 +++++++++++++++++++++++ types/thepiratebay/tsconfig.json | 23 +++++ types/thepiratebay/tslint.json | 1 + 4 files changed, 197 insertions(+) create mode 100644 types/thepiratebay/index.d.ts create mode 100644 types/thepiratebay/thepiratebay-tests.ts create mode 100644 types/thepiratebay/tsconfig.json create mode 100644 types/thepiratebay/tslint.json diff --git a/types/thepiratebay/index.d.ts b/types/thepiratebay/index.d.ts new file mode 100644 index 0000000000..20a1cc8945 --- /dev/null +++ b/types/thepiratebay/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for thepiratebay 1.4 +// Project: http://github.com/t3chnoboy/thepiratebay +// Definitions by: Jack Sorrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function search(query?: string, options?: SearchOptions): Promise; +export function getTorrent(id: string | number | { link: string; [propName: string]: any; }): Promise; +export function getComments(id: string | number): Promise; +export function topTorrents(category?: number): Promise; +export function recentTorrents(): Promise; +export function userTorrents(user: string, options?: SearchOptions): Promise; +export function getTvShow(id: string | number): Promise; +export function getCategories(): Promise; + +export interface SearchOptions { + category?: string | number; + filter?: { verified?: boolean }; + page?: number; + orderBy?: string; + sortBy?: string; +} + +export interface Category { + id: string; + name: string; +} + +export interface CategoryGroup extends Category { + subcategories: Category[]; +} + +export interface Torrent { + id: string; + name: string; + size: string; + link: string; + seeders: string; + leechers: string; + uploadDate: string; + magnetLink: string; + uploader: string; + uploaderLink: string; +} + +export interface TorrentDetails extends Torrent { + description: string; +} + +export interface TorrentSearchResult extends Torrent { + category: Category; + subcategory: Category; + verified: boolean; +} + +export interface Comment { + user: string; + comment: string; +} + +export interface TVTorrent { + id: string; + title: string; + link: string; +} + +export interface TVSeason { + title: string; + torrents: TVTorrent[]; +} diff --git a/types/thepiratebay/thepiratebay-tests.ts b/types/thepiratebay/thepiratebay-tests.ts new file mode 100644 index 0000000000..76c56eb269 --- /dev/null +++ b/types/thepiratebay/thepiratebay-tests.ts @@ -0,0 +1,104 @@ +import * as PirateBay from 'thepiratebay'; + +// $ExpectType Promise +const searchResultPromise = PirateBay.search('Game of Thrones', { + category: 'all', + filter: { + verified: false + }, + page: 0, + orderBy: 'leeches', + sortBy: 'desc' +}); +searchResultPromise.then((res: PirateBay.TorrentSearchResult[]) => { + res[0].id; // $ExpectType string + res[0].name; // $ExpectType string + res[0].size; // $ExpectType string + res[0].link; // $ExpectType string + res[0].seeders; // $ExpectType string + res[0].leechers; // $ExpectType string + res[0].uploadDate; // $ExpectType string + res[0].magnetLink; // $ExpectType string + res[0].uploader; // $ExpectType string + res[0].uploaderLink; // $ExpectType string + + const category = res[0].category; // $ExpectType Category + category.id; // $ExpectType string + category.name; // $ExpectType string + + res[0].subcategory; // $ExpectType Category + res[0].verified; // $ExpectType boolean +}); +// $ExpectError +PirateBay.search(15); + +// $ExpectType Promise +const torrentPromise = PirateBay.getTorrent('15496322'); +torrentPromise.then((torrent: PirateBay.TorrentDetails) => { + torrent.id; // $ExpectType string + torrent.name; // $ExpectType string + torrent.size; // $ExpectType string + torrent.link; // $ExpectType string + torrent.seeders; // $ExpectType string + torrent.leechers; // $ExpectType string + torrent.uploadDate; // $ExpectType string + torrent.magnetLink; // $ExpectType string + torrent.uploader; // $ExpectType string + torrent.uploaderLink; // $ExpectType string + torrent.description; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTorrent(15496322); +// $ExpectError +PirateBay.getTorrent(false); +// $ExpectType Promise +PirateBay.getTorrent('https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit'); +// $ExpectType Promise +PirateBay.getTorrent({ name: "ubuntu", link: 'https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit' }); + +// $ExpectType Promise +PirateBay.topTorrents(); +// $ExpectError +PirateBay.topTorrents(true); +// $ExpectType Promise +PirateBay.topTorrents(400); + +// $ExpectType Promise +PirateBay.recentTorrents(); +// $ExpectError +PirateBay.recentTorrents(10); + +// $ExpectError +PirateBay.userTorrents(); +// $ExpectType Promise +PirateBay.userTorrents('alice', { + page: 3, + orderBy: 'name', + sortBy: 'asc' +}); +// $ExpectType Promise +PirateBay.userTorrents('bob'); + +// $ExpectType Promise +const categoryGroup = PirateBay.getCategories(); +categoryGroup.then((groups: PirateBay.CategoryGroup[]) => { + groups[0].id; // $ExpectType string + groups[0].name; // $ExpectType string + groups[0].subcategories; // $ExpectType Category[] +}); +// $ExpectError +PirateBay.getCategories(154); + +// $ExpectError +PirateBay.getTvShow(); +// $ExpectType Promise +const tvShow = PirateBay.getTvShow(15); +tvShow.then((seasons: PirateBay.TVSeason[]) => { + seasons[0].title; // $ExpectType string + const torrents = seasons[0].torrents; // $ExpectType TVTorrent[] + torrents[0].id; // $ExpectType string + torrents[0].title; // $ExpectType string + torrents[0].link; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTvShow('15'); diff --git a/types/thepiratebay/tsconfig.json b/types/thepiratebay/tsconfig.json new file mode 100644 index 0000000000..1d491e4d75 --- /dev/null +++ b/types/thepiratebay/tsconfig.json @@ -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", + "thepiratebay-tests.ts" + ] +} diff --git a/types/thepiratebay/tslint.json b/types/thepiratebay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/thepiratebay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From eba49a93214286fdb652ccebf017b1e3753a6893 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Mon, 30 Jul 2018 15:56:47 -0700 Subject: [PATCH 089/275] office-js: tweak info about getEntities and getEntitiesByType (#27710) --- types/office-js/index.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 7521381cbf..d883822f37 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -8708,7 +8708,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8722,7 +8722,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8731,7 +8731,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks *
@@ -9989,7 +9989,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10003,7 +10003,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10012,7 +10012,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
@@ -11523,7 +11523,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11537,7 +11537,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11546,7 +11546,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * From f11a3342486e62b9f62a0fe54263a744bb5a34a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Freitas?= Date: Tue, 31 Jul 2018 00:02:02 +0100 Subject: [PATCH 090/275] video.js - complete definitions for video.js api (#27515) * Update index.d.ts Added definitions for almost every class * Update tslint.json Added rules to have module declaration support * Update index.d.ts Removed empty jsdoc comments * Update video.js-tests.ts Removed non existing size method call * Update tslint.json Disable no-redundant-jsdoc and void-return rules * Update index.d.ts Moved components option types one level up from the component specific namespace * Update video.js-tests.ts Removed default import signature * Update index.d.ts Fixed videojs.dom.getPointerPosition function return type from Coordinates to Dom.Coordinates * Update index.d.ts Removed redundant declare module change default export to = * Update tslint.json removed no-single-declare-module and no-declare-current-package disabling rules * Update tslint.json ups... * Update tslint.json ups again... * Update index.d.ts Changed Tech.SourceObject type option to be optional * Update tslint.json disabled 'no-redundant-jsdoc-2' rule * Update index.d.ts Removed types from @param and @return JSDoc tags set it compliant with no-redudant-jsdoc-2 * Update tslint.json Enabled no-redundant-jsdoc-2 rule --- types/video.js/index.d.ts | 6872 ++++++++++++++++++++++++++++-- types/video.js/video.js-tests.ts | 4 +- 2 files changed, 6609 insertions(+), 267 deletions(-) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index f18ff8890e..6e5863500d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 6.2 +// Type definitions for Video.js 7.0 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -15,285 +15,6629 @@ // Javascript, whether the browser is playing the video through HTML5 // video, Flash, or any other supported playback technologies. -declare function videojs( - id: any, - options?: videojs.PlayerOptions, - ready?: () => void -): videojs.Player; -export default videojs; +/** + * Doubles as the main function for users to create a inplayer instance and also + * the main library object. + * The `videojs` function can be used to initialize or retrieve a player. + * + * @param id + * Video element or video element ID + * + * @param [options] + * Optional options object for config/settings + * + * @param [ready] + * Optional ready callback + * + * @return A player instance + */ +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; export as namespace videojs; declare namespace videojs { - const getComponent: typeof Component.getComponent; - const registerComponent: typeof Component.registerComponent; - const getPlugin: typeof Plugin.getPlugin; - function registerPlugin( - pluginName: string, - pluginFn: (this: Player, ...parameters: any[]) => void - ): void; - function addLanguage(lang: string, data: { [key: string]: string }): void; - function mergeOptions( - option: A, - option2?: B, - option3?: C, - option4?: D, - option5?: E, - option6?: F - ): A & B & C & D & E & F; + /** + * Adding languages so that they're available to all players. + * Example: `addLanguage('es', { 'Hello': 'Hola' });` + * + * @param code + * The language code or dictionary property + * + * @param data + * The data values to be translated + * + * @return The resulting language dictionary object + */ + function addLanguage(code: string, data: LanguageTranslations): LanguageTranslations; - interface PlayerOptions { - aspectRatio?: string; - autoplay?: boolean; - autoSetup?: boolean; - children?: string[]; - controlBar?: { - volumePanel?: { - inline?: boolean; - vertical?: boolean; - }; - }; - controls?: boolean; - defaultVolume?: number; - fluid?: boolean; - height?: number; - html5?: any; - inactivityTimeout?: number; - language?: string; - languages?: { [key: string]: string }; - loop?: boolean; - muted?: boolean; - nativeControlsForTouch?: boolean; - notSupportedMessage?: string; - playbackRates?: number[]; - plugins?: any; - poster?: string; - preload?: string; - sourceOrder?: boolean; - sources?: Source[]; - src?: string; - techCanOverridePoster?: boolean; - techOrder?: string[]; - width?: number; - } + /** + * Bind (a.k.a proxy or Context). A simple method for changing the context of a function + * It also stores a unique id on the function so it can be easily removed from events. + * + * @param context + * The object to bind as scope. + * + * @param fn + * The function to be bound to a scope. + * + * @param [uid] + * An optional unique ID for the function to be set + * + * @return The new function that will be bound into the context given + */ + function bind any)>(context: any, fn: F, uid?: number): F; - interface Source { - type: string; - src: string; - } + /** + * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. + * + * @param start + * The start of a single range or an array of ranges + * + * @param end + * The end of a single range. + */ + function createTimeRanges(start?: number | TimeRange[], end?: number): TimeRange; - interface Dimensions { - width: number; - height: number; - } + /** + * A suite of browser and device tests from {@link browser}. + * + */ + const browser: Browser; - class EventTarget { - addEventListener( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - dispatchEvent(event: string | Event | { [key: string]: any }): void; - off( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - on( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - one( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - removeEventListener( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - trigger(event: string | Event | { [key: string]: any }): void; - } + const dom: Dom; - class Component extends EventTarget { - constructor(player: Player, options: any); + /** + * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) + * will force a number of leading zeros to cover the length of the guide. + * + * @param seconds + * Number of seconds to be turned into a string + * + * @param guide + * Number (in seconds) to model the string after + * + * @return Time formatted as H:MM:SS or M:SS + */ + function formatTime(seconds: number, guide: number): string; - static getComponent(name: "Player" | "player"): typeof Player; - static getComponent(name: "Button" | "button"): typeof Button; - static getComponent( - name: "ClickableComponent" | "clickablecomponent" - ): typeof ClickableComponent; - static getComponent( - name: "ModalDialog" | "modaldialog" - ): typeof ModalDialog; - static getComponent( - name: "ControlBar" | "controlbar" - ): typeof ControlBar; - static getComponent( - name: "Component" | "component" | string - ): typeof Component; - static registerComponent( - name: string, - ComponentToRegister: typeof Component - ): typeof Component; + /** + * Returns an array of all current players. + * + * @return An array of all players. The array will be in the order that + * `Object.keys` provides, which could potentially vary between + * JavaScript engines. + * + */ + function getAllPlayers(): Player[]; - $(selector: string, context?: string | Element): Element; - $$(selector: string, context?: string | Element): NodeList; - addChild( - component: string, - optionsopt?: any, - indexopt?: number - ): Component; - addChild( - component: Element, - optionsopt?: any, - indexopt?: number - ): Element; - addChild( - component: T, - optionsopt?: any, - indexopt?: number - ): T; - addClass(classToAdd: string): void; - blur(): void; - buildCSSClass(): string; - cancelAnimationFrame(id: number): number; - children(): Component[]; - controlText(key: string): string; - clearInterval(intervalId: number): number; - clearTimeout(timeoutId: number): number; - contentEl(): Element; - createEl( - tagNameopt?: string, - properties?: any, - attributes?: any - ): Element; - currentDimension(widthOrHeight: "width" | "height"): number; - currentDimensions(): Dimensions; - currentHeight(): number; - currentWidth(): number; - dimension(widthOrHeight: "width" | "height"): number; - dimension( - widthOrHeight: "width" | "height", - num: string | number, - skipListenersopt?: boolean - ): void; - dimensions(width: string | number, height: string | number): void; - dispose(): void; - el(): Element; - enableTouchActivity(): void; - focus(): void; - getAttribute(attribute: string): string | null; - getChild(name: string): Component | undefined; - getChildById(id: string): Component | undefined; - hasClass(classToCheck: string): boolean; - height(): number | string; - height(num: number | string, skipListeners?: boolean): void; - hide(): void; - id(): string; - initChildren(): void; - localize(key: string, tokens?: string[], defaultValue?: string): string; - name(): string; - options(obj: any): any; - played(): TimeRanges; - player(): Player; - ready(callback: (this: this) => void): this; - removeAttribute(attribute: string): void; - removeChild(component: Component): void; - removeClass(classToRemove: string): void; - requestAnimationFrame(fn: () => void): number; - setAttribute(attribute: string, value: string): void; - setInterval(fn: () => void, interval: number): number; - setTimeout(fn: () => void, timeout: number): number; - show(): void; - toggleClass( - classToToggle: string, - predicate?: - | boolean - | ((element: Element, classToToggle: string) => boolean) - ): void; - trigger(eventName: string, ...parameters: any[]): void; - triggerReady(): void; - width(): string | number; - width(num: number, skipListeners?: number): void; - } + /** + * Get a component class object by name + * + * @borrows Component.getComponent as getComponent + */ + const getComponent: typeof Component.getComponent; - class ControlBar extends Component {} + /** + * Get a single player based on an ID or DOM element. + * + * This is useful if you want to check if an element or ID has an associated + * Video.js player, but not create one if it doesn't. + * + * @param id + * An HTML element - `
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* * Returned by the status property of the AsyncResult object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum AsyncResultStatus { /** @@ -297,7 +313,20 @@ declare namespace Office { * Specifies whether the add-in was just inserted or was already contained in the document. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum InitializationReason { /** @@ -313,7 +342,23 @@ declare namespace Office { * Specifies the host Office application in which the add-in is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum HostType { /** @@ -349,7 +394,23 @@ declare namespace Office { * Specifies the OS or other platform on which the Office host application is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum PlatformType { /** @@ -1157,7 +1218,18 @@ declare namespace Office { /** * Specifies the state of the active view of the document, for example, whether the user can edit the document. * @remarks - *
HostsPowerPoint
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ enum ActiveView { /** @@ -1172,7 +1244,20 @@ declare namespace Office { /** * Specifies the type of the binding object that should be returned. * @remarks - *
HostsAccess, Excel, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ enum BindingType { /** @@ -1192,9 +1277,24 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
- * * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum CoercionType { /** @@ -1242,9 +1342,23 @@ declare namespace Office { * Specifies whether the document in the associated application is read-only or read-write. * * @remarks - *
HostsExcel, PowerPoint, Project, Word
- * + * * Returned by the mode property of the Document object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum DocumentMode { /** @@ -1260,9 +1374,19 @@ declare namespace Office { * Specifies the type of the XML node. * * @remarks - * + *
HostsWord
Requirement SetsCustomXmlParts
* - * Requirement SetsCustomXmlParts + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ enum CustomXMLNodeType { /** @@ -1296,13 +1420,27 @@ declare namespace Office { } /** * Specifies the kind of event that was raised. Returned by the `type` property of an *EventArgs object. - * - * @remarks - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Hosts (BindingDataChanged and BindingSelectionChanged)Access, Excel, Word
- * * * Add-ins for Project support the `Office.EventType.ResourceSelectionChanged`, `Office.EventType.TaskSelectionChanged`, and `Office.EventType.ViewSelectionChanged` event types. + * + * BindingDataChanged and BindingSelectionChanged hosts
Access, Excel, Word
+ * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
*/ enum EventType { /** @@ -1374,7 +1512,21 @@ declare namespace Office { * Specifies the format in which to return the document. * * @remarks - *
HostsPowerPoint, Word
+ * FileType.Text is only supported in Word, FileType.Pdf is only supported in Word for Windows, Word for Mac, Word Online, and PowerPoint. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ enum FileType { /** @@ -1382,7 +1534,7 @@ declare namespace Office { */ Text, /** - * Returns the entire document (.pptx, .docx, or .xslx) in Office Open XML (OOXML) format as a byte array. + * Returns the entire document (.pptx, .docx, or .xlsx) in Office Open XML (OOXML) format as a byte array. */ Compressed, /** @@ -1394,7 +1546,20 @@ declare namespace Office { * Specifies whether filtering from the host application is applied when the data is retrieved. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum FilterType { /** @@ -1410,7 +1575,20 @@ declare namespace Office { * Specifies the type of place or object to navigate to. * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
*/ enum GoToType { /** @@ -1435,7 +1613,20 @@ declare namespace Office { * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
Excel Y Y Y
PowerPoint Y
Word Y Y
*/ enum SelectionMode { Default, @@ -1452,10 +1643,22 @@ declare namespace Office { * Specifies whether values, such as numbers and dates, returned by the invoked method are returned with their formatting applied. * * @remarks - *
HostsExcel, Project, Word
- * * For example, if the valueFormat parameter is specified as "formatted", a number formatted as currency, or a date formatted as mm/dd/yy in the host application will have its formatting preserved. * If the valueFormat parameter is specified as "unformatted", a date will be returned in its underlying sequential serial number form. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum ValueFormat { /** @@ -3419,7 +3622,18 @@ declare namespace Office { * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks - *
HostsExcel
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
*/ enum Table { /** @@ -3450,9 +3664,20 @@ declare namespace Office { * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. * * @remarks - *
HostsProject
* * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectProjectFields { /** @@ -3512,6 +3737,18 @@ declare namespace Office { * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectResourceFields { /** @@ -4322,8 +4559,18 @@ declare namespace Office { * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. - * - *
HostsProject
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectTaskFields { /** @@ -5457,9 +5704,19 @@ declare namespace Office { * Specifies the types of views that the getSelectedViewAsync method can recognize. * * @remarks - *
HostsProject
- * * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectViewTypes { /** From 4ee926dbad683b2b8702f567dadde08b6cfc9843 Mon Sep 17 00:00:00 2001 From: Andrew MacLeay Date: Thu, 2 Aug 2018 16:33:31 -0400 Subject: [PATCH 164/275] Allow readonly parameters to storybook knobs Since these functions don't modify their parameters, they may be readonly. Non-breaking change as mutable arrays are still allowed as well. --- types/storybook__addon-knobs/index.d.ts | 5 +++-- .../storybook__addon-knobs-tests.tsx | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/types/storybook__addon-knobs/index.d.ts b/types/storybook__addon-knobs/index.d.ts index 3c9bbe0fc4..4d6eff536f 100644 --- a/types/storybook__addon-knobs/index.d.ts +++ b/types/storybook__addon-knobs/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Martynas Kadisa +// A.MacLeay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -49,11 +50,11 @@ export function object(name: string, value: T, groupId?: string): T; export type SelectValue = string | number; export function select(name: string, options: { [s: string]: string }, value: T, groupId?: string): T; export function select(name: string, options: { [s: number]: string }, value: T, groupId?: string): T; -export function select(name: string, options: T[], value: T, groupId?: string): T; +export function select(name: string, options: ReadonlyArray, value: T, groupId?: string): T; export function date(name: string, value?: Date, groupId?: string): Date; -export function array(name: string, value: T[], separator?: string, groupId?: string): T[]; +export function array(name: string, value: ReadonlyArray, separator?: string, groupId?: string): T[]; export function button(name: string, handler: () => any, groupId?: string): void; diff --git a/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx b/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx index c35268ac6b..ee8f58893c 100644 --- a/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx +++ b/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx @@ -90,6 +90,14 @@ stories.add('dynamic knobs', () => { ); }); +const readonlyOptionsArray: ReadonlyArray = ['hi']; +select('With readonly array', readonlyOptionsArray, readonlyOptionsArray[0]); + +const genericArray = array('With regular array', ['hi', 'there']); + +const userInputArray = array('With readonly array', readonlyOptionsArray); +userInputArray.push('Make sure that the output is still mutable although the input need not be!'); + // groups const groupId = 'GROUP-ID1'; From 3a9ec5cad2985894be9b275841c82d54bb3ce643 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Thu, 2 Aug 2018 16:40:51 -0700 Subject: [PATCH 165/275] office-js: initial set of SharedAPI scrub (#27826) * merge from master * office-js-first-set --- types/office-js/index.d.ts | 135 ++++++++++++++++++++++++++----------- 1 file changed, 95 insertions(+), 40 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 09cb848330..a731343bc6 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -280,7 +280,7 @@ declare namespace Office { * * @remarks * - * Returned by the status property of the AsyncResult object. + * Returned by the {@link Office.AsyncResult.status | status} property of the {@link Office.AsyncResult | AsyncResult} object. * * **Support details** * @@ -354,6 +354,7 @@ declare namespace Office { * Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac * Access Y * Excel Y Y Y + * OneNote Y Y * Outlook Y Y Y Y * PowerPoint Y Y Y * Project Y @@ -406,6 +407,7 @@ declare namespace Office { * Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac * Access Y * Excel Y Y Y + * OneNote Y Y * Outlook Y Y Y Y * PowerPoint Y Y Y * Project Y @@ -449,7 +451,7 @@ declare namespace Office { */ interface AsyncResult { /** - * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. + * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This returns the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. * * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
@@ -475,9 +477,9 @@ declare namespace Office { * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the Document object. + * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the {@link Office.Document.getSelectedDataAsync | getSelectedDataAsync} and {@link Office.Document.setSelectedDataAsync | setSelectedDataAsync} methods of the Document object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the AsyncResult object topic. + * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the {@link Office.AsyncResult | AsyncResult} object topic. */ value: any; } @@ -509,6 +511,7 @@ declare namespace Office { diagnostics: ContextInformation; /** * Gets the locale (language) specified by the user for the UI of the Office host application. + * * @remarks * When using in Outlook, the applicable modes are Compose or read. */ @@ -821,7 +824,8 @@ declare namespace Office { * @remarks * * - *
HostsExcel, OneNote, Outlook, PowerPoint, Word
Requirement setsIdentityAPI
+ * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements +| IdentityAPI} * * This API requires a single sign-on configuration that bridges the add-in to an Azure application. Office users sign-in with Organizational Accounts and Microsoft Accounts. Microsoft Azure returns tokens intended for both user account types to access resources in the Microsoft Graph. * @@ -1269,7 +1273,7 @@ declare namespace Office { */ Matrix, /** - * Tabular data with a header row. Data is returned as a TableData object. + * Tabular data with a header row. Data is returned as a {@link Office.TableData | TableData} object. */ Table } @@ -1277,7 +1281,9 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. + * + * Project supports only `Office.CoercionType.Text`. * * **Support details** * @@ -1298,43 +1304,42 @@ declare namespace Office { */ enum CoercionType { /** - * Return or set data as text (string).Data is returned or set as a one-dimensional run of characters. + * Return or set data as text (string). Data is returned or set as a one-dimensional run of characters. */ Text, /** * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. - * @remarks - * Only applies to data in Excel and Word. + * + * Note: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. - * @remarks - * Only applies to data in Access, Excel and Word. + * + * Note: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. - * @remarks - * Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * + * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. - * @remarks - * Only applies to data in Word. + * + * Note: Only applies to data in Word. */ Ooxml, /** - * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides.For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. - * @remarks - * Only applies to data in PowerPoint when calling the Document.getSelectedData method to get the current slide or selected range of slides. + * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. + * + * Note: Only applies to data in PowerPoint when calling the {@link Office.Document.getSelectedData | Document.getSelectedData} method to get the current slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * @remarks - * Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word and PowerPoint. */ Image } @@ -1343,7 +1348,7 @@ declare namespace Office { * * @remarks * - * Returned by the mode property of the Document object. + * Returned by the mode property of the {@link Office.Document | Document} object. * * **Support details** * @@ -1437,6 +1442,7 @@ declare namespace Office { * * * + * * * * @@ -1468,27 +1474,33 @@ declare namespace Office { */ DialogEventReceived, /** - * Triggers when a document level selection happens + * Triggers when a document level selection happens. */ DocumentSelectionChanged, /** - * A Document.SelectionChanged event was raised. + * Triggers when the selected Outlook item was changed. + * + * [Api set: Mailbox 1.1] */ ItemChanged, /** - * Triggers when a customXmlPart node was deleted + * Triggers when a customXmlPart node was deleted. */ NodeDeleted, /** - * Triggers when a customXmlPart node was inserted + * Triggers when a customXmlPart node was inserted. */ NodeInserted, /** - * Triggers when a customXmlPart node was replaced + * Triggers when a customXmlPart node was replaced. */ NodeReplaced, /** - * The recurrence pattern of the selected series has changed. + * Triggers when the recurrence pattern of the selected series was changed in Outlook. + * + * [Api set: Mailbox Preview] + * + * @beta */ RecurrencePatternChanged, /** @@ -1593,24 +1605,67 @@ declare namespace Office { enum GoToType { /** * Goes to a binding object using the specified binding id. + * + * Supported hosts: Excel, Word */ Binding, /** * Goes to a named item using that item's name. * In Excel, you can use any structured reference for a named range or table: "Worksheet2!Table1" + * + * Supported hosts: Excel */ NamedItem, /** * Goes to a slide using the specified id. + * + * Supported hosts: PowerPoint */ Slide, /** - * Goes to the specified index by slide number or Office.Index + * Goes to the specified index by slide number or {@link Office.Index}. + * + * Supported hosts: PowerPoint */ Index } /** - * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). + * Specifies the relative PowerPoint slide + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
+ * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
PowerPoint Y Y Y
+ */ + enum Index { + /** + * Represents the first PowerPoint slide + */ + First, + /** + * Represents the last PowerPoint slide + */ + Last, + /** + * Represents the next PowerPoint slide + */ + Next, + /** + * Represents the previous PowerPoint slide + */ + Previous + } + /** + * Specifies whether to select (highlight) the location to navigate to (when using the {@link Office.Document.goToByIdAsync | Document.goToByIdAsync} method). * * @remarks * @@ -1635,7 +1690,7 @@ declare namespace Office { */ Selected, /** - * The cursor is moved the beginning of the location. + * The cursor is moved to the beginning of the location. */ None } @@ -3619,7 +3674,7 @@ declare namespace Office { rows: any[][]; } /** - * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. + * Specifies enumerated values for the `cells` property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks * @@ -3661,11 +3716,11 @@ declare namespace Office { */ interface TextBinding extends Binding { } /** - * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. + * Specifies the project fields that are available as a parameter for the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. * * @remarks * - * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * A ProjectProjectFields constant can be used as a parameter of the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. * * **Support details** * @@ -3731,10 +3786,10 @@ declare namespace Office { WSSList } /** - * Specifies the resource fields that are available as a parameter for the getResourceFieldAsync method. + * Specifies the resource fields that are available as a parameter for the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * @remarks - * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. + * A ProjectResourceFields constant can be used as a parameter of the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -4553,10 +4608,10 @@ declare namespace Office { Text9 } /** - * Specifies the task fields that are available as a parameter for the getTaskFieldAsync method. + * Specifies the task fields that are available as a parameter for the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * @remarks - * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. + * A ProjectTaskFields constant can be used as a parameter of the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -5701,10 +5756,10 @@ declare namespace Office { WSSID } /** - * Specifies the types of views that the getSelectedViewAsync method can recognize. + * Specifies the types of views that the {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method can recognize. * * @remarks - * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * The {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method returns the ProjectViewTypes constant value and name that corresponds to the active view. * * **Support details** * From 7c33a958277e53aa335dcddec28ebfe6502638ca Mon Sep 17 00:00:00 2001 From: Claas Ahlrichs Date: Fri, 3 Aug 2018 01:41:18 +0200 Subject: [PATCH 166/275] added definitions for react select (v2) (#27737) * moved existing "react-select" definitions into "v1" directory * updated references to V1 of "react-select" * dts-gen --dt --name react-select --template module * added placeholders for react-select definitions and tests * fixed imports of react and react-select * updated config. files * drafted definitions for react-select * updated definitions for react-select * made Props in stateManager.d.ts and Select.d.ts optional * handle grouped options in Select.d.ts * updated definitions for react-select * resolved merge conflicts * fixed issues identified by "npm test" * updated type of "menuPortalTarget" * remove OptionType type and introduce throughout as a generic parameter * add an extra type * re-enable interface-over-type-literal lint rule * parameterize GroupedOptionsType after some consideration this should be parameterized, typically with a union type, see Grouped example which is a select of `ColourOption | FlavourOption` --- types/react-select/index.d.ts | 667 +----------------- types/react-select/lib/Async.d.ts | 47 ++ types/react-select/lib/AsyncCreatable.d.ts | 25 + types/react-select/lib/Creatable.d.ts | 49 ++ types/react-select/lib/Select.d.ts | 419 +++++++++++ .../react-select/lib/accessibility/index.d.ts | 10 + types/react-select/lib/animated/Input.d.ts | 10 + .../react-select/lib/animated/MultiValue.d.ts | 12 + .../lib/animated/Placeholder.d.ts | 9 + .../lib/animated/SingleValue.d.ts | 9 + .../lib/animated/ValueContainer.d.ts | 9 + types/react-select/lib/animated/index.d.ts | 17 + .../lib/animated/transitions.d.ts | 50 ++ types/react-select/lib/builtins.d.ts | 10 + .../react-select/lib/components/Control.d.ts | 29 + types/react-select/lib/components/Group.d.ts | 24 + types/react-select/lib/components/Input.d.ts | 23 + types/react-select/lib/components/Menu.d.ts | 158 +++++ .../lib/components/MultiValue.d.ts | 57 ++ types/react-select/lib/components/Option.d.ts | 41 ++ .../lib/components/Placeholder.d.ts | 17 + .../lib/components/SingleValue.d.ts | 23 + .../lib/components/containers.d.ts | 57 ++ types/react-select/lib/components/index.d.ts | 142 ++++ .../lib/components/indicators.d.ts | 67 ++ types/react-select/lib/diacritics.d.ts | 1 + types/react-select/lib/filters.d.ts | 16 + types/react-select/lib/stateManager.d.ts | 36 + types/react-select/lib/styles.d.ts | 99 +++ types/react-select/lib/theme.d.ts | 53 ++ types/react-select/lib/types.d.ts | 100 +++ types/react-select/lib/utils.d.ts | 121 ++++ types/react-select/test/AtlaskitDummy.ts | 11 + types/react-select/test/ChronoNodeDummy.ts | 1 + types/react-select/test/data.ts | 132 ++++ .../test/examples/AccessingInternals.tsx | 114 +++ .../test/examples/AnimatedMulti.tsx | 17 + .../test/examples/AsyncCallbacks.tsx | 42 ++ .../test/examples/AsyncCreatable.tsx | 28 + .../react-select/test/examples/AsyncMulti.tsx | 39 + .../test/examples/AsyncPromises.tsx | 34 + .../test/examples/BasicGrouped.tsx | 37 + .../react-select/test/examples/BasicMulti.tsx | 15 + .../test/examples/BasicSingle.tsx | 101 +++ .../test/examples/ControlledMenu.tsx | 42 ++ .../test/examples/CreatableAdvanced.tsx | 70 ++ .../test/examples/CreatableInputOnly.tsx | 72 ++ .../test/examples/CreatableMulti.tsx | 22 + .../test/examples/CreatableSingle.tsx | 29 + .../test/examples/CreateFilter.tsx | 85 +++ .../test/examples/CustomClearIndicator.tsx | 35 + .../test/examples/CustomControl.tsx | 32 + .../test/examples/CustomDropdownIndicator.tsx | 24 + .../test/examples/CustomFilterOptions.tsx | 34 + .../test/examples/CustomGetOptionLabel.tsx | 23 + .../test/examples/CustomGroup.tsx | 24 + .../test/examples/CustomGroupHeading.tsx | 31 + .../examples/CustomIndicatorSeparator.tsx | 27 + .../examples/CustomIndicatorsContainer.tsx | 21 + .../test/examples/CustomInput.tsx | 27 + .../test/examples/CustomIsOptionDisabled.tsx | 21 + .../test/examples/CustomLoadingIndicator.tsx | 47 ++ .../test/examples/CustomLoadingMessage.tsx | 50 ++ .../react-select/test/examples/CustomMenu.tsx | 37 + .../test/examples/CustomMenuList.tsx | 29 + .../examples/CustomMultiValueContainer.tsx | 23 + .../test/examples/CustomMultiValueLabel.tsx | 23 + .../test/examples/CustomMultiValueRemove.tsx | 25 + .../test/examples/CustomNoOptionsMessage.tsx | 31 + .../test/examples/CustomOption.tsx | 22 + .../test/examples/CustomPlaceholder.tsx | 19 + .../test/examples/CustomSelectContainer.tsx | 24 + .../test/examples/CustomSingleValue.tsx | 25 + .../test/examples/CustomValueContainer.tsx | 28 + .../test/examples/Experimental.tsx | 211 ++++++ .../react-select/test/examples/MenuPortal.tsx | 91 +++ .../test/examples/OnSelectResetsInput.tsx | 47 ++ types/react-select/test/examples/Popout.tsx | 128 ++++ .../test/examples/StyledMulti.tsx | 53 ++ .../test/examples/StyledSingle.tsx | 51 ++ types/react-select/test/styled-components.tsx | 17 + types/react-select/tsconfig.json | 97 ++- types/react-select/tslint.json | 4 +- types/react-select/v1/index.d.ts | 654 +++++++++++++++++ .../{ => v1}/lib/Option/index.d.ts | 0 .../lib/utils/defaultMenuRenderer/index.d.ts | 0 .../{ => v1}/react-select-tests.tsx | 0 types/react-select/v1/tsconfig.json | 35 + types/react-select/v1/tslint.json | 1 + types/react-virtualized-select/tsconfig.json | 9 +- 90 files changed, 4716 insertions(+), 662 deletions(-) create mode 100644 types/react-select/lib/Async.d.ts create mode 100644 types/react-select/lib/AsyncCreatable.d.ts create mode 100644 types/react-select/lib/Creatable.d.ts create mode 100644 types/react-select/lib/Select.d.ts create mode 100644 types/react-select/lib/accessibility/index.d.ts create mode 100644 types/react-select/lib/animated/Input.d.ts create mode 100644 types/react-select/lib/animated/MultiValue.d.ts create mode 100644 types/react-select/lib/animated/Placeholder.d.ts create mode 100644 types/react-select/lib/animated/SingleValue.d.ts create mode 100644 types/react-select/lib/animated/ValueContainer.d.ts create mode 100644 types/react-select/lib/animated/index.d.ts create mode 100644 types/react-select/lib/animated/transitions.d.ts create mode 100644 types/react-select/lib/builtins.d.ts create mode 100644 types/react-select/lib/components/Control.d.ts create mode 100644 types/react-select/lib/components/Group.d.ts create mode 100644 types/react-select/lib/components/Input.d.ts create mode 100644 types/react-select/lib/components/Menu.d.ts create mode 100644 types/react-select/lib/components/MultiValue.d.ts create mode 100644 types/react-select/lib/components/Option.d.ts create mode 100644 types/react-select/lib/components/Placeholder.d.ts create mode 100644 types/react-select/lib/components/SingleValue.d.ts create mode 100644 types/react-select/lib/components/containers.d.ts create mode 100644 types/react-select/lib/components/index.d.ts create mode 100644 types/react-select/lib/components/indicators.d.ts create mode 100644 types/react-select/lib/diacritics.d.ts create mode 100644 types/react-select/lib/filters.d.ts create mode 100644 types/react-select/lib/stateManager.d.ts create mode 100644 types/react-select/lib/styles.d.ts create mode 100644 types/react-select/lib/theme.d.ts create mode 100644 types/react-select/lib/types.d.ts create mode 100644 types/react-select/lib/utils.d.ts create mode 100644 types/react-select/test/AtlaskitDummy.ts create mode 100644 types/react-select/test/ChronoNodeDummy.ts create mode 100644 types/react-select/test/data.ts create mode 100644 types/react-select/test/examples/AccessingInternals.tsx create mode 100644 types/react-select/test/examples/AnimatedMulti.tsx create mode 100644 types/react-select/test/examples/AsyncCallbacks.tsx create mode 100644 types/react-select/test/examples/AsyncCreatable.tsx create mode 100644 types/react-select/test/examples/AsyncMulti.tsx create mode 100644 types/react-select/test/examples/AsyncPromises.tsx create mode 100644 types/react-select/test/examples/BasicGrouped.tsx create mode 100644 types/react-select/test/examples/BasicMulti.tsx create mode 100644 types/react-select/test/examples/BasicSingle.tsx create mode 100644 types/react-select/test/examples/ControlledMenu.tsx create mode 100644 types/react-select/test/examples/CreatableAdvanced.tsx create mode 100644 types/react-select/test/examples/CreatableInputOnly.tsx create mode 100644 types/react-select/test/examples/CreatableMulti.tsx create mode 100644 types/react-select/test/examples/CreatableSingle.tsx create mode 100644 types/react-select/test/examples/CreateFilter.tsx create mode 100644 types/react-select/test/examples/CustomClearIndicator.tsx create mode 100644 types/react-select/test/examples/CustomControl.tsx create mode 100644 types/react-select/test/examples/CustomDropdownIndicator.tsx create mode 100644 types/react-select/test/examples/CustomFilterOptions.tsx create mode 100644 types/react-select/test/examples/CustomGetOptionLabel.tsx create mode 100644 types/react-select/test/examples/CustomGroup.tsx create mode 100644 types/react-select/test/examples/CustomGroupHeading.tsx create mode 100644 types/react-select/test/examples/CustomIndicatorSeparator.tsx create mode 100644 types/react-select/test/examples/CustomIndicatorsContainer.tsx create mode 100644 types/react-select/test/examples/CustomInput.tsx create mode 100644 types/react-select/test/examples/CustomIsOptionDisabled.tsx create mode 100644 types/react-select/test/examples/CustomLoadingIndicator.tsx create mode 100644 types/react-select/test/examples/CustomLoadingMessage.tsx create mode 100644 types/react-select/test/examples/CustomMenu.tsx create mode 100644 types/react-select/test/examples/CustomMenuList.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueContainer.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueLabel.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueRemove.tsx create mode 100644 types/react-select/test/examples/CustomNoOptionsMessage.tsx create mode 100644 types/react-select/test/examples/CustomOption.tsx create mode 100644 types/react-select/test/examples/CustomPlaceholder.tsx create mode 100644 types/react-select/test/examples/CustomSelectContainer.tsx create mode 100644 types/react-select/test/examples/CustomSingleValue.tsx create mode 100644 types/react-select/test/examples/CustomValueContainer.tsx create mode 100644 types/react-select/test/examples/Experimental.tsx create mode 100644 types/react-select/test/examples/MenuPortal.tsx create mode 100644 types/react-select/test/examples/OnSelectResetsInput.tsx create mode 100644 types/react-select/test/examples/Popout.tsx create mode 100644 types/react-select/test/examples/StyledMulti.tsx create mode 100644 types/react-select/test/examples/StyledSingle.tsx create mode 100644 types/react-select/test/styled-components.tsx create mode 100644 types/react-select/v1/index.d.ts rename types/react-select/{ => v1}/lib/Option/index.d.ts (100%) rename types/react-select/{ => v1}/lib/utils/defaultMenuRenderer/index.d.ts (100%) rename types/react-select/{ => v1}/react-select-tests.tsx (100%) create mode 100644 types/react-select/v1/tsconfig.json create mode 100644 types/react-select/v1/tslint.json diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index 31ff0db561..9c4728254c 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -1,654 +1,21 @@ -// Type definitions for react-select 1.3 -// Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo -// Gilad Gray -// Izaak Baker -// Tadas Dailyda -// Mark Vujevits -// Mike Deverell -// MartynasZilinskas -// Onat Yigit Mercan -// Ian Johnson -// Anton Novik -// David Schkalee -// Arthur Udalov -// Sebastian Silbermann -// Endurance Idehen -// Guillaume Chartier +// Type definitions for react-select 2.0 +// Project: https://github.com/JedWatson/react-select#readme +// Definitions by: Claas Ahlrichs +// Jon Freedman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.9 -import * as React from 'react'; +import SelectBase from './lib/Select'; +import { StateManager } from './lib/stateManager'; -export default class ReactSelectClass extends React.Component> { - focus(): void; - setValue(value: Option): void; -} -// Other components -export class Creatable extends React.Component> { } -export class Async extends React.Component> { } -export class AsyncCreatable extends React.Component> { } +export default SelectBase; +// export default StateManager; -export type OptionComponentType = React.ComponentType>; -export type ValueComponentType = React.ComponentType>; - -export type HandlerRendererResult = JSX.Element | null | false; - -// Handlers -export type FocusOptionHandler = (option: Option) => void; -export type SelectValueHandler = (option: Option) => void; -export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; -export type ClearRendererHandler = () => HandlerRendererResult; -export type FilterOptionHandler = (option: Option, filter: string) => boolean; -export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; -export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; -export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; -export type OnCloseHandler = () => void; -export type OnInputChangeHandler = (inputValue: string) => string; -export type OnInputKeyDownHandler = React.KeyboardEventHandler; -export type OnMenuScrollToBottomHandler = () => void; -export type OnOpenHandler = () => void; -export type OnFocusHandler = React.FocusEventHandler; -export type OnBlurHandler = React.FocusEventHandler; -export type OptionRendererHandler = (option: Option) => HandlerRendererResult; -export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; -export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; -export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; -export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; -export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; -export type PromptTextCreatorHandler = (filterText: string) => string; -export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; - -export type OnChangeSingleHandler = OnChangeHandler>; -export type OnChangeMultipleHandler = OnChangeHandler>; -export type OnChangeHandler | Options> = (newValue: TOption | null) => void; -export type OnNewOptionClickHandler = (option: Option) => void; - -export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; -export type LoadOptionsAsyncHandler = (input: string) => Promise>; -export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; - -export interface AutocompleteResult { - /** The search-results to be displayed */ - options: Options; - /** - * Should be set to true, if and only if a longer query with the same prefix - * would return a subset of the results - * If set to true, more specific queries will not be sent to the server. - */ - complete: boolean; -} - -export type Options = Array>; - -export interface Option { - /** Text for rendering */ - label?: string; - /** Value for searching */ - value?: TValue; - /** - * Allow this option to be cleared - * @default true - */ - clearableValue?: boolean; - /** - * Do not allow this option to be selected - * @default false - */ - disabled?: boolean; - /** - * In the event that a custom menuRenderer is provided, Option should be able - * to accept arbitrary key-value pairs. See react-virtualized-select. - */ - [property: string]: any; -} - -export type OptionValues = string | number | boolean; - -export interface MenuRendererProps { - /** - * The currently focused option; should be visible in the menu by default. - * default {} - */ - focusedOption: Option; - - /** - * Callback to focus a new option; receives the option as a parameter. - */ - focusOption: FocusOptionHandler; - - /** - * Option labels are accessible with this string key. - */ - labelKey: string; - - /** - * Ordered array of options to render. - */ - options: Options; - - /** - * Callback to select a new option; receives the option as a parameter. - */ - selectValue: SelectValueHandler; - - /** - * Array of currently selected options. - */ - valueArray: Options; - - /** - * Callback to remove selection from option; receives the option as a parameter. - */ - removeValue: SelectValueHandler; - - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer: OptionRendererHandler; -} - -export interface OptionComponentProps { - /** - * Classname(s) to apply to the option component. - */ - className?: string; - - /** - * Currently focused option. - */ - focusOption?: Option; - - inputValue?: string; - instancePrefix?: string; - - /** - * True if this option is disabled. - */ - isDisabled?: boolean; - - /** - * True if this option is focused. - */ - isFocused?: boolean; - - /** - * True if this option is selected. - */ - isSelected?: boolean; - - /** - * Callback to be invoked when this option is focused. - */ - onFocus?: (option: Option, event: any) => void; - - /** - * Callback to be invoked when this option is selected. - */ - onSelect?: (option: Option, event: any) => void; - - /** - * Option to be rendered by this component. - */ - option: Option; - - /** - * Index of the option being rendered in the list - */ - optionIndex?: number; - - /** - * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one - * being rendered) - */ - removeValue?: (value: TValue | TValue[]) => void; - - /** - * Callback to invoke to select an option. (Not necessarily the one being rendered) - */ - selectValue?: (value: TValue | TValue[]) => void; -} - -export interface ArrowRendererProps { - /** - * Arrow mouse down event handler. - */ - onMouseDown: React.MouseEventHandler; - - /** - * whether the Select is open or not. - */ - isOpen: boolean; -} - -export interface ValueComponentProps { - disabled: ReactSelectProps['disabled']; - id: string; - instancePrefix: string; - onClick: OnValueClickHandler | null; - onRemove?: SelectValueHandler; - placeholder: ReactSelectProps['placeholder']; - value: Option; - values?: Array>; -} - -export interface ReactSelectProps extends React.Props> { - /** - * text to display when `allowCreate` is true. - * @default 'Add "{label}"?' - */ - addLabelText?: string; - /** - * renders a custom drop-down arrow to be shown in the right-hand side of the select. - * @default undefined - */ - arrowRenderer?: ArrowRendererHandler | null; - /** - * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. - * @default false - */ - autoBlur?: boolean; - /** - * autofocus the component on mount - * @deprecated. Use autoFocus instead - * @default false - */ - autofocus?: boolean; - /** - * autofocus the component on mount - * @default false - */ - autoFocus?: boolean; - /** - * If enabled, the input will expand as the length of its value increases - */ - autosize?: boolean; - /** - * whether pressing backspace removes the last item when there is no input value - * @default true - */ - backspaceRemoves?: boolean; - /** - * Message to use for screenreaders to press backspace to remove the current item - * {label} is replaced with the item label - * @default "Press backspace to remove..." - */ - backspaceToRemoveMessage?: string; - /** - * CSS className for the outer element - */ - className?: string; - /** - * Prefix prepended to element default className if no className is defined - */ - classNamePrefix?: string; - /** - * title for the "clear" control when `multi` is true - * @default "Clear all" - */ - clearAllText?: string; - /** - * Renders a custom clear to be shown in the right-hand side of the select when clearable true - * @default undefined - */ - clearRenderer?: ClearRendererHandler; - /** - * title for the "clear" control - * @default "Clear value" - */ - clearValueText?: string; - /** - * whether to close the menu when a value is selected - * @default true - */ - closeOnSelect?: boolean; - /** - * whether it is possible to reset value. if enabled, an X button will appear at the right side. - * @default true - */ - clearable?: boolean; - /** - * whether backspace removes an item if there is no text input - * @default true - */ - deleteRemoves?: boolean; - /** - * delimiter to use to join multiple values - * @default "," - */ - delimiter?: string; - /** - * whether the Select is disabled or not - * @default false - */ - disabled?: boolean; - /** - * whether escape clears the value when the menu is closed - * @default true - */ - escapeClearsValue?: boolean; - /** - * method to filter a single option - */ - filterOption?: FilterOptionHandler; - /** - * method to filter the options array - */ - filterOptions?: FilterOptionsHandler; - /** - * id for the underlying HTML input element - * @default undefined - */ - id?: string; - /** - * whether to strip diacritics when filtering - * @default true - */ - ignoreAccents?: boolean; - /** - * whether to perform case-insensitive filtering - * @default true - */ - ignoreCase?: boolean; - /** - * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} - * @default {} - */ - inputProps?: { [key: string]: any }; - /** - * renders a custom input - */ - inputRenderer?: InputRendererHandler; - /** - * allows for synchronization of component id's on server and client. - * @see https://github.com/JedWatson/react-select/pull/1105 - */ - instanceId?: string; - /** - * whether the Select is loading externally or not (such as options being loaded). - * if true, a loading spinner will be shown at the right side. - * @default false - */ - isLoading?: boolean; - /** - * (legacy mode) joins multiple values into a single form field with the delimiter - * @default false - */ - joinValues?: boolean; - /** - * the option property to use for the label - * @default "label" - */ - labelKey?: string; - /** - * (any, start) match the start or entire string when filtering - * @default "any" - */ - matchPos?: string; - /** - * (any, label, value) which option property to filter on - * @default "any" - */ - matchProp?: string; - /** - * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport - * @default 0 - */ - menuBuffer?: number; - /** - * optional style to apply to the menu container - */ - menuContainerStyle?: React.CSSProperties; - /** - * renders a custom menu with options - */ - menuRenderer?: MenuRendererHandler; - /** - * optional style to apply to the menu - */ - menuStyle?: React.CSSProperties; - /** - * multi-value input - * @default false - */ - multi?: boolean; - /** - * field name, for hidden `` tag - */ - name?: string; - /** - * placeholder displayed when there are no matching search results or a falsy value to hide it - * @default "No results found" - */ - noResultsText?: string | JSX.Element; - /** - * onBlur handler: function (event) {} - */ - onBlur?: OnBlurHandler; - /** - * whether to clear input on blur or not - * @default true - */ - onBlurResetsInput?: boolean; - /** - * whether the input value should be reset when options are selected. - * Also input value will be set to empty if 'onSelectResetsInput=true' and - * Select will get new value that not equal previous value. - * @default true - */ - onSelectResetsInput?: boolean; - /** - * whether to clear input when closing the menu through the arrow - * @default true - */ - onCloseResetsInput?: boolean; - /** - * onChange handler: function (newValue) {} - */ - onChange?: OnChangeHandler; - /** - * fires when the menu is closed - */ - onClose?: OnCloseHandler; - /** - * onFocus handler: function (event) {} - */ - onFocus?: OnFocusHandler; - /** - * onInputChange handler: function (inputValue) {} - */ - onInputChange?: OnInputChangeHandler; - /** - * onInputKeyDown handler: function (keyboardEvent) {} - */ - onInputKeyDown?: OnInputKeyDownHandler; - /** - * fires when the menu is scrolled to the bottom; can be used to paginate options - */ - onMenuScrollToBottom?: OnMenuScrollToBottomHandler; - /** - * fires when the menu is opened - */ - onOpen?: OnOpenHandler; - /** - * boolean to enable opening dropdown when focused - * @default false - */ - openOnClick?: boolean; - /** - * open the options menu when the input gets focus (requires searchable = true) - * @default true - */ - openOnFocus?: boolean; - /** - * className to add to each option component - */ - optionClassName?: string; - /** - * option component to render in dropdown - */ - optionComponent?: OptionComponentType; - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer?: OptionRendererHandler; - /** - * array of Select options - * @default false - */ - options?: Options; - /** - * number of options to jump when using page up/down keys - * @default 5 - */ - pageSize?: number; - /** - * field placeholder, displayed when there's no value - * @default "Select..." - */ - placeholder?: string | JSX.Element; - /** - * whether the selected option is removed from the dropdown on multi selects - * @default true - */ - removeSelected?: boolean; - /** - * applies HTML5 required attribute when needed - * @default false - */ - required?: boolean; - /** - * value to use when you clear the control - */ - resetValue?: any; - /** - * use react-select in right-to-left direction - * @default false - */ - rtl?: boolean; - /** - * whether the viewport will shift to display the entire menu when engaged - * @default true - */ - scrollMenuIntoView?: boolean; - /** - * whether to enable searching feature or not - * @default true; - */ - searchable?: boolean; - /** - * whether to select the currently focused value when the [tab] key is pressed - */ - tabSelectsValue?: boolean; - /** - * initial field value - */ - value?: Option | Options | string | string[] | number | number[] | boolean; - /** - * the option property to use for the value - * @default "value" - */ - valueKey?: string; - /** - * function which returns a custom way to render the value selected - * @default false - */ - valueRenderer?: ValueRendererHandler; - /** - * optional style to apply to the control - */ - style?: React.CSSProperties; - - /** - * optional tab index of the control - */ - tabIndex?: string | number; - - /** - * value component to render - */ - valueComponent?: ValueComponentType; - - /** - * optional style to apply to the component wrapper - */ - wrapperStyle?: React.CSSProperties; - - /** - * onClick handler for value labels: function (value, event) {} - */ - onValueClick?: OnValueClickHandler; - - /** - * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false - */ - simpleValue?: boolean; -} - -export interface ReactCreatableSelectProps extends ReactSelectProps { - /** - * Searches for any matching option within the set of options. This function prevents - * duplicate options from being created. - */ - isOptionUnique?: IsOptionUniqueHandler; - - /** - * Determines if the current input text represents a valid option. - */ - isValidNewOption?: IsValidNewOptionHandler; - - /** - * factory to create new options - */ - newOptionCreator?: NewOptionCreatorHandler; - - /** - * Creates prompt/placeholder for option text. - */ - promptTextCreator?: PromptTextCreatorHandler; - - /** - * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. - */ - shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; - - /** - * new option click handler: function (option) {} - */ - onNewOptionClick?: OnNewOptionClickHandler; - - /** - * true: Show new option at top of list - * false: Show new option at bottom of list - * @default true - */ - showNewOptionAtTop?: boolean; -} - -export interface ReactAsyncSelectProps extends ReactSelectProps { - /** - * Whether to auto-load the default async options set. - */ - autoload?: boolean; - - /** - * object to use to cache results; can be null to disable cache - */ - cache?: { [key: string]: any } | boolean; - - /** - * function to call to load options asynchronously - */ - loadOptions: LoadOptionsHandler; - - /** - * replaces the placeholder while options are loading - */ - loadingPlaceholder?: string | JSX.Element; - /** - * displayed in the drop down list when the user did not type anything yet - */ - searchPromptText?: string; -} - -export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; +export { SelectBase }; +export { default as Async } from './lib/Async'; +export { default as AsyncCreatable } from './lib/AsyncCreatable'; +export { default as Creatable } from './lib/Creatable'; +export { createFilter } from './lib/filters'; +export { default as makeAnimated } from './lib/animated/index'; +export { components } from './lib/components/index'; +export { mergeStyles } from './lib/styles'; diff --git a/types/react-select/lib/Async.d.ts b/types/react-select/lib/Async.d.ts new file mode 100644 index 0000000000..8acc5532b7 --- /dev/null +++ b/types/react-select/lib/Async.d.ts @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { handleInputChange } from './utils'; +import manageState from './stateManager'; +import { OptionsType, InputActionMeta } from './types'; + +export interface AsyncProps { + /* The default set of options to show before the user starts searching. When + set to `true`, the results for loadOptions('') will be autoloaded. */ + defaultOptions: OptionsType | boolean; + /* Function that returns a promise, which is the set of options to be used + once the promise resolves. */ + loadOptions: (inputValue: string, callback: ((options: OptionsType) => void)) => Promise | void; + /* If cacheOptions is truthy, then the loaded data will be cached. The cache + will remain until `cacheOptions` changes value. */ + cacheOptions: any; +} + +export type Props = SelectProps & AsyncProps; + +export const defaultProps: Props; + +export interface State { + defaultOptions?: OptionsType; + inputValue: string; + isLoading: boolean; + loadedInputValue?: string; + loadedOptions: OptionsType; + passEmptyOptions: boolean; +} + +export class Async extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; +} + +export function makeAsyncSelect(SelectComponent: React.ComponentType): Async; + +export default Async; diff --git a/types/react-select/lib/AsyncCreatable.d.ts b/types/react-select/lib/AsyncCreatable.d.ts new file mode 100644 index 0000000000..5fbdd8e52c --- /dev/null +++ b/types/react-select/lib/AsyncCreatable.d.ts @@ -0,0 +1,25 @@ +import { Component, Ref as ElementRef } from 'react'; +import { Props as AsyncProps, State as AsyncState } from './Async'; +import { Props as CreatableProps, State as CreatableState } from './Creatable'; +import { OptionsType, ValueType, ActionMeta, InputActionMeta } from './types'; +import { cleanValue } from './utils'; + +type Props = AsyncProps & CreatableProps; + +type State = AsyncState & CreatableState; + +export class AsyncCreatable extends Component, State> { + static defaultProps: Props; + select: ElementRef; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; +} + +export default AsyncCreatable; diff --git a/types/react-select/lib/Creatable.d.ts b/types/react-select/lib/Creatable.d.ts new file mode 100644 index 0000000000..c194441a8b --- /dev/null +++ b/types/react-select/lib/Creatable.d.ts @@ -0,0 +1,49 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { OptionsType, ValueType, ActionMeta } from './types'; +import { cleanValue } from './utils'; +import manageState from './stateManager'; + +export interface CreatableProps { + /* Allow options to be created while the `isLoading` prop is true. Useful to + prevent the "create new ..." option being displayed while async results are + still being loaded. */ + allowCreateWhileLoading?: boolean; + /* Gets the label for the "create new ..." option in the menu. Is given the + current input value. */ + formatCreateLabel?: (inputValue: string) => Node; + /* Determines whether the "create new ..." option should be displayed based on + the current input value, select value and options array. */ + isValidNewOption?: (a: string, b: ValueType, c: OptionsType) => boolean; + /* Returns the data for the new option when it is created. Used to display the + value, and is passed to `onChange`. */ + getNewOptionData?: (a: string, b: Node) => OptionType; + /* If provided, this will be called with the input value when a new option is + created, and `onChange` will **not** be called. Use this when you need more + control over what happens when new options are created. */ + onCreateOption?: (inputValue: string) => void; + /* Sets the position of the createOption element in your options list. Defaults to 'last' */ + createOptionPosition?: 'first' | 'last'; +} + +export type Props = SelectProps & CreatableProps; + +export const defaultProps: Props; + +export interface State { + newOption: OptionType | undefined; + options: OptionsType; +} + +export class Creatable extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; + focus(): void; + blur(): void; +} + +export function makeCreatableSelect(SelectComponent: React.ComponentType): Creatable; + +export default Creatable; diff --git a/types/react-select/lib/Select.d.ts b/types/react-select/lib/Select.d.ts new file mode 100644 index 0000000000..0298ea0288 --- /dev/null +++ b/types/react-select/lib/Select.d.ts @@ -0,0 +1,419 @@ +import * as React from 'react'; + +import { Option } from './filters'; +import { + InstructionsContext, + ValueEventContext, +} from './accessibility/index'; + +import { + classNames, + noop, + scrollIntoView, +} from './utils'; + +import { + formatGroupLabel, + getOptionLabel, + getOptionValue, + isOptionDisabled, +} from './builtins'; + +import { + PlaceholderOrValue, + SelectComponents, + SelectComponentsConfig, +} from './components/index'; +import { StylesConfig } from './styles'; + +import { + ActionMeta, + ActionTypes, + FocusDirection, + FocusEventHandler, + GroupType, + InputActionMeta, + KeyboardEventHandler, + MenuPlacement, + MenuPosition, + OptionsType, + ValueType, + GroupedOptionsType, +} from './types'; + +export type MouseOrTouchEvent = + | React.MouseEvent + | React.TouchEvent; +export type FormatOptionLabelContext = 'menu' | 'value'; +export interface FormatOptionLabelMeta { + context: FormatOptionLabelContext; + inputValue: string; + selectValue: ValueType; +} + +export interface Props { + /* Aria label (for assistive tech) */ + 'aria-label'?: string; + /* HTML ID of an element that should be used as the label (for assistive tech) */ + 'aria-labelledby'?: string; + /* Focus the control when it is mounted */ + autoFocus?: boolean; + /* Remove the currently focused option when the user presses backspace */ + backspaceRemovesValue?: boolean; + /* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */ + blurInputOnSelect?: boolean; + /* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */ + captureMenuScroll?: boolean; + /* className attribute applied to the outer component */ + className?: string; + /* classNamePrefix attribute used as a base for inner component classNames */ + classNamePrefix?: string | null; + /* Close the select menu when the user selects an option */ + closeMenuOnSelect?: boolean; + /* + If `true`, close the select menu when the user scrolls the document/body. + + If a function, takes a standard javascript `ScrollEvent` you return a boolean: + + `true` => The menu closes + + `false` => The menu stays open + + This is useful when you have a scrollable modal and want to portal the menu out, + but want to avoid graphical issues. + */ + closeMenuOnScroll?: boolean | EventListener; + /* + This complex object includes all the compositional components that are used + in `react-select`. If you wish to overwrite a component, pass in an object + with the appropriate namespace. + + If you only wish to restyle a component, we recommend using the `styles` prop + instead. For a list of the components that can be passed in, and the shape + that will be passed to them, see [the components docs](/api#components) + */ + components?: SelectComponentsConfig; + /* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */ + controlShouldRenderValue?: boolean; + /* Delimiter used to join multiple values into a single HTML Input value */ + delimiter?: string; + /* Clear all values when the user presses escape AND the menu is closed */ + escapeClearsValue?: boolean; + /* Custom method to filter whether an option should be displayed in the menu */ + filterOption?: (( + option: Option, + rawInput: string + ) => boolean) | null; + /* Formats group labels in the menu as React components */ + formatGroupLabel?: typeof formatGroupLabel; + /* Formats option labels in the menu and control as React components */ + formatOptionLabel?: (a: OptionType, b: FormatOptionLabelMeta) => Node; + /* Resolves option data to a string to be displayed as the label by components */ + getOptionLabel?: typeof getOptionLabel; + /* Resolves option data to a string to compare options and specify value attributes */ + getOptionValue?: typeof getOptionValue; + /* Hide the selected option from the menu */ + hideSelectedOptions?: boolean; + /* The id to set on the SelectContainer component. */ + id?: string; + /* The value of the search input */ + inputValue?: string; + /* The id of the search input */ + inputId?: string; + /* Define an id prefix for the select components e.g. {your-id}-value */ + instanceId?: number | string; + /* Is the select value clearable */ + isClearable?: boolean; + /* Is the select disabled */ + isDisabled?: boolean; + /* Is the select in a state of loading (async) */ + isLoading?: boolean; + /* Override the built-in logic to detect whether an option is disabled */ + isOptionDisabled?: (a: OptionType, b: OptionsType) => boolean | false; + /* Override the built-in logic to detect whether an option is selected */ + isOptionSelected?: (a: OptionType, b: OptionsType) => boolean; + /* Support multiple selected options */ + isMulti?: boolean; + /* Is the select direction right-to-left */ + isRtl?: boolean; + /* Whether to enable search functionality */ + isSearchable?: boolean; + /* Async: Text to display when loading options */ + loadingMessage?: (obj: { inputValue: string }) => string | null; + /* Minimum height of the menu before flipping */ + minMenuHeight?: number; + /* Maximum height of the menu before scrolling */ + maxMenuHeight?: number; + /* Whether the menu is open */ + menuIsOpen?: boolean; + /* Default placement of the menu in relation to the control. 'auto' will flip + when there isn't enough space below the control. */ + menuPlacement?: MenuPlacement; + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition?: MenuPosition; + /* Whether the menu should use a portal, and where it should attach */ + menuPortalTarget?: HTMLElement | null; + /* Whether to block scroll events when the menu is open */ + menuShouldBlockScroll?: boolean; + /* Whether the menu should be scrolled into view when it opens */ + menuShouldScrollIntoView?: boolean; + /* Name of the HTML Input (optional - without this, no input will be rendered) */ + name?: string; + /* Text to display when there are no options */ + noOptionsMessage?: (obj: { inputValue: string }) => string | null; + /* Handle blur events on the control */ + onBlur?: FocusEventHandler; + /* Handle change events on the select */ + onChange?: (value: ValueType, action: ActionMeta) => void; + /* Handle focus events on the control */ + onFocus?: FocusEventHandler; + /* Handle change events on the input */ + onInputChange?: (newValue: string, actionMeta: InputActionMeta) => void; + /* Handle key down events on the select */ + onKeyDown?: KeyboardEventHandler; + /* Handle the menu opening */ + onMenuOpen?: () => void; + /* Handle the menu closing */ + onMenuClose?: () => void; + /* Fired when the user scrolls to the top of the menu */ + onMenuScrollToTop?: (event: React.SyntheticEvent) => void; + /* Fired when the user scrolls to the bottom of the menu */ + onMenuScrollToBottom?: (event: React.SyntheticEvent) => void; + /* Allows control of whether the menu is opened when the Select is focused */ + openMenuOnFocus?: boolean; + /* Allows control of whether the menu is opened when the Select is clicked */ + openMenuOnClick?: boolean; + /* Array of options that populate the select menu */ + options?: GroupedOptionsType | OptionsType; + /* Number of options to jump in menu when page{up|down} keys are used */ + pageSize?: number; + /* Placeholder text for the select value */ + placeholder?: string; + /* Status to relay to screen readers */ + screenReaderStatus?: (obj: { count: number }) => string; + /* Style modifier methods */ + styles?: StylesConfig; + /* Sets the tabIndex attribute on the input */ + tabIndex?: string; + /* Select the currently focused option when the user presses tab */ + tabSelectsValue?: boolean; + /* The value of the select; reflected by the selected option */ + value?: ValueType; + + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; +} + +export const defaultProps: Props; + +export interface MenuOptions { + render: OptionType[]; + focusable: OptionType[]; +} + +export interface State { + ariaLiveSelection: string; + ariaLiveContext: string; + inputIsHidden: boolean; + isFocused: boolean; + isComposing: boolean; + focusedOption: OptionType | null; + focusedValue: OptionType | null; + menuOptions: MenuOptions; + selectValue: OptionsType; +} + +export type ElRef = React.Ref; + +export default class Select extends React.Component, State> { + static defaultProps: Props; + + // Misc. Instance Properties + // ------------------------------ + + blockOptionHover: boolean; + clearFocusValueOnUpdate: boolean; + commonProps: any; // TODO + components: SelectComponents; + hasGroups: boolean; + initialTouchX: number; + initialTouchY: number; + inputIsHiddenAfterUpdate: boolean | null; + instancePrefix: string; + openAfterFocus: boolean; + scrollToFocusedOptionOnUpdate: boolean; + userIsDragging: boolean | null; + + // Refs + // ------------------------------ + + controlRef: ElRef; + getControlRef: (ref: HTMLElement) => void; + focusedOptionRef: ElRef; + getFocusedOptionRef: (ref: HTMLElement) => void; + menuListRef: ElRef; + getMenuListRef: (ref: HTMLElement) => void; + inputRef: ElRef; + getInputRef: (ref: HTMLElement) => void; + + // Lifecycle + // ------------------------------ + + cacheComponents: (components: SelectComponents) => void; + + // ============================== + // Consumer Handlers + // ============================== + + onMenuOpen(): void; + onMenuClose(): void; + onInputChange(newValue: string, actionMeta: InputActionMeta): void; + + // ============================== + // Methods + // ============================== + + focusInput(): void; + blurInput(): void; + + // aliased for consumers + focus(): void; + blur(): void; + + openMenu(focusOption: 'first' | 'last'): void; + focusValue(direction: 'previous' | 'next'): void; + + focusOption(direction: FocusDirection): void; + setValue: ( + newValue: ValueType, + action: ActionTypes, + option?: OptionType + ) => void; + selectOption: (newValue: OptionType) => void; + removeValue: (removedValue: OptionType) => void; + clearValue: () => void; + popValue: () => void; + + // ============================== + // Getters + // ============================== + + getCommonProps(): { + cx: any; + clearValue: () => void; + getStyles: (key: string, props: {}) => {}; + getValue: () => OptionType[]; + hasValue: boolean; + isMulti: boolean; + isRtl: boolean; + options: OptionsType; + selectOption: (newValue: OptionType) => void; + setValue: (newValue: ValueType, action: ActionTypes, option?: OptionType) => void; + selectProps: Readonly<{ + children?: Node; + }> & Readonly>; +}; + + getNextFocusedValue(nextSelectValue: OptionsType): OptionType; + + getNextFocusedOption(options: OptionsType): OptionType; + getOptionLabel: (data: OptionType) => string; + getOptionValue: (data: OptionType) => string; + getStyles: (key: string, props: {}) => {}; + getElementId: (element: 'group' | 'input' | 'listbox' | 'option') => string; + getActiveDescendentId: () => any; + + // ============================== + // Helpers + // ============================== + announceAriaLiveSelection: (props: { + event: string, + context: ValueEventContext, + }) => void; + announceAriaLiveContext: (props: { + event: string, + context?: InstructionsContext, + }) => void; + + hasValue(): boolean; + hasOptions(): boolean; + countOptions(): number; + isClearable(): boolean; + isOptionDisabled(option: OptionType, selectValue: OptionsType): boolean; + isOptionSelected(option: OptionType, selectValue: OptionsType): boolean; + filterOption(option: {}, inputValue: string): boolean; + formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): Node; + formatGroupLabel(data: GroupType): Node; + + // ============================== + // Mouse Handlers + // ============================== + + onMenuMouseDown: (event: React.MouseEvent) => void; + onMenuMouseMove: (event: React.MouseEvent) => void; + onControlMouseDown: (event: MouseOrTouchEvent) => void; + onDropdownIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onClearIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onScroll: (event: Event) => void; + + // ============================== + // Composition Handlers + // ============================== + + startListeningComposition(): void; + stopListeningComposition(): void; + onCompositionStart: () => void; + onCompositionEnd: () => void; + + // ============================== + // Touch Handlers + // ============================== + + startListeningToTouch(): void; + stopListeningToTouch(): void; + onTouchStart: (event: TouchEvent) => void; + onTouchMove: (event: TouchEvent) => void; + onTouchEnd: (event: TouchEvent) => void; + onControlTouchEnd: (event: React.TouchEvent) => void; + onClearIndicatorTouchEnd: (event: React.TouchEvent) => void; + onDropdownIndicatorTouchEnd: (event: React.TouchEvent) => void; + + // ============================== + // Focus Handlers + // ============================== + + handleInputChange: (event: React.KeyboardEvent) => void; + onInputFocus: (event: React.FocusEvent) => void; + onInputBlur: (event: React.FocusEvent) => void; + onOptionHover: (focusedOption: OptionType) => void; + shouldHideSelectedOptions: () => boolean; + + // ============================== + // Keyboard Handlers + // ============================== + + onKeyDown: (event: React.KeyboardEvent) => void; + + // ============================== + // Menu Options + // ============================== + + buildMenuOptions(props: Props, selectValue: OptionsType): MenuOptions; + + // ============================== + // Renderers + // ============================== + constructAriaLiveMessage(): string; + + renderInput(): Node; + renderPlaceholderOrValue(): PlaceholderOrValue | null; + renderClearIndicator(): Node; + renderLoadingIndicator(): Node; + renderIndicatorSeparator(): Node; + renderDropdownIndicator(): Node; + renderMenu(): Node; + renderFormField(): Node; + + renderLiveRegion(): Node; +} diff --git a/types/react-select/lib/accessibility/index.d.ts b/types/react-select/lib/accessibility/index.d.ts new file mode 100644 index 0000000000..633aaeda72 --- /dev/null +++ b/types/react-select/lib/accessibility/index.d.ts @@ -0,0 +1,10 @@ +export interface InstructionsContext { isSearchable?: boolean; isMulti?: boolean; label?: string; } +export interface ValueEventContext { value: string; } + +export function instructionsAriaMessage(event: any, context?: InstructionsContext): string; + +export function valueEventAriaMessage(event: any, context: ValueEventContext): string; + +export function valueFocusAriaMessage({ focusedValue, getOptionLabel, selectValue }: any): string; +export function optionFocusAriaMessage({ focusedOption, getOptionLabel, options }: any): string; +export function resultsAriaMessage({ inputValue, screenReaderMessage }: any): string; diff --git a/types/react-select/lib/animated/Input.d.ts b/types/react-select/lib/animated/Input.d.ts new file mode 100644 index 0000000000..ad752a96c5 --- /dev/null +++ b/types/react-select/lib/animated/Input.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { InputProps } from '../components/Input'; +import { BaseTransition } from './transitions'; +import { PropsWithInnerRef } from '../types'; + +export type AnimatedInputProps = BaseTransition & PropsWithInnerRef & InputProps; + +export function AnimatedInput(WrappedComponent: React.ComponentType): React.ComponentType; + +export default AnimatedInput; diff --git a/types/react-select/lib/animated/MultiValue.d.ts b/types/react-select/lib/animated/MultiValue.d.ts new file mode 100644 index 0000000000..8a8f37ad16 --- /dev/null +++ b/types/react-select/lib/animated/MultiValue.d.ts @@ -0,0 +1,12 @@ +import { ComponentType } from 'react'; +import { MultiValueProps } from '../components/MultiValue'; +import { Collapse, fn } from './transitions'; + +export type AnimatedMultiValueProps = { + in: boolean, + onExited: fn, +} & MultiValueProps; + +export function AnimatedMultiValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedMultiValue; diff --git a/types/react-select/lib/animated/Placeholder.d.ts b/types/react-select/lib/animated/Placeholder.d.ts new file mode 100644 index 0000000000..1dbd3ba203 --- /dev/null +++ b/types/react-select/lib/animated/Placeholder.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { PlaceholderProps } from '../components/Placeholder'; +import { Fade, collapseDuration } from './transitions'; + +export type AnimatedPlaceholderProps = PlaceholderProps; + +export function AnimatedPlaceholder(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedPlaceholder; diff --git a/types/react-select/lib/animated/SingleValue.d.ts b/types/react-select/lib/animated/SingleValue.d.ts new file mode 100644 index 0000000000..6cd1bea908 --- /dev/null +++ b/types/react-select/lib/animated/SingleValue.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { SingleValueProps } from '../components/SingleValue'; +import { Fade } from './transitions'; + +export type AnimatedSingleValueProps = SingleValueProps; + +export function AnimatedSingleValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedSingleValue; diff --git a/types/react-select/lib/animated/ValueContainer.d.ts b/types/react-select/lib/animated/ValueContainer.d.ts new file mode 100644 index 0000000000..6bd15c0c19 --- /dev/null +++ b/types/react-select/lib/animated/ValueContainer.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { TransitionGroup } from 'react-transition-group'; +import { ValueContainerProps } from '../components/containers'; + +export type AnimatedValueContainerProps = ValueContainerProps; + +export function AnimatedValueContainer(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedValueContainer; diff --git a/types/react-select/lib/animated/index.d.ts b/types/react-select/lib/animated/index.d.ts new file mode 100644 index 0000000000..6760d55e81 --- /dev/null +++ b/types/react-select/lib/animated/index.d.ts @@ -0,0 +1,17 @@ +import { ComponentType } from 'react'; +import { SelectComponents, defaultComponents } from '../components/index'; +import { default as AnimatedInput, AnimatedInputProps } from './Input'; +import { default as AnimatedMultiValue, AnimatedMultiValueProps } from './MultiValue'; +import { default as AnimatedPlaceholder, AnimatedPlaceholderProps } from './Placeholder'; +import { default as AnimatedSingleValue, AnimatedSingleValueProps } from './SingleValue'; +import { default as AnimatedValueContainer, AnimatedValueContainerProps } from './ValueContainer'; + +export function makeAnimated(externalComponents?: SelectComponents): SelectComponents; + +export const Input: ComponentType; +export const MultiValue: ComponentType>; +export const Placeholder: ComponentType>; +export const SingleValue: ComponentType>; +export const ValueContainer: ComponentType>; + +export default makeAnimated; diff --git a/types/react-select/lib/animated/transitions.d.ts b/types/react-select/lib/animated/transitions.d.ts new file mode 100644 index 0000000000..ee2bd3c83b --- /dev/null +++ b/types/react-select/lib/animated/transitions.d.ts @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Transition } from 'react-transition-group'; + +export type fn = () => void; +export interface BaseTransition { + /** Whether we are in a transition. */ + in: boolean; + /** Function to be called once transition finishes. */ + onExited: fn; +} + +// ============================== +// Fade Transition +// ============================== + +export type FadeProps = BaseTransition & { + component: React.ComponentType, + duration: number, +}; +export const Fade: React.ComponentType; + +// ============================== +// Collapse Transition +// ============================== + +export const collapseDuration: number; + +export type TransitionState = 'exiting' | 'exited'; +export type Width = number | 'auto'; +export interface CollapseProps { children: any; in: boolean; } +export interface CollapseState { width: Width; } + +// wrap each MultiValue with a collapse transition; decreases width until +// finally removing from DOM +export class Collapse extends React.Component { + duration: number; + transition: { + exiting: any, + exited: any, + }; + + // width must be calculated; cannot transition from `undefined` to `number` + getWidth: (ref: React.Ref) => void; + + // get base styles + getStyle: (width: Width) => any; + + // get transition styles + getTransition: (state: TransitionState) => any; +} diff --git a/types/react-select/lib/builtins.d.ts b/types/react-select/lib/builtins.d.ts new file mode 100644 index 0000000000..b1e1c37cc8 --- /dev/null +++ b/types/react-select/lib/builtins.d.ts @@ -0,0 +1,10 @@ +import { ReactNode as Node } from 'react'; +import { GroupType } from './types'; + +export function formatGroupLabel(group: GroupType): Node; + +export function getOptionLabel(option: any): string; + +export function getOptionValue(option: any): string; + +export function isOptionDisabled(option: any): boolean; diff --git a/types/react-select/lib/components/Control.d.ts b/types/react-select/lib/components/Control.d.ts new file mode 100644 index 0000000000..019f75bee9 --- /dev/null +++ b/types/react-select/lib/components/Control.d.ts @@ -0,0 +1,29 @@ +import { ComponentType, ReactNode as Node, Ref as ElementRef } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles } from '../types'; + +interface State { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the select is focused. */ + isFocused: boolean; +} + +export type ControlProps = CommonProps & + PropsWithStyles & + State & { + /** Children to render. */ + children: Node, + innerRef: ElementRef, + /** The mouse down event and the innerRef to pass down to the controller element. */ + innerProps: { + onMouseDown: (event: React.MouseEvent) => void, + }, + }; + +export function css(state: State): any; // TODO css type + +declare const Control: ComponentType>; + +export default Control; diff --git a/types/react-select/lib/components/Group.d.ts b/types/react-select/lib/components/Group.d.ts new file mode 100644 index 0000000000..d37964c0b4 --- /dev/null +++ b/types/react-select/lib/components/Group.d.ts @@ -0,0 +1,24 @@ +import { ReactNode as Node, ComponentType } from 'react'; + +import { spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface ComponentProps { + /** The children to be rendered. */ + children: Node; + /** Component to wrap the label, recieves headingProps. */ + Heading: ComponentType; + /** Label to be displayed in the heading component. */ + label: Node; +} +export type GroupProps = CommonProps & ComponentProps; + +export function groupCSS(): any; // TODO css type + +export const Group: ComponentType>; + +export function groupHeadingCSS(): any; // TODO css type + +export const GroupHeading: ComponentType; + +export default Group; diff --git a/types/react-select/lib/components/Input.d.ts b/types/react-select/lib/components/Input.d.ts new file mode 100644 index 0000000000..16f07491d2 --- /dev/null +++ b/types/react-select/lib/components/Input.d.ts @@ -0,0 +1,23 @@ +import { ComponentType, Ref as ElementRef } from 'react'; + +import { colors, spacing } from '../theme'; + +import { PropsWithStyles, ClassNamesState } from '../types'; + +export type InputProps = PropsWithStyles & { + cx: (a: string | null, b: ClassNamesState, c: string) => string | void, + /** Reference to the internal element */ + innerRef: (element: ElementRef) => void, + /** Set whether the input should be visible. Does not affect input size. */ + isHidden: boolean, + /** Whether the input is disabled */ + isDisabled?: boolean, + className?: string, +}; + +export function inputCSS(props: InputProps): any; // TODO css type; +export function inputStyle(isHidden: boolean): any; // TODO css type + +export const Input: ComponentType; + +export default Input; diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts new file mode 100644 index 0000000000..85b5ef0fae --- /dev/null +++ b/types/react-select/lib/components/Menu.d.ts @@ -0,0 +1,158 @@ +import { + Component, + ReactElement, + Ref as ElementRef, + ReactNode as Node, + ComponentType +} from 'react'; +import { createPortal } from 'react-dom'; + +import { + animatedScrollTo, + getBoundingClientObj, + RectType, + getScrollParent, + getScrollTop, + scrollTo, +} from '../utils'; +import { borderRadius, colors, spacing } from '../theme'; +import { + InnerRef, + MenuPlacement, + MenuPosition, + CommonProps, +} from '../types'; + +// ============================== +// Menu +// ============================== + +// Get Menu Placement +// ------------------------------ + +interface MenuState { placement: 'bottom' | 'top' | null; maxHeight: number; } +interface PlacementArgs { + maxHeight: number; + menuEl: ElementRef; + minHeight: number; + placement: 'bottom' | 'top' | 'auto'; + shouldScroll: boolean; + isFixedPosition: boolean; +} + +export function getMenuPlacement(args: PlacementArgs): MenuState; + +// Menu Component +// ------------------------------ + +export type MenuProps = CommonProps & { + /** The children to be rendered. */ + children: ReactElement, + /** Callback to update the portal after possible flip. */ + getPortalPlacement: (state: MenuState) => void, + /** Props to be passed to the menu wrapper. */ + innerProps: object, + /** Set the maximum height of the menu. */ + maxMenuHeight: number, + /** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */ + menuPlacement: MenuPlacement, + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition: MenuPosition, + /** Set the minimum height of the menu. */ + minMenuHeight: number, + /** Set whether the page should scroll to show the menu. */ + menuShouldScrollIntoView: boolean, +}; + +export function menuCSS(state: MenuState): any; // TODO css type + +export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getPlacement: (ref: ElementRef) => void; + getState: () => MenuProps & MenuState; +} + +export default Menu; + +// ============================== +// Menu List +// ============================== + +interface MenuListState { + /** Set classname for isMulti */ + isMulti: boolean; + /* Set the max height of the Menu component */ + maxHeight: number; +} + +export interface MenuListProps { + /** The children to be rendered. */ + children: Node; + /** Inner ref to DOM Node */ + innerRef: InnerRef; +} +export type MenuListComponentProps = CommonProps & + MenuListProps & + MenuListState; +export function menuListCSS(state: MenuState): any; // TODO css type +export const MenuList: ComponentType>; + +// ============================== +// Menu Notices +// ============================== + +export function noOptionsMessageCSS(): any; // TODO css type +export function loadingMessageCSS(): any; // TODO css type + +export type NoticeProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** Props to be passed on to the wrapper. */ + innerProps: { [key: string]: any }, +}; + +export const NoOptionsMessage: ComponentType>; +// NoOptionsMessage.defaultProps = { +// children: 'No options', +// }; + +export const LoadingMessage: ComponentType>; +// LoadingMessage.defaultProps = { +// children: 'Loading...', +// }; + +// ============================== +// Menu Portal +// ============================== + +export type MenuPortalProps = CommonProps & { + appendTo: HTMLElement, + children: Node, // ideally Menu + controlElement: HTMLElement, + menuPlacement: MenuPlacement, + menuPosition: MenuPosition, +}; +interface MenuPortalState { + placement: 'bottom' | 'top' | null; +} +interface PortalStyleArgs { + offset: number; + position: MenuPosition; + rect: RectType; +} + +export function menuPortalCSS(args: PortalStyleArgs): any; // TODO css type + +export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getChildContext(): { + getPortalPlacement: (state: MenuState) => void; + }; + + // callback for occassions where the menu must "flip" + getPortalPlacement: (state: MenuState) => void; +} diff --git a/types/react-select/lib/components/MultiValue.d.ts b/types/react-select/lib/components/MultiValue.d.ts new file mode 100644 index 0000000000..495b4fc96f --- /dev/null +++ b/types/react-select/lib/components/MultiValue.d.ts @@ -0,0 +1,57 @@ +import { ComponentType, Component, ReactNode as Node } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type MultiValueProps = CommonProps &{ + children: Node, + components: any, + cropWithEllipsis: boolean, + data: OptionType, + innerProps: any, + isFocused: boolean, + isDisabled: boolean, + removeProps: { + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, +}; + +export function multiValueCSS(): any; // TODO css type +export function multiValueLabelCSS(props: MultiValueProps): any; // TODO css type +export function multiValueRemoveCSS(props: MultiValueProps): any; // TODO css type + +export interface MultiValueGenericProps { + children: Node; + data: OptionType; + innerProps: { className?: string }; + selectProps: any; +} +export const MultiValueGeneric: ComponentType>; + +export const MultiValueContainer: typeof MultiValueGeneric; +export const MultiValueLabel: typeof MultiValueGeneric; +export type MultiValueRemoveProps = CommonProps & { + children: Node, + innerProps: { + className: string, + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, + selectProps: any, +}; +export class MultiValueRemove extends Component> { + static defaultProps: { + children: Node, + }; +} + +export class MultiValue extends Component> { + static defaultProps: { + cropWithEllipsis: boolean, + }; +} + +export default MultiValue; diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts new file mode 100644 index 0000000000..743083fff8 --- /dev/null +++ b/types/react-select/lib/components/Option.d.ts @@ -0,0 +1,41 @@ +import { ComponentType, ReactNode as Node, MouseEventHandler } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles, InnerRef } from '../types'; + +interface State { + /** Wether the option is disabled. */ + isDisabled: boolean; + /** Wether the option is focused. */ + isFocused: boolean; + /** Whether the option is selected. */ + isSelected: boolean; +} +interface InnerProps { + id: string; + key: string; + onClick: MouseEventHandler; + onMouseOver: MouseEventHandler; + tabIndex: number; +} +export type OptionProps = PropsWithStyles & + CommonProps & + State & { + /** The children to be rendered. */ + children: Node, + /** Inner ref to DOM Node */ + innerRef: InnerRef, + /** props passed to the wrapping element for the group. */ + innerProps: InnerProps, + /* Text to be displayed representing the option. */ + label: string, + /* Type is used by the menu to determine whether this is an option or a group. + In the case of option this is always `option`. */ + type: 'option', + }; + +export function optionCSS(state: State): any; // TODO css type + +export const Option: ComponentType>; + +export default Option; diff --git a/types/react-select/lib/components/Placeholder.d.ts b/types/react-select/lib/components/Placeholder.d.ts new file mode 100644 index 0000000000..f674f74cc2 --- /dev/null +++ b/types/react-select/lib/components/Placeholder.d.ts @@ -0,0 +1,17 @@ +import { ComponentType, ReactNode as Node } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type PlaceholderProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** props passed to the wrapping element for the group. */ + innerProps: { [key: string]: any }, +}; + +export function placeholderCSS(): any; // TODO css type + +export const Placeholder: ComponentType>; + +export default Placeholder; diff --git a/types/react-select/lib/components/SingleValue.d.ts b/types/react-select/lib/components/SingleValue.d.ts new file mode 100644 index 0000000000..c5f922d84c --- /dev/null +++ b/types/react-select/lib/components/SingleValue.d.ts @@ -0,0 +1,23 @@ +import { ComponentType } from 'react'; +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface State { + /** Whether this is disabled */ + isDisabled: boolean; +} +interface ValueProps { + /** The children to be rendered. */ + children: string; + /* The data of the selected option rendered in the Single Value componentn */ + data: OptionType; + /** Props passed to the wrapping element for the group. */ + innerProps: any; +} +export type SingleValueProps = CommonProps & ValueProps & State; + +export function css(props: SingleValueProps): any; // TODO css type + +export const SingleValue: ComponentType>; + +export default SingleValue; diff --git a/types/react-select/lib/components/containers.d.ts b/types/react-select/lib/components/containers.d.ts new file mode 100644 index 0000000000..373a552062 --- /dev/null +++ b/types/react-select/lib/components/containers.d.ts @@ -0,0 +1,57 @@ +import { Component, ReactNode as Node, ComponentType } from 'react'; +import { spacing } from '../theme'; +import { CommonProps, KeyboardEventHandler } from '../types'; + +// ============================== +// Root Container +// ============================== + +export interface ContainerState { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the text in the select is indented from right to left. */ + isRtl: boolean; +} + +export type ContainerProps = CommonProps & + ContainerState & { + /** The children to be rendered. */ + children: Node, + /** Inner props to be passed down to the container. */ + innerProps: { onKeyDown: KeyboardEventHandler }, + }; +export function containerCSS(state: ContainerState): any; // TODO css type; +export const SelectContainer: ComponentType>; + +// ============================== +// Value Container +// ============================== + +export type ValueContainerProps = CommonProps & { + /** Set when the value container should hold multiple values */ + isMulti: boolean, + /** Whether the value container currently holds a value. */ + hasValue: boolean, + /** The children to be rendered. */ + children: Node, +}; +export function valueContainerCSS(): any; // TODO css type; +export class ValueContainer extends Component> {} + +// ============================== +// Indicator Container +// ============================== + +export interface IndicatorsState { + /** Whether the text should be rendered right to left. */ + isRtl: boolean; +} + +export type IndicatorContainerProps = CommonProps & + IndicatorsState & { + /** The children to be rendered. */ + children: Node, + }; + +export function indicatorsContainerCSS(): any; // TODO css type; +export const IndicatorsContainer: ComponentType>; diff --git a/types/react-select/lib/components/index.d.ts b/types/react-select/lib/components/index.d.ts new file mode 100644 index 0000000000..7d493a562a --- /dev/null +++ b/types/react-select/lib/components/index.d.ts @@ -0,0 +1,142 @@ +import { + ComponentType, + ReactElement as Element, +} from 'react'; +import { + IndicatorContainerProps, + ContainerProps, + ValueContainerProps, + IndicatorsContainer, + SelectContainer, + ValueContainer, +} from './containers'; +import { + IndicatorProps, + LoadingIconProps, + ClearIndicator, + DropdownIndicator, + LoadingIndicator, + IndicatorSeparator, + DownChevron, + CrossIcon, +} from './indicators'; + +import Control, { ControlProps } from './Control'; +import Group, { GroupProps, GroupHeading } from './Group'; +import Input, { InputProps } from './Input'; +import Menu, { + MenuProps, + MenuList, + MenuListComponentProps, + MenuPortal, + MenuPortalProps, + NoticeProps, + NoOptionsMessage, + LoadingMessage, +} from './Menu'; +import MultiValue, { + MultiValueProps, + MultiValueContainer, + MultiValueLabel, + MultiValueRemove, +} from './MultiValue'; +import Option, { OptionProps } from './Option'; +import Placeholder, { PlaceholderProps } from './Placeholder'; +import SingleValue, { SingleValueProps } from './SingleValue'; + +export type PlaceholderOrValue = + | Element>> + | Element>> + | Array>>>; + +export type IndicatorComponentType = ComponentType>; + +export interface SelectComponents { + ClearIndicator: IndicatorComponentType | null; + Control: ComponentType>; + DropdownIndicator: IndicatorComponentType | null; + DownChevron: ComponentType; + CrossIcon: ComponentType; + Group: ComponentType>; + GroupHeading: ComponentType; + IndicatorsContainer: ComponentType>; + IndicatorSeparator: IndicatorComponentType | null; + Input: ComponentType; + LoadingIndicator: ComponentType> | null; + Menu: ComponentType>; + MenuList: ComponentType>; + MenuPortal: ComponentType>; + LoadingMessage: ComponentType>; + NoOptionsMessage: ComponentType>; + MultiValue: ComponentType>; + MultiValueContainer: ComponentType; + MultiValueLabel: ComponentType; + MultiValueRemove: ComponentType; + Option: ComponentType>; + Placeholder: ComponentType>; + SelectContainer: ComponentType>; + SingleValue: ComponentType>; + ValueContainer: ComponentType>; +} + +export interface SelectComponentsConfig { + ClearIndicator?: IndicatorComponentType | null; + Control?: ComponentType>; + DropdownIndicator?: IndicatorComponentType | null; + DownChevron?: ComponentType; + CrossIcon?: ComponentType; + Group?: ComponentType>; + GroupHeading?: ComponentType; + IndicatorsContainer?: ComponentType>; + IndicatorSeparator?: IndicatorComponentType | null; + Input?: ComponentType; + LoadingIndicator?: ComponentType> | null; + Menu?: ComponentType>; + MenuList?: ComponentType>; + MenuPortal?: ComponentType>; + LoadingMessage?: ComponentType>; + NoOptionsMessage?: ComponentType>; + MultiValue?: ComponentType>; + MultiValueContainer?: ComponentType; + MultiValueLabel?: ComponentType; + MultiValueRemove?: ComponentType; + Option?: ComponentType>; + Placeholder?: ComponentType>; + SelectContainer?: ComponentType>; + SingleValue?: ComponentType>; + ValueContainer?: ComponentType>; +} + +export namespace components { + const ClearIndicator: IndicatorComponentType | null; + const Control: ComponentType>; + const DropdownIndicator: IndicatorComponentType | null; + const DownChevron: ComponentType; + const CrossIcon: ComponentType; + const Group: ComponentType>; + const GroupHeading: ComponentType; + const IndicatorsContainer: ComponentType>; + const IndicatorSeparator: IndicatorComponentType | null; + const Input: ComponentType; + const LoadingIndicator: ComponentType> | null; + const Menu: ComponentType>; + const MenuList: ComponentType>; + const MenuPortal: ComponentType>; + const LoadingMessage: ComponentType>; + const NoOptionsMessage: ComponentType>; + const MultiValue: ComponentType>; + const MultiValueContainer: ComponentType; + const MultiValueLabel: ComponentType; + const MultiValueRemove: ComponentType; + const Option: ComponentType>; + const Placeholder: ComponentType>; + const SelectContainer: ComponentType>; + const SingleValue: ComponentType>; + const ValueContainer: ComponentType>; +} + +export interface Props { + components: SelectComponentsConfig; +} + +export function defaultComponents(props: Props): SelectComponentsConfig; diff --git a/types/react-select/lib/components/indicators.d.ts b/types/react-select/lib/components/indicators.d.ts new file mode 100644 index 0000000000..d27cc518da --- /dev/null +++ b/types/react-select/lib/components/indicators.d.ts @@ -0,0 +1,67 @@ +import { ComponentType, ReactElement as ElementType } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +// ============================== +// Dropdown & Clear Icons +// ============================== + +export function CrossIcon(props: any): any; // TODO svg type +export function DownChevron(props: any): any; // TODO svg type + +// ============================== +// Dropdown & Clear Buttons +// ============================== + +export type IndicatorProps = CommonProps & { + /** The children to be rendered inside the indicator. */ + children: ElementType, + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +}; + +export type baseCSS = (props: IndicatorProps) => any; // TODO css type + +export const dropdownIndicatorCSS: baseCSS; +export const DropdownIndicator: ComponentType>; + +export const clearIndicatorCSS: baseCSS; +export const ClearIndicator: ComponentType>; + +// ============================== +// Separator +// ============================== + +export interface SeparatorState { isDisabled: boolean; } + +export function indicatorSeparatorCSS(state: SeparatorState): any; // TODO css type + +export const IndicatorSeparator: ComponentType>; + +// ============================== +// Loading +// ============================== + +export function loadingIndicatorCSS(state: { + isFocused: boolean, + size: number, +}): any; // TODO css type + +export type LoadingIconProps = { + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +} & CommonProps & { + /** Set size of the container. */ + size: number, +}; +export const LoadingIndicator: ComponentType>; +// TODO LoadingIndicator.defaultProps: { size: number }; diff --git a/types/react-select/lib/diacritics.d.ts b/types/react-select/lib/diacritics.d.ts new file mode 100644 index 0000000000..855a0e152a --- /dev/null +++ b/types/react-select/lib/diacritics.d.ts @@ -0,0 +1 @@ +export function stripDiacritics(str: string): string; diff --git a/types/react-select/lib/filters.d.ts b/types/react-select/lib/filters.d.ts new file mode 100644 index 0000000000..33d1a7fddf --- /dev/null +++ b/types/react-select/lib/filters.d.ts @@ -0,0 +1,16 @@ +export interface Config { + ignoreCase?: boolean; + ignoreAccents?: boolean; + stringify?: (obj: any) => string; + trim?: boolean; + matchFrom?: 'any' | 'start'; +} + +import { stripDiacritics } from './diacritics'; + +export interface Option { label: string; value: string; data: any; } + +export function createFilter(config: Config | null): ( + option: Option, + rawInput: string +) => boolean; diff --git a/types/react-select/lib/stateManager.d.ts b/types/react-select/lib/stateManager.d.ts new file mode 100644 index 0000000000..07a17f52f7 --- /dev/null +++ b/types/react-select/lib/stateManager.d.ts @@ -0,0 +1,36 @@ +import { Component, ComponentType, Ref as ElementRef } from 'react'; + +import { ActionMeta, InputActionMeta, ValueType } from './types'; + +export interface Props { + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; + inputValue?: string; + menuIsOpen?: boolean; + value?: ValueType; +} +interface State { + inputValue: string; + menuIsOpen: boolean; + value: ValueType; +} + +export class StateManager extends Component, State> { + static defaultProps: Props; + + select: ElementRef; + + focus(): void; + blur(): void; + getProp(key: string): any; + callProp(name: string, ...args: any[]): any; + onChange: (value: any, actionMeta: ActionMeta) => void; + onInputChange: (value: any, actionMeta: InputActionMeta) => void; + onMenuOpen: () => void; + onMenuClose: () => void; +} + +export function manageState(SelectComponent: ComponentType): StateManager; + +export default manageState; diff --git a/types/react-select/lib/styles.d.ts b/types/react-select/lib/styles.d.ts new file mode 100644 index 0000000000..9c5178fed1 --- /dev/null +++ b/types/react-select/lib/styles.d.ts @@ -0,0 +1,99 @@ +import { + containerCSS, + indicatorsContainerCSS, + valueContainerCSS, +} from './components/containers'; +import { css as controlCSS } from './components/Control'; +import { groupCSS, groupHeadingCSS } from './components/Group'; +import { + clearIndicatorCSS, + dropdownIndicatorCSS, + loadingIndicatorCSS, + indicatorSeparatorCSS, +} from './components/indicators'; +import { inputCSS } from './components/Input'; +import { placeholderCSS } from './components/Placeholder'; +import { optionCSS } from './components/Option'; +import { + menuCSS, + menuListCSS, + menuPortalCSS, + noOptionsMessageCSS, + loadingMessageCSS, +} from './components/Menu'; +import { css as singleValueCSS } from './components/SingleValue'; +import { + multiValueCSS, + multiValueLabelCSS, + multiValueRemoveCSS, +} from './components/MultiValue'; + +export interface Props { [key: string]: any; } + +/** + * @param base -- the component's default style + * @param state -- the component's current state e.g. `isFocused` + * @returns + */ +export type styleFn = (base: any, state: any) => any; + +export interface Styles { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer: styleFn; +} +export interface StylesConfig { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer?: styleFn; +} +export type GetStyles = (a: string, b: Props) => any; + +export const defaultStyles: Styles; + +// Merge Utility +// Allows consumers to extend a base Select with additional styles + +export function mergeStyles(source: any, target: any): any; diff --git a/types/react-select/lib/theme.d.ts b/types/react-select/lib/theme.d.ts new file mode 100644 index 0000000000..7282dd20ad --- /dev/null +++ b/types/react-select/lib/theme.d.ts @@ -0,0 +1,53 @@ +export const borderRadius: number; + +export const colors: { + text: string; + textLight: string; + primary: string; + primary75: string; + primary50: string; + primary25: string; + danger: string; + dangerLight: string; + + neutral0: string; + neutral1: string; + neutral2: string; + neutral3: string; + neutral4: string; + neutral5: string; + neutral10: string; + neutral20: string; + neutral30: string; + neutral40: string; + neutral50: string; + neutral60: string; + neutral70: string; + neutral80: string; + neutral90: string; + neutral100: string; + + neutral1a: string; + neutral2a: string; + neutral3a: string; + neutral4a: string; + neutral5a: string; + neutral10a: string; + neutral20a: string; + neutral30a: string; + neutral40a: string; + neutral50a: string; + neutral60a: string; + neutral70a: string; + neutral80a: string; + neutral90a: string; +}; + +export const spacing: { + /* Used to calculate consistent margin/padding on elements */ + baseUnit: number, + /* The minimum height of the control */ + controlHeight: number, + /* The amount of space between the control and menu */ + menuGutter: number, +}; diff --git a/types/react-select/lib/types.d.ts b/types/react-select/lib/types.d.ts new file mode 100644 index 0000000000..08ebfae965 --- /dev/null +++ b/types/react-select/lib/types.d.ts @@ -0,0 +1,100 @@ +import * as React from 'react'; + +export type OptionsType = OptionType[]; + +export interface GroupType { + options: OptionsType; + [key: string]: any; +} + +export type GroupedOptionsType = Array>; + +export type ValueType = OptionType | OptionsType | null | undefined; + +export type FocusEventHandler = (event: React.FocusEvent) => void; +export type MouseEventHandler = (event: React.MouseEvent) => void; +export type KeyboardEventHandler = (event: React.KeyboardEvent) => void; + +export type InnerRef = React.Ref; +export interface PropsWithInnerRef { + /** The inner reference. */ + innerRef: React.Ref; +} + +export interface PropsWithStyles { + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; +} + +export type ClassNameList = string[]; +export type ClassNamesState = { [key: string]: boolean } | undefined; + +export interface CommonProps { + clearValue: () => void; + className?: string; + cx: (a: string | null, b: ClassNamesState | undefined, c: string | undefined) => string | void; + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; + getValue: () => ValueType; + hasValue: boolean; + isMulti: boolean; + options: OptionsType; + selectOption: (option: OptionType) => void; + selectProps: any; + setValue: (value: ValueType, action: ActionTypes) => void; +} + +export type ActionTypes = + | 'select-option' + | 'deselect-option' + | 'remove-value' + | 'pop-value' + | 'set-value' + | 'clear' + | 'create-option'; + +export interface ActionMeta { + action: ActionTypes; +} + +export type InputActionTypes = + | 'set-value' + | 'input-change' + | 'input-blur' + | 'menu-close'; + +export interface InputActionMeta { + action: InputActionTypes; +} + +export type MenuPlacement = 'auto' | 'bottom' | 'top'; +export type MenuPosition = 'absolute' | 'fixed'; + +export type FocusDirection = + | 'up' + | 'down' + | 'pageup' + | 'pagedown' + | 'first' + | 'last'; + +export type OptionProps = PropsWithInnerRef & { + data: any, + id: number, + index: number, + isDisabled: boolean, + isFocused: boolean, + isSelected: boolean, + label: string, + onClick: MouseEventHandler, + onMouseOver: MouseEventHandler, + value: any, +}; diff --git a/types/react-select/lib/utils.d.ts b/types/react-select/lib/utils.d.ts new file mode 100644 index 0000000000..c907d59c2a --- /dev/null +++ b/types/react-select/lib/utils.d.ts @@ -0,0 +1,121 @@ +import * as React from 'react'; +import { + ClassNamesState, + InputActionMeta, + OptionsType, + ValueType, +} from './types'; + +// ============================== +// NO OP +// ============================== + +export function noop(): void; +export function emptyString(): string; + +// ============================== +// Class Name Prefixer +// ============================== + +export function classNames( + prefix?: string | null, + cssKey?: string | null, + state?: ClassNamesState, + className?: string, +): string; + +// ============================== +// Clean Value +// ============================== + +export function cleanValue(value: ValueType): OptionsType; + +// ============================== +// Handle Input Change +// ============================== + +export function handleInputChange( + inputValue: string, + actionMeta: InputActionMeta, + onInputChange?: (inputValue: string, actionMeta: InputActionMeta) => string | void +): string; + +// ============================== +// Scroll Helpers +// ============================== + +export function isDocumentElement(el: Element): boolean; + +// Normalized Scroll Top +// ------------------------------ + +export function normalizedHeight(el: Element): number; + +// Normalized scrollTo & scrollTop +// ------------------------------ + +export function getScrollTop(el: Element): number; + +export function scrollTo(el: Element, top: number): void; + +// Get Scroll Parent +// ------------------------------ + +export function getScrollParent(element: React.Ref): Element; + +// Animated Scroll To +// ------------------------------ + +export function animatedScrollTo( + element: Element, + to: number, + duration: number, + callback: (element: Element) => void +): void; + +// Scroll Into View +// ------------------------------ + +export function scrollIntoView( + menuEl: HTMLElement, + focusedEl: HTMLElement +): void; + +// ============================== +// Get bounding client object +// ============================== + +// cannot get keys using array notation with DOMRect +export function getBoundingClientObj(element: HTMLElement): { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; +}; +export interface RectType { + left: number; + right: number; + bottom: number; + height: number; + width: number; +} + +// ============================== +// String to Key (kebabify) +// ============================== + +export function toKey(str: string): string; + +// ============================== +// Touch Capability Detector +// ============================== + +export function isTouchCapable(): boolean; + +// ============================== +// Mobile Device Detector +// ============================== + +export function isMobileDevice(): boolean; diff --git a/types/react-select/test/AtlaskitDummy.ts b/types/react-select/test/AtlaskitDummy.ts new file mode 100644 index 0000000000..e6e75e9e32 --- /dev/null +++ b/types/react-select/test/AtlaskitDummy.ts @@ -0,0 +1,11 @@ +export const Tooltip = (props: any) => null; + +export const EmojiIcon = (props: any) => null; + +export const EditorPanelIcon = (props: any) => null; + +export const Spinner = (props: any) => null; + +export const Button = (props: any) => null; + +export const Modal = (props: any) => null; diff --git a/types/react-select/test/ChronoNodeDummy.ts b/types/react-select/test/ChronoNodeDummy.ts new file mode 100644 index 0000000000..1e4aed01b0 --- /dev/null +++ b/types/react-select/test/ChronoNodeDummy.ts @@ -0,0 +1 @@ +export function parseDate(a: any): any {} diff --git a/types/react-select/test/data.ts b/types/react-select/test/data.ts new file mode 100644 index 0000000000..a4bff0225d --- /dev/null +++ b/types/react-select/test/data.ts @@ -0,0 +1,132 @@ +import { GroupedOptionsType, GroupType } from "react-select/lib/types"; + +export interface ColourOption { + value: string; + label: string; + color: string; + disabled?: boolean; +} + +export const colourOptions: ColourOption[] = [ + { value: 'ocean', label: 'Ocean', color: '#00B8D9' }, + { value: 'blue', label: 'Blue', color: '#0052CC', disabled: true }, + { value: 'purple', label: 'Purple', color: '#5243AA' }, + { value: 'red', label: 'Red', color: '#FF5630' }, + { value: 'orange', label: 'Orange', color: '#FF8B00' }, + { value: 'yellow', label: 'Yellow', color: '#FFC400' }, + { value: 'green', label: 'Green', color: '#36B37E' }, + { value: 'forest', label: 'Forest', color: '#00875A' }, + { value: 'slate', label: 'Slate', color: '#253858' }, + { value: 'silver', label: 'Silver', color: '#666666' }, +]; + +export interface FlavourOption { + value: string; + label: string; + rating: 'safe' | 'good' | 'wild' | 'crazy'; +} + +export const flavourOptions: FlavourOption[] = [ + { value: 'vanilla', label: 'Vanilla', rating: 'safe' }, + { value: 'chocolate', label: 'Chocolate', rating: 'good' }, + { value: 'strawberry', label: 'Strawberry', rating: 'wild' }, + { value: 'salted-caramel', label: 'Salted Caramel', rating: 'crazy' }, +]; + +export interface StateOption { + value: string; + label: string; +} + +export const stateOptions: StateOption[] = [ + { value: 'AL', label: 'Alabama' }, + { value: 'AK', label: 'Alaska' }, + { value: 'AS', label: 'American Samoa' }, + { value: 'AZ', label: 'Arizona' }, + { value: 'AR', label: 'Arkansas' }, + { value: 'CA', label: 'California' }, + { value: 'CO', label: 'Colorado' }, + { value: 'CT', label: 'Connecticut' }, + { value: 'DE', label: 'Delaware' }, + { value: 'DC', label: 'District Of Columbia' }, + { value: 'FM', label: 'Federated States Of Micronesia' }, + { value: 'FL', label: 'Florida' }, + { value: 'GA', label: 'Georgia' }, + { value: 'GU', label: 'Guam' }, + { value: 'HI', label: 'Hawaii' }, + { value: 'ID', label: 'Idaho' }, + { value: 'IL', label: 'Illinois' }, + { value: 'IN', label: 'Indiana' }, + { value: 'IA', label: 'Iowa' }, + { value: 'KS', label: 'Kansas' }, + { value: 'KY', label: 'Kentucky' }, + { value: 'LA', label: 'Louisiana' }, + { value: 'ME', label: 'Maine' }, + { value: 'MH', label: 'Marshall Islands' }, + { value: 'MD', label: 'Maryland' }, + { value: 'MA', label: 'Massachusetts' }, + { value: 'MI', label: 'Michigan' }, + { value: 'MN', label: 'Minnesota' }, + { value: 'MS', label: 'Mississippi' }, + { value: 'MO', label: 'Missouri' }, + { value: 'MT', label: 'Montana' }, + { value: 'NE', label: 'Nebraska' }, + { value: 'NV', label: 'Nevada' }, + { value: 'NH', label: 'New Hampshire' }, + { value: 'NJ', label: 'New Jersey' }, + { value: 'NM', label: 'New Mexico' }, + { value: 'NY', label: 'New York' }, + { value: 'NC', label: 'North Carolina' }, + { value: 'ND', label: 'North Dakota' }, + { value: 'MP', label: 'Northern Mariana Islands' }, + { value: 'OH', label: 'Ohio' }, + { value: 'OK', label: 'Oklahoma' }, + { value: 'OR', label: 'Oregon' }, + { value: 'PW', label: 'Palau' }, + { value: 'PA', label: 'Pennsylvania' }, + { value: 'PR', label: 'Puerto Rico' }, + { value: 'RI', label: 'Rhode Island' }, + { value: 'SC', label: 'South Carolina' }, + { value: 'SD', label: 'South Dakota' }, + { value: 'TN', label: 'Tennessee' }, + { value: 'TX', label: 'Texas' }, + { value: 'UT', label: 'Utah' }, + { value: 'VT', label: 'Vermont' }, + { value: 'VI', label: 'Virgin Islands' }, + { value: 'VA', label: 'Virginia' }, + { value: 'WA', label: 'Washington' }, + { value: 'WV', label: 'West Virginia' }, + { value: 'WI', label: 'Wisconsin' }, + { value: 'WY', label: 'Wyoming' }, +]; + +export const optionLength = [ + { value: 1, label: 'general' }, + { + value: 2, + label: + 'Evil is the moment when I lack the strength to be true to the Good that compels me.', + }, + { + value: 3, + label: + // tslint:disable-next-line:max-line-length + "It is now an easy matter to spell out the ethic of a truth: 'Do all that you can to persevere in that which exceeds your perseverance. Persevere in the interruption. Seize in your being that which has seized and broken you.", + }, +]; + +// let bigOptions = []; +// for (let i = 0; i < 10000; i++) { +// bigOptions = bigOptions.concat(colourOptions); +// } + +const colourGroup: GroupType = { + label: 'Colours', + options: colourOptions +}; +const flavourGroup: GroupType = { + label: 'Flavours', + options: flavourOptions, +}; + +export const groupedOptions: GroupedOptionsType = [ colourGroup, flavourGroup ]; diff --git a/types/react-select/test/examples/AccessingInternals.tsx b/types/react-select/test/examples/AccessingInternals.tsx new file mode 100644 index 0000000000..8948bc19e7 --- /dev/null +++ b/types/react-select/test/examples/AccessingInternals.tsx @@ -0,0 +1,114 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import AsyncSelect from 'react-select/lib/Async'; +import CreatableSelect from 'react-select/lib/Creatable'; +import { Note } from '../styled-components'; +import { ColourOption, colourOptions } from '../data'; + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class AccessingInterals extends React.Component { + selectRef: Select; + asyncRef: AsyncSelect; + creatableRef: CreatableSelect; + focus = () => { + console.log(this.selectRef); + this.selectRef.focus(); + } + focusCreatable = () => { + console.log(this.creatableRef); + this.creatableRef.focus(); + } + focusAsync = () => { + console.log(this.asyncRef); + this.asyncRef.focus(); + } + blurAsync = () => { + this.asyncRef.blur(); + } + blurCreatable = () => { + this.creatableRef.blur(); + } + blur = () => this.selectRef.blur(); + onSelectRef = (ref: any) => { + console.log(ref); + this.selectRef = ref; + } + render() { + return ( + +

+ Creatable Select +

+ { this.creatableRef = ref; }} + isClearable + options={colourOptions} + /> + + + + + + +

+ Async Select +

+ { this.asyncRef = ref; }} + cacheOptions + defaultOptions + loadOptions={promiseOptions} + /> + + + + + + +

Select

+ +); diff --git a/types/react-select/test/examples/BasicSingle.tsx b/types/react-select/test/examples/BasicSingle.tsx new file mode 100644 index 0000000000..69697566c2 --- /dev/null +++ b/types/react-select/test/examples/BasicSingle.tsx @@ -0,0 +1,101 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { Note } from '../styled-components'; + +const Checkbox = (props: any) => ; + +interface State { + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + isRtl: boolean; + isSearchable: boolean; +} + +export default class SingleSelect extends React.Component { + state = { + isClearable: true, + isDisabled: false, + isLoading: false, + isRtl: false, + isSearchable: true, + }; + + toggleClearable = () => + this.setState(state => ({ isClearable: !state.isClearable })) + toggleDisabled = () => + this.setState(state => ({ isDisabled: !state.isDisabled })) + toggleLoading = () => + this.setState(state => ({ isLoading: !state.isLoading })) + toggleRtl = () => this.setState(state => ({ isRtl: !state.isRtl })); + toggleSearchable = () => + this.setState(state => ({ isSearchable: !state.isSearchable })) + render() { + const { + isClearable, + isSearchable, + isDisabled, + isLoading, + isRtl, + } = this.state; + return ( + + ; + +interface State { + menuIsOpen: boolean; +} + +export default class controlledMenu extends React.Component { + state = { + menuIsOpen: false, + }; + toggleMenuIsOpen = () => + this.setState(state => ({ menuIsOpen: !state.menuIsOpen })) + render() { + const { menuIsOpen } = this.state; + return ( + + ; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFromStart: boolean; +} + +export default class SelectCreateFilter extends React.Component { + state: State = { + ignoreCase: false, + ignoreAccents: false, + trim: false, + matchFromStart: false, + }; + toggleOption = (key: string) => () => { + this.setState((state: any) => ({ ...state, [key]: !state[key] })); + } + render() { + const { + ignoreCase, + ignoreAccents, + trim, + matchFromStart, + } = this.state; + + const filterConfig = { + ignoreCase, + ignoreAccents, + trim, + matchFrom: this.state.matchFromStart ? ('start' as 'start') : ('any' as 'any'), + }; + + return ( + + + ); +} diff --git a/types/react-select/test/examples/CustomControl.tsx b/types/react-select/test/examples/CustomControl.tsx new file mode 100644 index 0000000000..3ed018e05e --- /dev/null +++ b/types/react-select/test/examples/CustomControl.tsx @@ -0,0 +1,32 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; +const controlStyles = { + borderRadius: '1px solid black', + padding: '5px', + background: colourOptions[2].color, + color: 'white' +}; + +const ControlComponent = (props: any) => ( +
+ {

Custom Control

} + +
+); + +export default class CustomControl extends React.Component { + render() { + return ( + +); diff --git a/types/react-select/test/examples/CustomFilterOptions.tsx b/types/react-select/test/examples/CustomFilterOptions.tsx new file mode 100644 index 0000000000..62a13f2a89 --- /dev/null +++ b/types/react-select/test/examples/CustomFilterOptions.tsx @@ -0,0 +1,34 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFrom: boolean; +} + +const filterOptions = (candidate: any, input: string) => { + if (input) { + return candidate.value === customOptions[0].value; + } + return true; +}; + +const customOptions = [{ value: 'custom', label: 'Using a custom filter to always display this option on search' }, ...colourOptions]; + +export default class SelectCreateFilter extends React.Component { + render() { + return ( + +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomGroup.tsx b/types/react-select/test/examples/CustomGroup.tsx new file mode 100644 index 0000000000..7085e2901c --- /dev/null +++ b/types/react-select/test/examples/CustomGroup.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + borderRadius: '5px', + background: '#f2fcff' +}; + +const Group = (props: any) => ( +
+ +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Group }} + /> +); diff --git a/types/react-select/test/examples/CustomGroupHeading.tsx b/types/react-select/test/examples/CustomGroupHeading.tsx new file mode 100644 index 0000000000..abf09de9ef --- /dev/null +++ b/types/react-select/test/examples/CustomGroupHeading.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; +import { EditorPanelIcon, Tooltip } from '../AtlaskitDummy'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + color: 'white', + background: colourOptions[2].color, + padding: '5px 0px', + display: 'flex', +}; + +const GroupHeading = (props: any) => ( +
+ + + + +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ GroupHeading }} + styles={{ groupHeading: (base: any) => ({ ...base, flex: '1 1', color: 'white', margin: 0 }) }} + /> +); diff --git a/types/react-select/test/examples/CustomIndicatorSeparator.tsx b/types/react-select/test/examples/CustomIndicatorSeparator.tsx new file mode 100644 index 0000000000..c63d4a0f0e --- /dev/null +++ b/types/react-select/test/examples/CustomIndicatorSeparator.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +const indicatorSeparatorStyle = { + alignSelf: 'stretch', + backgroundColor: colourOptions[2].color, + marginBottom: 8, + marginTop: 8, + width: 1, +}; + +const IndicatorSeparator = ({ innerProps }: any) => { + return ( + + ); +}; + +export default () => ( + +); diff --git a/types/react-select/test/examples/CustomInput.tsx b/types/react-select/test/examples/CustomInput.tsx new file mode 100644 index 0000000000..e2bd0eb7d6 --- /dev/null +++ b/types/react-select/test/examples/CustomInput.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Input = (props: any) => { + if (props.isHidden) { + return ; + } + return ( +
+ + + +
+ ); +}; + +export default () => ( + option.rating !== 'safe'} + /> +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingIndicator.tsx b/types/react-select/test/examples/CustomLoadingIndicator.tsx new file mode 100644 index 0000000000..627599d52a --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingIndicator.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import { Spinner, Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingIndicator = (props: any) => { + return ( + + + + ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + + ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingMessage.tsx b/types/react-select/test/examples/CustomLoadingMessage.tsx new file mode 100644 index 0000000000..04776ebfd6 --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingMessage.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingMessage = (props: any) => { + return ( + +
+ {props.children} +
+
+ ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + components={{ LoadingMessage }} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomMenu.tsx b/types/react-select/test/examples/CustomMenu.tsx new file mode 100644 index 0000000000..b774a7fa1e --- /dev/null +++ b/types/react-select/test/examples/CustomMenu.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +function getLength(options: any) { + return options.reduce((acc: any, curr: any) => { + if (curr.options) return acc + getLength(curr.options); + return acc + 1; + }, 0); +} + +const menuHeaderStyle = { + padding: '8px 12px', +}; + +const Menu = (props: any) => { + const optionsLength = getLength(props.options); + return ( + +
+ Custom Menu with {optionsLength} options +
+ + {props.children} + +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Menu }} + /> +); diff --git a/types/react-select/test/examples/CustomMenuList.tsx b/types/react-select/test/examples/CustomMenuList.tsx new file mode 100644 index 0000000000..48a3cf62f7 --- /dev/null +++ b/types/react-select/test/examples/CustomMenuList.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const menuHeaderStyle = { + padding: '8px 12px', + background: colourOptions[2].color, + color: 'white', +}; + +const MenuList = (props: any) => { + return ( + +
+ Custom Menu List +
+ {props.children} +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ MenuList }} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueContainer.tsx b/types/react-select/test/examples/CustomMultiValueContainer.tsx new file mode 100644 index 0000000000..1b556751e1 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueContainer.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueContainer = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + defaultValue={[colourOptions[4], colourOptions[5]]} + isMulti + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueRemove.tsx b/types/react-select/test/examples/CustomMultiValueRemove.tsx new file mode 100644 index 0000000000..81dfaf35e9 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueRemove.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { EmojiIcon, Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueRemove = (props: any) => { + return ( + + + + + + ); +}; + +export default () => ( + ({ ...base, ...msgStyles }) }} + isSearchable + name="color" + options={[]} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomOption.tsx b/types/react-select/test/examples/CustomOption.tsx new file mode 100644 index 0000000000..aa115e78bf --- /dev/null +++ b/types/react-select/test/examples/CustomOption.tsx @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Option = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, fontSize: '1em', color: colourOptions[2].color, fontWeight: 400 }) }} + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomSelectContainer.tsx b/types/react-select/test/examples/CustomSelectContainer.tsx new file mode 100644 index 0000000000..393b8d1dd8 --- /dev/null +++ b/types/react-select/test/examples/CustomSelectContainer.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { Tooltip } from '../AtlaskitDummy'; +import { colourOptions } from '../data'; + +const SelectContainer = ({ children, ...props }: any) => { + return ( + + + {children} + + + ); +}; + +export default () => ( + ({ ...base, padding: 5, borderRadius: 5, background: colourOptions[2].color, color: 'white', display: 'flex' }) }} + components={{ SingleValue }} + isSearchable + name="color" + options={colourOptions} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomValueContainer.tsx b/types/react-select/test/examples/CustomValueContainer.tsx new file mode 100644 index 0000000000..31d18ef50b --- /dev/null +++ b/types/react-select/test/examples/CustomValueContainer.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const ValueContainer = ({ children, ...props }: any) => ( + + {children} + +); + +export default class CustomControl extends React.Component { + render() { + return ( + v.some(i => i.date.isSame(o.date, 'day'))} + maxMenuHeight={380} + onChange={this.props.onChange} + onInputChange={this.handleInputChange} + options={options} + value={value} + /> + ); + } +} + +export default class Experimental extends React.Component { + state = { + value: defaultOptions[0], + }; + handleChange = (value: any) => { + this.setState({ value }); + } + render() { + const { value } = this.state; + const displayValue = value && value.value ? value.value.toString() : 'null'; + return ( +
+
Value: {displayValue}
+ +
+ ); + } +} diff --git a/types/react-select/test/examples/MenuPortal.tsx b/types/react-select/test/examples/MenuPortal.tsx new file mode 100644 index 0000000000..32590acfb1 --- /dev/null +++ b/types/react-select/test/examples/MenuPortal.tsx @@ -0,0 +1,91 @@ +import * as React from 'react'; +import { Modal, Button } from '../AtlaskitDummy'; +import Select from 'react-select'; +import { H1, Note } from '../styled-components'; + +import { colourOptions } from '../data'; + +interface State { + isOpen: boolean; + isFixed: boolean; + portalPlacement: 'auto' | 'bottom' | 'top'; +} + +export default class MenuPortal extends React.Component { + state: State = { + isOpen: false, + isFixed: false, + portalPlacement: 'bottom', + }; + open = () => { + console.log('menuPortal is Open'); + this.setState({ isOpen: true }); + } + close = () => { this.setState({ isOpen: false }); }; + setPlacement = ({ currentTarget }: any) => { + const portalPlacement = currentTarget && currentTarget.value; + this.setState({ portalPlacement }); + } + toggleMode = () => { + this.setState(state => ({ isFixed: !state.isFixed })); + } + render() { + const { close, open } = this; + const { isOpen, isFixed, portalPlacement } = this.state; + return ( + + + { + isOpen ? + +

Portaled Menu Element

+ + + + + + + + + Fixed + + + + Portal + +
+ : null + } +
+ ); + } +} diff --git a/types/react-select/test/examples/OnSelectResetsInput.tsx b/types/react-select/test/examples/OnSelectResetsInput.tsx new file mode 100644 index 0000000000..af1327b1bb --- /dev/null +++ b/types/react-select/test/examples/OnSelectResetsInput.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { InputActionMeta } from 'react-select/lib/types'; + +export default class OnSelectResetsInput extends React.Component { + state = { + inputValue: '', + menuIsOpen: undefined + }; + onInputChange = (inputValue: string, { action }: InputActionMeta) => { + console.log(inputValue, action); + switch (action) { + case 'input-change': + this.setState({ inputValue }); + return; + case 'menu-close': + console.log(this.state.inputValue); + let menuIsOpen; + if (this.state.inputValue) { + menuIsOpen = true; + } + this.setState({ + menuIsOpen + }); + return; + default: + return; + } + } + render() { + const { inputValue, menuIsOpen } = this.state; + return ( + + + ); + } +} + +// styled components + +const Menu = (props: any) => { + const shadow = colors.neutral10a; + return ( +
+ ); +}; +const Blanket = (props: any) => ( +
+); +const Dropdown = ({ children, isOpen, target, onClose }: any) => ( +
// TODO css type + {target} + {isOpen ? {children} : null} + {isOpen ? : null} +
+); +const Svg = (p: any) => ( + +); +const DropdownIndicator = () => ( +
// TODO css type + + + +
+); +const ChevronDown = () => ( + + + +); diff --git a/types/react-select/test/examples/StyledMulti.tsx b/types/react-select/test/examples/StyledMulti.tsx new file mode 100644 index 0000000000..a4dedb4156 --- /dev/null +++ b/types/react-select/test/examples/StyledMulti.tsx @@ -0,0 +1,53 @@ +import * as React from 'react'; +import * as chroma from 'chroma-js'; + +import { colourOptions } from '../data'; +import Select from 'react-select'; + +const colourStyles = { + control: (styles: any) => ({ ...styles, backgroundColor: 'white' }), + option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: isDisabled + ? null + : isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null, + color: isDisabled + ? '#ccc' + : isSelected + ? chroma.contrast(color, 'white') > 2 ? 'white' : 'black' + : data.color, + cursor: isDisabled ? 'not-allowed' : 'default', + }; + }, + multiValue: (styles: any, { data }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: color.alpha(0.1).css(), + }; + }, + multiValueLabel: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + }), + multiValueRemove: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + ':hover': { + backgroundColor: data.color, + color: 'white', + }, + }), +}; + +export default () => ( + +); diff --git a/types/react-select/test/styled-components.tsx b/types/react-select/test/styled-components.tsx new file mode 100644 index 0000000000..fa18465cd8 --- /dev/null +++ b/types/react-select/test/styled-components.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; + +export const Note = ({ Tag = 'div', ...props }: any) => ( + +); + +export const H1 = (props: any) =>

; +export const H2 = (props: any) =>

; diff --git a/types/react-select/tsconfig.json b/types/react-select/tsconfig.json index 7855eceaf1..8c7a1921bd 100644 --- a/types/react-select/tsconfig.json +++ b/types/react-select/tsconfig.json @@ -1,10 +1,4 @@ { - "files": [ - "index.d.ts", - "lib/Option/index.d.ts", - "lib/utils/defaultMenuRenderer/index.d.ts", - "react-select-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -12,16 +6,99 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "jsx": "react", "typeRoots": [ "../" ], + "jsx": "react", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/animated/Input.d.ts", + "lib/animated/MultiValue.d.ts", + "lib/animated/Placeholder.d.ts", + "lib/animated/SingleValue.d.ts", + "lib/animated/ValueContainer.d.ts", + "lib/animated/transitions.d.ts", + "lib/animated/index.d.ts", + "lib/components/containers.d.ts", + "lib/components/Control.d.ts", + "lib/components/Group.d.ts", + "lib/components/Input.d.ts", + "lib/components/Menu.d.ts", + "lib/components/MultiValue.d.ts", + "lib/components/Option.d.ts", + "lib/components/Placeholder.d.ts", + "lib/components/SingleValue.d.ts", + "lib/components/indicators.d.ts", + "lib/components/index.d.ts", + "lib/accessibility/index.d.ts", + "lib/theme.d.ts", + "lib/Creatable.d.ts", + "lib/Async.d.ts", + "lib/AsyncCreatable.d.ts", + "lib/filters.d.ts", + "lib/styles.d.ts", + "lib/stateManager.d.ts", + "lib/builtins.d.ts", + "lib/utils.d.ts", + "lib/diacritics.d.ts", + "lib/types.d.ts", + "lib/Select.d.ts", + "test/data.ts", + "test/styled-components.tsx", + "test/AtlaskitDummy.ts", + "test/ChronoNodeDummy.ts", + "test/examples/AccessingInternals.tsx", + "test/examples/AnimatedMulti.tsx", + "test/examples/AsyncCallbacks.tsx", + "test/examples/AsyncCreatable.tsx", + "test/examples/AsyncMulti.tsx", + "test/examples/AsyncPromises.tsx", + "test/examples/BasicGrouped.tsx", + "test/examples/BasicMulti.tsx", + "test/examples/BasicSingle.tsx", + "test/examples/ControlledMenu.tsx", + "test/examples/CreatableAdvanced.tsx", + "test/examples/CreatableInputOnly.tsx", + "test/examples/CreatableMulti.tsx", + "test/examples/CreatableSingle.tsx", + "test/examples/CreateFilter.tsx", + "test/examples/CustomClearIndicator.tsx", + "test/examples/CustomControl.tsx", + "test/examples/CustomDropdownIndicator.tsx", + "test/examples/CustomFilterOptions.tsx", + "test/examples/CustomGetOptionLabel.tsx", + "test/examples/CustomGroup.tsx", + "test/examples/CustomGroupHeading.tsx", + "test/examples/CustomIndicatorsContainer.tsx", + "test/examples/CustomIndicatorSeparator.tsx", + "test/examples/CustomInput.tsx", + "test/examples/CustomIsOptionDisabled.tsx", + "test/examples/CustomLoadingIndicator.tsx", + "test/examples/CustomLoadingMessage.tsx", + "test/examples/CustomMenu.tsx", + "test/examples/CustomMenuList.tsx", + "test/examples/CustomMultiValueContainer.tsx", + "test/examples/CustomMultiValueLabel.tsx", + "test/examples/CustomMultiValueRemove.tsx", + "test/examples/CustomNoOptionsMessage.tsx", + "test/examples/CustomOption.tsx", + "test/examples/CustomPlaceholder.tsx", + "test/examples/CustomSelectContainer.tsx", + "test/examples/CustomSingleValue.tsx", + "test/examples/CustomValueContainer.tsx", + "test/examples/Experimental.tsx", + "test/examples/MenuPortal.tsx", + "test/examples/OnSelectResetsInput.tsx", + "test/examples/Popout.tsx", + "test/examples/StyledMulti.tsx", + "test/examples/StyledSingle.tsx" + ] } diff --git a/types/react-select/tslint.json b/types/react-select/tslint.json index 3db14f85ea..f93cf8562a 100644 --- a/types/react-select/tslint.json +++ b/types/react-select/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-select/v1/index.d.ts b/types/react-select/v1/index.d.ts new file mode 100644 index 0000000000..31ff0db561 --- /dev/null +++ b/types/react-select/v1/index.d.ts @@ -0,0 +1,654 @@ +// Type definitions for react-select 1.3 +// Project: https://github.com/JedWatson/react-select +// Definitions by: ESQUIBET Hugo +// Gilad Gray +// Izaak Baker +// Tadas Dailyda +// Mark Vujevits +// Mike Deverell +// MartynasZilinskas +// Onat Yigit Mercan +// Ian Johnson +// Anton Novik +// David Schkalee +// Arthur Udalov +// Sebastian Silbermann +// Endurance Idehen +// Guillaume Chartier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export default class ReactSelectClass extends React.Component> { + focus(): void; + setValue(value: Option): void; +} +// Other components +export class Creatable extends React.Component> { } +export class Async extends React.Component> { } +export class AsyncCreatable extends React.Component> { } + +export type OptionComponentType = React.ComponentType>; +export type ValueComponentType = React.ComponentType>; + +export type HandlerRendererResult = JSX.Element | null | false; + +// Handlers +export type FocusOptionHandler = (option: Option) => void; +export type SelectValueHandler = (option: Option) => void; +export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; +export type ClearRendererHandler = () => HandlerRendererResult; +export type FilterOptionHandler = (option: Option, filter: string) => boolean; +export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; +export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; +export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; +export type OnCloseHandler = () => void; +export type OnInputChangeHandler = (inputValue: string) => string; +export type OnInputKeyDownHandler = React.KeyboardEventHandler; +export type OnMenuScrollToBottomHandler = () => void; +export type OnOpenHandler = () => void; +export type OnFocusHandler = React.FocusEventHandler; +export type OnBlurHandler = React.FocusEventHandler; +export type OptionRendererHandler = (option: Option) => HandlerRendererResult; +export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; +export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; +export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; +export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; +export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; +export type PromptTextCreatorHandler = (filterText: string) => string; +export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; + +export type OnChangeSingleHandler = OnChangeHandler>; +export type OnChangeMultipleHandler = OnChangeHandler>; +export type OnChangeHandler | Options> = (newValue: TOption | null) => void; +export type OnNewOptionClickHandler = (option: Option) => void; + +export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; +export type LoadOptionsAsyncHandler = (input: string) => Promise>; +export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; + +export interface AutocompleteResult { + /** The search-results to be displayed */ + options: Options; + /** + * Should be set to true, if and only if a longer query with the same prefix + * would return a subset of the results + * If set to true, more specific queries will not be sent to the server. + */ + complete: boolean; +} + +export type Options = Array>; + +export interface Option { + /** Text for rendering */ + label?: string; + /** Value for searching */ + value?: TValue; + /** + * Allow this option to be cleared + * @default true + */ + clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; + /** + * In the event that a custom menuRenderer is provided, Option should be able + * to accept arbitrary key-value pairs. See react-virtualized-select. + */ + [property: string]: any; +} + +export type OptionValues = string | number | boolean; + +export interface MenuRendererProps { + /** + * The currently focused option; should be visible in the menu by default. + * default {} + */ + focusedOption: Option; + + /** + * Callback to focus a new option; receives the option as a parameter. + */ + focusOption: FocusOptionHandler; + + /** + * Option labels are accessible with this string key. + */ + labelKey: string; + + /** + * Ordered array of options to render. + */ + options: Options; + + /** + * Callback to select a new option; receives the option as a parameter. + */ + selectValue: SelectValueHandler; + + /** + * Array of currently selected options. + */ + valueArray: Options; + + /** + * Callback to remove selection from option; receives the option as a parameter. + */ + removeValue: SelectValueHandler; + + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer: OptionRendererHandler; +} + +export interface OptionComponentProps { + /** + * Classname(s) to apply to the option component. + */ + className?: string; + + /** + * Currently focused option. + */ + focusOption?: Option; + + inputValue?: string; + instancePrefix?: string; + + /** + * True if this option is disabled. + */ + isDisabled?: boolean; + + /** + * True if this option is focused. + */ + isFocused?: boolean; + + /** + * True if this option is selected. + */ + isSelected?: boolean; + + /** + * Callback to be invoked when this option is focused. + */ + onFocus?: (option: Option, event: any) => void; + + /** + * Callback to be invoked when this option is selected. + */ + onSelect?: (option: Option, event: any) => void; + + /** + * Option to be rendered by this component. + */ + option: Option; + + /** + * Index of the option being rendered in the list + */ + optionIndex?: number; + + /** + * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one + * being rendered) + */ + removeValue?: (value: TValue | TValue[]) => void; + + /** + * Callback to invoke to select an option. (Not necessarily the one being rendered) + */ + selectValue?: (value: TValue | TValue[]) => void; +} + +export interface ArrowRendererProps { + /** + * Arrow mouse down event handler. + */ + onMouseDown: React.MouseEventHandler; + + /** + * whether the Select is open or not. + */ + isOpen: boolean; +} + +export interface ValueComponentProps { + disabled: ReactSelectProps['disabled']; + id: string; + instancePrefix: string; + onClick: OnValueClickHandler | null; + onRemove?: SelectValueHandler; + placeholder: ReactSelectProps['placeholder']; + value: Option; + values?: Array>; +} + +export interface ReactSelectProps extends React.Props> { + /** + * text to display when `allowCreate` is true. + * @default 'Add "{label}"?' + */ + addLabelText?: string; + /** + * renders a custom drop-down arrow to be shown in the right-hand side of the select. + * @default undefined + */ + arrowRenderer?: ArrowRendererHandler | null; + /** + * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. + * @default false + */ + autoBlur?: boolean; + /** + * autofocus the component on mount + * @deprecated. Use autoFocus instead + * @default false + */ + autofocus?: boolean; + /** + * autofocus the component on mount + * @default false + */ + autoFocus?: boolean; + /** + * If enabled, the input will expand as the length of its value increases + */ + autosize?: boolean; + /** + * whether pressing backspace removes the last item when there is no input value + * @default true + */ + backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; + /** + * CSS className for the outer element + */ + className?: string; + /** + * Prefix prepended to element default className if no className is defined + */ + classNamePrefix?: string; + /** + * title for the "clear" control when `multi` is true + * @default "Clear all" + */ + clearAllText?: string; + /** + * Renders a custom clear to be shown in the right-hand side of the select when clearable true + * @default undefined + */ + clearRenderer?: ClearRendererHandler; + /** + * title for the "clear" control + * @default "Clear value" + */ + clearValueText?: string; + /** + * whether to close the menu when a value is selected + * @default true + */ + closeOnSelect?: boolean; + /** + * whether it is possible to reset value. if enabled, an X button will appear at the right side. + * @default true + */ + clearable?: boolean; + /** + * whether backspace removes an item if there is no text input + * @default true + */ + deleteRemoves?: boolean; + /** + * delimiter to use to join multiple values + * @default "," + */ + delimiter?: string; + /** + * whether the Select is disabled or not + * @default false + */ + disabled?: boolean; + /** + * whether escape clears the value when the menu is closed + * @default true + */ + escapeClearsValue?: boolean; + /** + * method to filter a single option + */ + filterOption?: FilterOptionHandler; + /** + * method to filter the options array + */ + filterOptions?: FilterOptionsHandler; + /** + * id for the underlying HTML input element + * @default undefined + */ + id?: string; + /** + * whether to strip diacritics when filtering + * @default true + */ + ignoreAccents?: boolean; + /** + * whether to perform case-insensitive filtering + * @default true + */ + ignoreCase?: boolean; + /** + * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} + * @default {} + */ + inputProps?: { [key: string]: any }; + /** + * renders a custom input + */ + inputRenderer?: InputRendererHandler; + /** + * allows for synchronization of component id's on server and client. + * @see https://github.com/JedWatson/react-select/pull/1105 + */ + instanceId?: string; + /** + * whether the Select is loading externally or not (such as options being loaded). + * if true, a loading spinner will be shown at the right side. + * @default false + */ + isLoading?: boolean; + /** + * (legacy mode) joins multiple values into a single form field with the delimiter + * @default false + */ + joinValues?: boolean; + /** + * the option property to use for the label + * @default "label" + */ + labelKey?: string; + /** + * (any, start) match the start or entire string when filtering + * @default "any" + */ + matchPos?: string; + /** + * (any, label, value) which option property to filter on + * @default "any" + */ + matchProp?: string; + /** + * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport + * @default 0 + */ + menuBuffer?: number; + /** + * optional style to apply to the menu container + */ + menuContainerStyle?: React.CSSProperties; + /** + * renders a custom menu with options + */ + menuRenderer?: MenuRendererHandler; + /** + * optional style to apply to the menu + */ + menuStyle?: React.CSSProperties; + /** + * multi-value input + * @default false + */ + multi?: boolean; + /** + * field name, for hidden `` tag + */ + name?: string; + /** + * placeholder displayed when there are no matching search results or a falsy value to hide it + * @default "No results found" + */ + noResultsText?: string | JSX.Element; + /** + * onBlur handler: function (event) {} + */ + onBlur?: OnBlurHandler; + /** + * whether to clear input on blur or not + * @default true + */ + onBlurResetsInput?: boolean; + /** + * whether the input value should be reset when options are selected. + * Also input value will be set to empty if 'onSelectResetsInput=true' and + * Select will get new value that not equal previous value. + * @default true + */ + onSelectResetsInput?: boolean; + /** + * whether to clear input when closing the menu through the arrow + * @default true + */ + onCloseResetsInput?: boolean; + /** + * onChange handler: function (newValue) {} + */ + onChange?: OnChangeHandler; + /** + * fires when the menu is closed + */ + onClose?: OnCloseHandler; + /** + * onFocus handler: function (event) {} + */ + onFocus?: OnFocusHandler; + /** + * onInputChange handler: function (inputValue) {} + */ + onInputChange?: OnInputChangeHandler; + /** + * onInputKeyDown handler: function (keyboardEvent) {} + */ + onInputKeyDown?: OnInputKeyDownHandler; + /** + * fires when the menu is scrolled to the bottom; can be used to paginate options + */ + onMenuScrollToBottom?: OnMenuScrollToBottomHandler; + /** + * fires when the menu is opened + */ + onOpen?: OnOpenHandler; + /** + * boolean to enable opening dropdown when focused + * @default false + */ + openOnClick?: boolean; + /** + * open the options menu when the input gets focus (requires searchable = true) + * @default true + */ + openOnFocus?: boolean; + /** + * className to add to each option component + */ + optionClassName?: string; + /** + * option component to render in dropdown + */ + optionComponent?: OptionComponentType; + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer?: OptionRendererHandler; + /** + * array of Select options + * @default false + */ + options?: Options; + /** + * number of options to jump when using page up/down keys + * @default 5 + */ + pageSize?: number; + /** + * field placeholder, displayed when there's no value + * @default "Select..." + */ + placeholder?: string | JSX.Element; + /** + * whether the selected option is removed from the dropdown on multi selects + * @default true + */ + removeSelected?: boolean; + /** + * applies HTML5 required attribute when needed + * @default false + */ + required?: boolean; + /** + * value to use when you clear the control + */ + resetValue?: any; + /** + * use react-select in right-to-left direction + * @default false + */ + rtl?: boolean; + /** + * whether the viewport will shift to display the entire menu when engaged + * @default true + */ + scrollMenuIntoView?: boolean; + /** + * whether to enable searching feature or not + * @default true; + */ + searchable?: boolean; + /** + * whether to select the currently focused value when the [tab] key is pressed + */ + tabSelectsValue?: boolean; + /** + * initial field value + */ + value?: Option | Options | string | string[] | number | number[] | boolean; + /** + * the option property to use for the value + * @default "value" + */ + valueKey?: string; + /** + * function which returns a custom way to render the value selected + * @default false + */ + valueRenderer?: ValueRendererHandler; + /** + * optional style to apply to the control + */ + style?: React.CSSProperties; + + /** + * optional tab index of the control + */ + tabIndex?: string | number; + + /** + * value component to render + */ + valueComponent?: ValueComponentType; + + /** + * optional style to apply to the component wrapper + */ + wrapperStyle?: React.CSSProperties; + + /** + * onClick handler for value labels: function (value, event) {} + */ + onValueClick?: OnValueClickHandler; + + /** + * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false + */ + simpleValue?: boolean; +} + +export interface ReactCreatableSelectProps extends ReactSelectProps { + /** + * Searches for any matching option within the set of options. This function prevents + * duplicate options from being created. + */ + isOptionUnique?: IsOptionUniqueHandler; + + /** + * Determines if the current input text represents a valid option. + */ + isValidNewOption?: IsValidNewOptionHandler; + + /** + * factory to create new options + */ + newOptionCreator?: NewOptionCreatorHandler; + + /** + * Creates prompt/placeholder for option text. + */ + promptTextCreator?: PromptTextCreatorHandler; + + /** + * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. + */ + shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; + + /** + * new option click handler: function (option) {} + */ + onNewOptionClick?: OnNewOptionClickHandler; + + /** + * true: Show new option at top of list + * false: Show new option at bottom of list + * @default true + */ + showNewOptionAtTop?: boolean; +} + +export interface ReactAsyncSelectProps extends ReactSelectProps { + /** + * Whether to auto-load the default async options set. + */ + autoload?: boolean; + + /** + * object to use to cache results; can be null to disable cache + */ + cache?: { [key: string]: any } | boolean; + + /** + * function to call to load options asynchronously + */ + loadOptions: LoadOptionsHandler; + + /** + * replaces the placeholder while options are loading + */ + loadingPlaceholder?: string | JSX.Element; + /** + * displayed in the drop down list when the user did not type anything yet + */ + searchPromptText?: string; +} + +export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; diff --git a/types/react-select/lib/Option/index.d.ts b/types/react-select/v1/lib/Option/index.d.ts similarity index 100% rename from types/react-select/lib/Option/index.d.ts rename to types/react-select/v1/lib/Option/index.d.ts diff --git a/types/react-select/lib/utils/defaultMenuRenderer/index.d.ts b/types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts similarity index 100% rename from types/react-select/lib/utils/defaultMenuRenderer/index.d.ts rename to types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/v1/react-select-tests.tsx similarity index 100% rename from types/react-select/react-select-tests.tsx rename to types/react-select/v1/react-select-tests.tsx diff --git a/types/react-select/v1/tsconfig.json b/types/react-select/v1/tsconfig.json new file mode 100644 index 0000000000..e01d55ae8a --- /dev/null +++ b/types/react-select/v1/tsconfig.json @@ -0,0 +1,35 @@ +{ + "files": [ + "index.d.ts", + "lib/Option/index.d.ts", + "lib/utils/defaultMenuRenderer/index.d.ts", + "react-select-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-select/v1/tslint.json b/types/react-select/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-select/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-virtualized-select/tsconfig.json b/types/react-virtualized-select/tsconfig.json index b544360da3..42387bc3e0 100644 --- a/types/react-virtualized-select/tsconfig.json +++ b/types/react-virtualized-select/tsconfig.json @@ -10,11 +10,18 @@ "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, - "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 26de87320e92496029806ae61d481f51ca54541e Mon Sep 17 00:00:00 2001 From: Sean Nichols Date: Fri, 3 Aug 2018 12:44:52 -0400 Subject: [PATCH 167/275] [redux-form] Add FieldsProps.move --- types/redux-form/lib/FieldArray.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index b1ddbc6aa6..d800452a3e 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -42,6 +42,7 @@ interface FieldsProps { remove(index: number): void; shift(): FieldValue; swap(indexA: number, indexB: number): void; + move(from: number, to: number): void; unshift(value: FieldValue): void; } From 98d94b19b12c12b0d2f92f8ac0acf3e654d3fbd7 Mon Sep 17 00:00:00 2001 From: johnjbarton Date: Fri, 3 Aug 2018 10:45:02 -0700 Subject: [PATCH 168/275] Add new (pariial) typings for npm 'di' github 'node-di' (#27741) These typings are adequate for the primary user of di, karma-runner. The underlying project is deprecated and we will move to a new di system, but these typings help document where we are today. --- types/di/di-tests.ts | 21 +++++++++++++++++++++ types/di/index.d.ts | 15 +++++++++++++++ types/di/tsconfig.json | 23 +++++++++++++++++++++++ types/di/tslint.json | 1 + 4 files changed, 60 insertions(+) create mode 100644 types/di/di-tests.ts create mode 100644 types/di/index.d.ts create mode 100644 types/di/tsconfig.json create mode 100644 types/di/tslint.json diff --git a/types/di/di-tests.ts b/types/di/di-tests.ts new file mode 100644 index 0000000000..4cfd3de5e7 --- /dev/null +++ b/types/di/di-tests.ts @@ -0,0 +1,21 @@ +import * as di from "di"; + +const emptyInjector = new di.Injector(); +const moduleSpecifications = [{}]; +const fullInjector = new di.Injector(moduleSpecifications); +const childInjector = new di.Injector(moduleSpecifications, emptyInjector); + +const dep: {} = fullInjector.get('foo'); + +const factory = (context: {}, deps: Array<{}>) => { + return {}; +}; + +const invoked: {} = fullInjector.invoke(factory, {}); + +const oldTimeyClass = {prototype: {}}; + +const instance: {} = fullInjector.instantiate(oldTimeyClass); + +const anotherChildInjector: di.Injector = + fullInjector.createChild(moduleSpecifications); diff --git a/types/di/index.d.ts b/types/di/index.d.ts new file mode 100644 index 0000000000..ea1d596017 --- /dev/null +++ b/types/di/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for di 0.0 +// Project: https://github.com/vojtajina/node-di +// Definitions by: John J Barton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export class Injector { + get(dep: string): {}; + invoke(fn: (context: {}, deps: Array<{}>) => {}, context: {}): {}; + instantiate({prototype: {}}): {}; + createChild(modules: Array<{}>): Injector; + constructor(modules?: Array<{}>, parent?: Injector); +} diff --git a/types/di/tsconfig.json b/types/di/tsconfig.json new file mode 100644 index 0000000000..c7e591ab5a --- /dev/null +++ b/types/di/tsconfig.json @@ -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", + "di-tests.ts" + ] +} diff --git a/types/di/tslint.json b/types/di/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/di/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 94f81483b95499461c72e6cd947aec5b753dd868 Mon Sep 17 00:00:00 2001 From: Manuel Warum Date: Fri, 3 Aug 2018 19:45:51 +0200 Subject: [PATCH 169/275] Adding types for crypto-random-string 1.0 (#27686) * Adding types for crypto-random-string 1.0 * Fixup in last commit wrt review * Fixing import of crypto-random-string test * Changing tslint.json as per review --- .../crypto-random-string-tests.ts | 4 ++++ types/crypto-random-string/index.d.ts | 13 +++++++++++ types/crypto-random-string/tsconfig.json | 23 +++++++++++++++++++ types/crypto-random-string/tslint.json | 3 +++ 4 files changed, 43 insertions(+) create mode 100644 types/crypto-random-string/crypto-random-string-tests.ts create mode 100644 types/crypto-random-string/index.d.ts create mode 100644 types/crypto-random-string/tsconfig.json create mode 100644 types/crypto-random-string/tslint.json diff --git a/types/crypto-random-string/crypto-random-string-tests.ts b/types/crypto-random-string/crypto-random-string-tests.ts new file mode 100644 index 0000000000..1a66c25981 --- /dev/null +++ b/types/crypto-random-string/crypto-random-string-tests.ts @@ -0,0 +1,4 @@ +import generate = require('crypto-random-string'); + +// $ExpectType string +generate(10); diff --git a/types/crypto-random-string/index.d.ts b/types/crypto-random-string/index.d.ts new file mode 100644 index 0000000000..dc41e18428 --- /dev/null +++ b/types/crypto-random-string/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for crypto-random-string 1.0 +// Project: https://github.com/sindresorhus/crypto-random-string +// Definitions by: Manuel Warum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Generate a hexadecimal string of the given length. + * @param length the length of the random string. + * @return a string of the specified length. + */ +declare function cryptoRandomString(length: number): string; + +export = cryptoRandomString; diff --git a/types/crypto-random-string/tsconfig.json b/types/crypto-random-string/tsconfig.json new file mode 100644 index 0000000000..fd68e9d080 --- /dev/null +++ b/types/crypto-random-string/tsconfig.json @@ -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", + "crypto-random-string-tests.ts" + ] +} diff --git a/types/crypto-random-string/tslint.json b/types/crypto-random-string/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/crypto-random-string/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From a440521e0be93a8a15633fb12abd9cce5ec712cc Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Fri, 3 Aug 2018 10:48:02 -0700 Subject: [PATCH 170/275] office-js: Update links (#27850) --- types/office-js/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index a731343bc6..52966a988d 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -280,7 +280,7 @@ declare namespace Office { * * @remarks * - * Returned by the {@link Office.AsyncResult.status | status} property of the {@link Office.AsyncResult | AsyncResult} object. + * Returned by the `status` property of the {@link Office.AsyncResult | AsyncResult} object. * * **Support details** * @@ -477,9 +477,9 @@ declare namespace Office { * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the {@link Office.Document.getSelectedDataAsync | getSelectedDataAsync} and {@link Office.Document.setSelectedDataAsync | setSelectedDataAsync} methods of the Document object. + * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the {@link Office.AsyncResult | AsyncResult} object topic. + * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. */ value: any; } @@ -1334,7 +1334,7 @@ declare namespace Office { /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document.getSelectedData | Document.getSelectedData} method to get the current slide or selected range of slides. + * Note: Only applies to data in PowerPoint when calling the `{@link Office.Document | Document}.getSelectedData` method to get the current slide or selected range of slides. */ SlideRange, /** @@ -1665,7 +1665,7 @@ declare namespace Office { Previous } /** - * Specifies whether to select (highlight) the location to navigate to (when using the {@link Office.Document.goToByIdAsync | Document.goToByIdAsync} method). + * Specifies whether to select (highlight) the location to navigate to (when using the `{@link Office.Document | Document}.goToByIdAsync` method). * * @remarks * @@ -3716,11 +3716,11 @@ declare namespace Office { */ interface TextBinding extends Binding { } /** - * Specifies the project fields that are available as a parameter for the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. + * Specifies the project fields that are available as a parameter for the `{@link Office.Document | Document}.getProjectFieldAsync` method. * * @remarks * - * A ProjectProjectFields constant can be used as a parameter of the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. + * A ProjectProjectFields constant can be used as a parameter of the `{@link Office.Document | Document}.getProjectFieldAsync` method. * * **Support details** * @@ -3786,10 +3786,10 @@ declare namespace Office { WSSList } /** - * Specifies the resource fields that are available as a parameter for the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. + * Specifies the resource fields that are available as a parameter for the `{@link Office.Document | Document}.getResourceFieldAsync` method. * * @remarks - * A ProjectResourceFields constant can be used as a parameter of the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. + * A ProjectResourceFields constant can be used as a parameter of the `{@link Office.Document | Document}.getResourceFieldAsync` method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -4608,10 +4608,10 @@ declare namespace Office { Text9 } /** - * Specifies the task fields that are available as a parameter for the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. + * Specifies the task fields that are available as a parameter for the `{@link Office.Document | Document}.getTaskFieldAsync` method. * * @remarks - * A ProjectTaskFields constant can be used as a parameter of the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. + * A ProjectTaskFields constant can be used as a parameter of the `{@link Office.Document | Document}.getTaskFieldAsync` method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -5756,10 +5756,10 @@ declare namespace Office { WSSID } /** - * Specifies the types of views that the {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method can recognize. + * Specifies the types of views that the `{@link Office.Document | Document}.getSelectedViewAsync` method can recognize. * * @remarks - * The {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * The `{@link Office.Document | Document}.getSelectedViewAsync` method returns the ProjectViewTypes constant value and name that corresponds to the active view. * * **Support details** * From 610b0b70cf74a5f2976623f34f32b1447b8d40be Mon Sep 17 00:00:00 2001 From: Simon Hoss Date: Fri, 3 Aug 2018 19:50:04 +0200 Subject: [PATCH 171/275] Added additional ns prop for react-i18next (#27812) --- types/react-i18next/src/trans.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-i18next/src/trans.d.ts b/types/react-i18next/src/trans.d.ts index 3ef535cf5d..2b0e8e7738 100644 --- a/types/react-i18next/src/trans.d.ts +++ b/types/react-i18next/src/trans.d.ts @@ -19,6 +19,7 @@ export interface TransProps { defaults?: string; values?: Values; components?: React.ReactNode[]; + ns?: string; } export default class Trans extends React.Component { } From 9995645f5b4798fdd7eeb39a69cf5c5cf3a2b1f6 Mon Sep 17 00:00:00 2001 From: Max Rumpf Date: Fri, 3 Aug 2018 19:50:40 +0200 Subject: [PATCH 172/275] [@types/dnssd] Fix return types (#27828) * [@types/dnsds] Fix return types Especially the ServiceType constructor was handled rather poorly before. This commit fixes it. Some methods (e.g. for resolving) could probably also be handled better, but that will be another PR. * Increase version number * Fix tests * Make options optional * Fix oversight introduces in previous commit --- types/dnssd/dnssd-tests.ts | 2 +- types/dnssd/index.d.ts | 51 ++++++++++++++++++++++---------------- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/types/dnssd/dnssd-tests.ts b/types/dnssd/dnssd-tests.ts index 14b637d384..0fa7498bb2 100644 --- a/types/dnssd/dnssd-tests.ts +++ b/types/dnssd/dnssd-tests.ts @@ -1,6 +1,6 @@ import * as dnssd from 'dnssd'; -const serviceType = new dnssd.ServiceType(dnssd.tcp('_mqtt'), dnssd.udp('_mqtt')); +const serviceType = dnssd.ServiceType.tcp('_mqtt', '_mqtt._udp'); const advertisement = new dnssd.Advertisement(serviceType, 1883, { name: 'broker' }); const browser: dnssd.Browser = new dnssd.Browser(serviceType); diff --git a/types/dnssd/index.d.ts b/types/dnssd/index.d.ts index 9c66a6d6a4..80de2900f3 100644 --- a/types/dnssd/index.d.ts +++ b/types/dnssd/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for dnssd 0.3 +// Type definitions for dnssd 0.4 // Project: https://github.com/DeMille/dnssd.js#readme // Definitions by: Angel Merino +// Max Rumpf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,22 +10,30 @@ import { EventEmitter } from 'events'; /** Declaration file generated by dts-gen */ export class Advertisement { - constructor(type: any, port: any, ...args: any[]); + constructor(type: string | string[] | ServiceType, port: number, ...args: any[]); - start(): any; + start(): Advertisement; - stop(forceImmediate: any, callback: any): void; + stop(forceImmediate?: boolean, callback?: () => any): void; updateTXT(txtObj: any): void; } +export class Options { + name?: string; + host?: string; + txt?: any; + subtypes?: string[]; + interface?: string; +} + /** * A service entry as returned by serviceUp */ export class Service { fullname: string; // 'InstanceName._googlecast._tcp.local.' name: string; // 'InstanceName' - type: SType; // { name: 'googlecast'; protocol: 'tcp' } + type: ServiceType; // { name: 'googlecast'; protocol: 'tcp' } domain: string; // 'local' host: string; // 'Hostname.local.' port: number; // 8009 @@ -33,9 +42,21 @@ export class Service { txtRaw: any; } -export class SType { +export class ServiceType { + constructor(...args: string[]) + constructor(args: ServiceType); + name: string; protocol: string; + subtypes: string[]; + + toString(): string; + + static all(): ServiceType; + + static tcp(...args: string[]): ServiceType; + + static udp(...args: string[]): ServiceType; } export class Browser extends EventEmitter { @@ -48,23 +69,11 @@ export class Browser extends EventEmitter { stop(): any; } -export class ServiceType { - constructor(...args: any[]); - - toString(): any; - - static all(): any; - - static tcp(...args: any[]): any; - - static udp(...args: any[]): any; -} - export const resolveA: any; export const resolveAAAA: any; -export function all(): any; +export function all(): ServiceType; export function resolve(name: any, type: any, ...args: any[]): any; @@ -74,6 +83,6 @@ export function resolveService(name: any, ...args: any[]): any; export function resolveTXT(name: any, opts: any): any; -export function tcp(...args: any[]): any; +export function tcp(...args: string[]): ServiceType; -export function udp(...args: any[]): any; +export function udp(...args: string[]): ServiceType; From 6d2581cf26ce2d1e5d9c3cbed6fcf255a930d358 Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Sat, 4 Aug 2018 01:51:04 +0800 Subject: [PATCH 173/275] update setData to include callback (#27832) --- types/weixin-app/index.d.ts | 10 ++++++++-- types/weixin-app/weixin-app-tests.ts | 20 ++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 85740f7481..100a00bc48 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3218,9 +3218,14 @@ interface Component { */ data: T; /** - * 设置data并执行视图层渲染 + * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 + * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + * 3. 请不要把 data 中任何一项的 value 设为 undefined ,否则这一项将不被设置并可能遗留一些潜在问题 + * @param data object 以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value + * @param [callback] callback 是一个回调函数,在这次setData对界面渲染完毕后调用 */ - setData(data: object): void; + setData(data: { [key in keyof T]?: string | number | boolean | symbol | object | null | any[] }, callback?: () => any): void; /** * 检查组件是否具有 behavior * 检查时会递归检查被直接或间接引入的所有behavior @@ -3332,6 +3337,7 @@ interface PageOptions { */ onTabItemTap?: (item: any) => void; } + interface Page { /** * 强制更新 diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index 39943eba61..000fd36a3f 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -29,22 +29,31 @@ Component({ }, myProperty2: String // 简化的定义方式 }, - data: {}, // 私有数据,可用于模版渲染 + data: { + key: 'value', + anotherKey: 'value' + }, // 私有数据,可用于模版渲染 // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 - attached() { }, + attached() { + this.setData({}, () => { }); + }, moved() { }, detached() { }, methods: { onMyButtonTap() { + // 更新属性和数据的方法与更新页面数据的方法类似 this.setData({ - // 更新属性和数据的方法与更新页面数据的方法类似 + key: 123 // note this is edge case where it cannot detect wrong types... }); }, _myPrivateMethod() { // 内部方法建议以下划线开头 // this.replaceDataOnPath(['A', 0, 'B'], 'myPrivateData'); // 这里将 data.A[0].B 设为 'myPrivateData' // this.applyDataUpdates(); + this.setData({ + anotherKey: 123 + }); }, _propertyChange(newVal: string, oldVal: string) { // @@ -71,8 +80,11 @@ Page({ data: { text: "This is page data." }, - onLoad: () => { + onLoad() { // Do some initialize when page load. + this.setData({}, () => { + // callback + }); }, onReady: () => { // Do something when page ready. From 9241cf1a2b1c8b2704bbcba9c620157e39f7f4e2 Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Fri, 3 Aug 2018 19:54:48 +0200 Subject: [PATCH 174/275] Fix types from last big addition (#27834) * Fix some type from last big addition * Version * Test player.play * Remove patch version * remove whitespaces --- types/video.js/index.d.ts | 14 +++++++------- types/video.js/video.js-tests.ts | 6 +++++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 3d432fb9b3..8535cf4f16 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 7.0 +// Type definitions for Video.js 7.2 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -1962,7 +1962,7 @@ declare namespace videojs { }; interface ControlBarOptions extends ComponentOptions { - VolumePanel?: VolumePanelOptions; + volumePanel?: VolumePanelOptions; } /** @@ -3527,7 +3527,7 @@ declare namespace videojs { * * @return The current content of the modal dialog */ - content(value: Content): any; + content(value?: Content): any; /** * Create the `ModalDialog`'s DOM element @@ -3570,7 +3570,7 @@ declare namespace videojs { * @param [content] * The same rules apply to this as apply to the `content` option. */ - fillWith(content: Content): void; + fillWith(content?: Content): void; /** * Keydown handler. Attached when modal is focused. @@ -4073,7 +4073,7 @@ declare namespace videojs { * * @return The current MediaError when getting (or null) */ - error(err: MediaError | string | number): void; + error(err: MediaError | string | number | null): void; error(): MediaError | null; @@ -4243,7 +4243,7 @@ declare namespace videojs { * is ready to begin playback. For some browsers and all non-ready * situations, this will return `undefined`. */ - play(): Player; + play(): Promise | undefined; /** * Gets or sets the current playback rate. A playback rate of @@ -4741,7 +4741,7 @@ declare namespace videojs { * @return For advanced plugins, a factory function for that plugin. For * basic plugins, a wrapper function that initializes the plugin. */ - registerPlugin(name: string, plugin: (this: Player, options: any) => T): () => T; + registerPlugin(name: string, plugin: (this: Player, ...options: K[]) => T): (...options: K[]) => T; registerPlugin(name: string, plugin: T): () => T; }; diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index d332a430cc..814aec9edd 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -2,7 +2,11 @@ import * as videojs from 'video.js'; videojs("example_video_1").ready(function() { // EXAMPLE: Start playing the video. - this.play(); + const playPromise = this.play(); + + if (playPromise) { + playPromise.then(() => {}); + } this.pause(); From 3a7e4864a0bed4f554668cd69756cf59c293875b Mon Sep 17 00:00:00 2001 From: Kevin Mircovich Date: Fri, 3 Aug 2018 13:55:00 -0400 Subject: [PATCH 175/275] added trial_from_plan to ISubscriptionCustCreationOptions interface (#27820) This property was added to the Stripe API on 2018-05-21 [API Change Log](https://stripe.com/docs/upgrades#2018-05-21) [API Docs](https://stripe.com/docs/api#create_subscription-trial_from_plan) --- types/stripe/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index bf359012d1..e05908e579 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4679,6 +4679,12 @@ declare namespace Stripe { */ trial_period_days?: number; + /** + * Indicates if a plan’s trial_period_days should be applied to the subscription. Setting trial_end per subscription is preferred, + * and this defaults to false. Setting this flag to true together with trial_end is not allowed. + */ + trial_from_plan?: boolean; + /** * List of subscription items, each with an attached plan. */ From 8e20fb6f88558ec78f82778839d8e7177ffdc707 Mon Sep 17 00:00:00 2001 From: Elias Toivanen Date: Fri, 3 Aug 2018 20:55:18 +0300 Subject: [PATCH 176/275] @types/react-native - Add missing property textContentType for TextInputIOSProps. (#27809) * @types/react-native Add missing property `textContentType` for `TextInputIOSProps`. * Add the `textContentType` in the TextInput test --- types/react-native/index.d.ts | 48 +++++++++++++++++++++++++++++++ types/react-native/test/index.tsx | 1 + 2 files changed, 49 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2d3337c96d..abec02a1b3 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1009,6 +1009,54 @@ export interface TextInputIOSProps { * If false, disables spell-check style (i.e. red underlines). The default value is inherited from autoCorrect */ spellCheck?: boolean; + + + /** + * Give the keyboard and the system information about the expected + * semantic meaning for the content that users enter. + * + * For iOS 11+ you can set `textContentType` to `username` or `password` to + * enable autofill of login details from the device keychain. + * + * To disable autofill, set textContentType to `none`. + * + * Possible values for `textContentType` are: + * + * - `'none'` + * - `'URL'` + * - `'addressCity'` + * - `'addressCityAndState'` + * - `'addressState'` + * - `'countryName'` + * - `'creditCardNumber'` + * - `'emailAddress'` + * - `'familyName'` + * - `'fullStreetAddress'` + * - `'givenName'` + * - `'jobTitle'` + * - `'location'` + * - `'middleName'` + * - `'name'` + * - `'namePrefix'` + * - `'nameSuffix'` + * - `'nickname'` + * - `'organizationName'` + * - `'postalCode'` + * - `'streetAddressLine1'` + * - `'streetAddressLine2'` + * - `'sublocality'` + * - `'telephoneNumber'` + * - `'username'` + * - `'password'` + * + */ + textContentType?: "none" | "URL" | "addressCity" | "addressCityAndState" | + "addressState" | "countryName" | "creditCardNumber" | "emailAddress" | + "familyName" | "fullStreetAddress" | "givenName" | "jobTitle" | + "location" | "middleName" | "name" | "namePrefix" | "nameSuffix" | + "nickname" | "organizationName" | "postalCode" | "streetAddressLine1" | + "streetAddressLine2" | "sublocality" | "telephoneNumber" | "username" | + "password"; } /** diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 818be960c7..4921847c2b 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -547,6 +547,7 @@ class TextInputTest extends React.Component<{}, {username: string}> { this.username = input} + textContentType="username" value={this.state.username} onChangeText={this.handleUsernameChange} /> From aff6b6dfeb421cd0547fabe47acb5fd2406c51d6 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 3 Aug 2018 10:55:37 -0700 Subject: [PATCH 177/275] Make GridAutoValue responsive (#27827) --- types/styled-system/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index d99382e5fd..5f6e64c590 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -447,21 +447,22 @@ export interface GridRowProps { export function gridRow(...args: any[]): any; export type GridAutoValue = string; +export type ResponsiveGridAutoValue = ResponsiveValue; export interface GridAutoFlowProps { - gridAutoFlow?: GridAutoValue; + gridAutoFlow?: ResponsiveGridAutoValue; } export function gridAutoFlow(...args: any[]): any; export interface GridAutoRowsProps { - gridAutoRows?: GridAutoValue; + gridAutoRows?: ResponsiveGridAutoValue; } export function gridAutoRows(...args: any[]): any; export interface GridAutoColumnsProps { - gridAutoColumns?: GridAutoValue; + gridAutoColumns?: ResponsiveGridAutoValue; } export function gridAutoColumns(...args: any[]): any; From 630a154f1c35e96b0b7ebde4b33c4adc9dab813d Mon Sep 17 00:00:00 2001 From: nemoinho Date: Fri, 3 Aug 2018 19:57:19 +0200 Subject: [PATCH 178/275] Update redom-definitions (#27839) * Add lifecycle-events * Add exported alias `s()` and `h()` * Add definitions for ListPool, because it's exported in redom as well * Add namespace for list and svg to enable `list.extend` as described in [redom-docs](https://redom.js.org/documentation/#list-extend) --- types/redom/index.d.ts | 34 ++++++++++++++++++++++++++++++++++ types/redom/redom-tests.ts | 31 +++++++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/types/redom/index.d.ts b/types/redom/index.d.ts index 24e149258e..2814b63c61 100644 --- a/types/redom/index.d.ts +++ b/types/redom/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for redom 3.6 // Project: https://github.com/redom/redom/ // Definitions by: Rauli Laine +// Felix Nehrke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -12,18 +13,40 @@ export type RedomQueryArgument = RedomQueryArgumentValue | RedomQueryArgumentVal export interface RedomComponent { el: HTMLElement; + + update?(item: any, index: number, data: any, context?: any): void; + + onmount?(): void; + + onremount?(): void; + + onunmount?(): void; } export interface RedomComponentConstructor { new (): RedomComponent; } +export class ListPool { + constructor(View: RedomComponentConstructor, key?: string, initData?: any); + + update(data: any[], context?: any): void; +} + export class List implements RedomComponent { el: HTMLElement; constructor(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any); update(data: any[], context?: any): void; + + onmount?(): void; + + onremount?(): void; + + onunmount?(): void; + + static extend(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): RedomComponentConstructor; } export class Place implements RedomComponent { @@ -47,8 +70,10 @@ export interface RouterDictionary { } export function html(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; +export function h(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; export function el(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; +export function listPool(View: RedomComponentConstructor, key?: string, initData?: any): ListPool; export function list(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): List; export function mount(parent: RedomElement, child: RedomElement, before?: RedomElement): RedomElement; @@ -65,5 +90,14 @@ export function setStyle(view: RedomElement, arg1: string | object, arg2?: strin export function setChildren(parent: RedomElement, children: RedomElement[]): void; export function svg(query: RedomQuery, ...args: RedomQueryArgument[]): SVGElement; +export function s(query: RedomQuery, ...args: RedomQueryArgument[]): SVGElement; export function text(str: string): Text; + +export namespace list { + function extend(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): RedomComponentConstructor; +} + +export namespace svg { + function extend(query: RedomQuery): RedomComponentConstructor; +} diff --git a/types/redom/redom-tests.ts b/types/redom/redom-tests.ts index 83eb899c65..b1baff790e 100644 --- a/types/redom/redom-tests.ts +++ b/types/redom/redom-tests.ts @@ -4,13 +4,36 @@ const el1: HTMLElement = redom.el(''); const el2: HTMLElement = redom.el('p', 'Hello, World!', (el: HTMLElement) => { el.setAttribute('ok', '!'); }); const el3: HTMLElement = redom.html('p', 2, { color: 'red' }); -redom.mount(document.body!, el1); -redom.mount(document.body!, el2, el1); -redom.unmount(document.body!, el1); +redom.mount(document.body, el1); +redom.mount(document.body, el2, el1); +redom.unmount(document.body, el1); redom.setAttr(el3, 'ok', '!'); redom.setAttr(el3, { ok: '!' }); redom.setStyle(el3, { color: 'blue' }); redom.setChildren(el1, [el2, el3]); -redom.mount(document.body!, redom.text('Hello, World!')); +redom.mount(document.body, redom.text('Hello, World!')); + +class Td implements redom.RedomComponent { + el: HTMLElement; + constructor() { + this.el = redom.h('td'); + } + update(value: any) { + this.el.textContent = value; + } + onmount() { + console.log('mounted td'); + } +} +const Tr = redom.list.extend('tr', Td); +const table = redom.list('table', Tr); +table.onmount = () => console.log('mounted table'); + +table.update([ + [1, 2], + [3, 4], +]); + +redom.mount(document.body, table); From c64a75483502a48970d929fadf08d7cbb874e191 Mon Sep 17 00:00:00 2001 From: Ben Iofel Date: Fri, 3 Aug 2018 13:57:51 -0400 Subject: [PATCH 179/275] @types/graphql: is*Type() predicates can take null and undefined (#27785) * @types/graphql: is*Type() predicates can take null and undefined * add tests * use any * assert*Type() should take any * add tests --- types/graphql/graphql-tests.ts | 7 +++- types/graphql/type/definition.d.ts | 64 +++++++++++++++--------------- 2 files changed, 37 insertions(+), 34 deletions(-) diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index 7c0210249b..e75fecb329 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -1,4 +1,4 @@ -import * as graphql from 'graphql'; +import { assertInputType, isInputType, isOutputType } from 'graphql'; /////////////////////////// // graphql // @@ -50,7 +50,10 @@ function language_visitor_tests() { // graphql/type // /////////////////////////// function type_definition_tests() { - // TODO + isInputType(null); + isOutputType(null); + + assertInputType(null); } function type_directives_tests() { diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index b078acccb1..ced45be4a2 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -36,37 +36,37 @@ export function isType(type: any): type is GraphQLType; export function assertType(type: any): GraphQLType; -export function isScalarType(type: GraphQLType): type is GraphQLScalarType; +export function isScalarType(type: any): type is GraphQLScalarType; -export function assertScalarType(type: GraphQLType): GraphQLScalarType; +export function assertScalarType(type: any): GraphQLScalarType; -export function isObjectType(type: GraphQLType): type is GraphQLObjectType; +export function isObjectType(type: any): type is GraphQLObjectType; -export function assertObjectType(type: GraphQLType): GraphQLObjectType; +export function assertObjectType(type: any): GraphQLObjectType; -export function isInterfaceType(type: GraphQLType): type is GraphQLInterfaceType; +export function isInterfaceType(type: any): type is GraphQLInterfaceType; -export function assertInterfaceType(type: GraphQLType): GraphQLInterfaceType; +export function assertInterfaceType(type: any): GraphQLInterfaceType; -export function isUnionType(type: GraphQLType): type is GraphQLUnionType; +export function isUnionType(type: any): type is GraphQLUnionType; -export function assertUnionType(type: GraphQLType): GraphQLUnionType; +export function assertUnionType(type: any): GraphQLUnionType; -export function isEnumType(type: GraphQLType): type is GraphQLEnumType; +export function isEnumType(type: any): type is GraphQLEnumType; -export function assertEnumType(type: GraphQLType): GraphQLEnumType; +export function assertEnumType(type: any): GraphQLEnumType; -export function isInputObjectType(type: GraphQLType): type is GraphQLInputObjectType; +export function isInputObjectType(type: any): type is GraphQLInputObjectType; -export function assertInputObjectType(type: GraphQLType): GraphQLInputObjectType; +export function assertInputObjectType(type: any): GraphQLInputObjectType; -export function isListType(type: GraphQLType): type is GraphQLList; +export function isListType(type: any): type is GraphQLList; -export function assertListType(type: GraphQLType): GraphQLList; +export function assertListType(type: any): GraphQLList; -export function isNonNullType(type: GraphQLType): type is GraphQLNonNull; +export function isNonNullType(type: any): type is GraphQLNonNull; -export function assertNonNullType(type: GraphQLType): GraphQLNonNull; +export function assertNonNullType(type: any): GraphQLNonNull; /** * These types may be used as input types for arguments and directives. @@ -78,9 +78,9 @@ export type GraphQLInputType = | GraphQLList | GraphQLNonNull>; -export function isInputType(type: GraphQLType): type is GraphQLInputType; +export function isInputType(type: any): type is GraphQLInputType; -export function assertInputType(type: GraphQLType): GraphQLInputType; +export function assertInputType(type: any): GraphQLInputType; /** * These types may be used as output types as the result of fields. @@ -101,36 +101,36 @@ export type GraphQLOutputType = | GraphQLList >; -export function isOutputType(type: GraphQLType): type is GraphQLOutputType; +export function isOutputType(type: any): type is GraphQLOutputType; -export function assertOutputType(type: GraphQLType): GraphQLOutputType; +export function assertOutputType(type: any): GraphQLOutputType; /** * These types may describe types which may be leaf values. */ export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; -export function isLeafType(type: GraphQLType): type is GraphQLLeafType; +export function isLeafType(type: any): type is GraphQLLeafType; -export function assertLeafType(type: GraphQLType): GraphQLLeafType; +export function assertLeafType(type: any): GraphQLLeafType; /** * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; -export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; +export function isCompositeType(type: any): type is GraphQLCompositeType; -export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; +export function assertCompositeType(type: any): GraphQLCompositeType; /** * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; -export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; +export function isAbstractType(type: any): type is GraphQLAbstractType; -export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; +export function assertAbstractType(type: any): GraphQLAbstractType; /** * List Modifier @@ -188,9 +188,9 @@ export class GraphQLNonNull { export type GraphQLWrappingType = GraphQLList | GraphQLNonNull; -export function isWrappingType(type: GraphQLType): type is GraphQLWrappingType; +export function isWrappingType(type: any): type is GraphQLWrappingType; -export function assertWrappingType(type: GraphQLType): GraphQLWrappingType; +export function assertWrappingType(type: any): GraphQLWrappingType; /** * These types can all accept null as a value. @@ -204,9 +204,9 @@ export type GraphQLNullableType = | GraphQLInputObjectType | GraphQLList; -export function isNullableType(type: GraphQLType): type is GraphQLNullableType; +export function isNullableType(type: any): type is GraphQLNullableType; -export function assertNullableType(type: GraphQLType): GraphQLNullableType; +export function assertNullableType(type: any): GraphQLNullableType; export function getNullableType(type: void): undefined; export function getNullableType(type: T): T; @@ -223,9 +223,9 @@ export type GraphQLNamedType = | GraphQLEnumType | GraphQLInputObjectType; -export function isNamedType(type: GraphQLType): type is GraphQLNamedType; +export function isNamedType(type: any): type is GraphQLNamedType; -export function assertNamedType(type: GraphQLType): GraphQLNamedType; +export function assertNamedType(type: any): GraphQLNamedType; export function getNamedType(type: void): undefined; export function getNamedType(type: GraphQLType): GraphQLNamedType; From fb1b2554a8cc4ddcfd6c51c67154846b4e1544f7 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 19:59:09 +0200 Subject: [PATCH 180/275] Chrome-apps better coverage, cleanup and fixes (#27849) * Bugfixes: Webview is an HTMLElement and also frame must be of type chrome to set options * Bugfixes: Webview is an HTMLElement and also frame must be of type chrome to set options * Bluetooth Socket: typings complete * Bluetooth tests * Fix typo * Typo fix * HID typings, but missing documentation * Documentation and testing added * InstanceID Typings * Typings for mdns complete * typings for chrome.syncFileSystem * Major cleanup - comments and documentation review * More cleanup, comment shortening, bugfixing, updates * Cleanup and fixes: Continued (WIP) * Fixed and cleanup: idle, instanceId, mediaGalleries (+added docs) * Transfer types to enums * networking.onc -> complete api typing, Enums to types to prevent runtime errors * Restored enums that are present (after checking) * Implemented desktopCapture * Added management * Typings for experimental clipboard api * chrome.networking.onc: Documentation + fixes * Removed unnecessary imports and compiler options. * Bumped typescript version to support new language features. * Cleanup: No need to specify defaults --- types/chrome-apps/index.d.ts | 6737 +++++++++++++++++++++---------- types/chrome-apps/test/index.ts | 231 +- 2 files changed, 4897 insertions(+), 2071 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index a1713aa6f9..07437c787a 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 +// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingconst Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /// @@ -12,25 +12,55 @@ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// declare namespace chrome { - //////////////////// - // Accessibility Features - //////////////////// + ////////////// + // INTERNAL // + ////////////// + + /** @deprecated Could be used, if e.g. deprecated recently */ + type deprecatedButUsable = any; + + /** @deprecated Should never be used, used to guide migrations. */ + type deprecated = never; + + // Not proper types, but used to give the programmer a hint // + /** + * Integer + */ + type integer = number; + /** + * Double + */ + type double = number; + + + //////////////////////////// + // Accessibility Features // + //////////////////////////// + /** + * @requires Important: This API works only on Chrome OS. + * @requires Permissions: + * 'accessibilityFeatures.read' (For read access) + * 'accessibilityFeatures.modify' (For modifications) + * Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. + * @since Available since Chrome 37. + * @description * Use the chrome.accessibilityFeatures API to manage Chrome's accessibility features. * This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. * In order to get feature states the extension must request accessibilityFeatures.read permission. * For modifying feature state, the extension needs accessibilityFeatures.modify permission. * Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. - * Permissions: 'accessibilityFeatures.read' (For read access); 'accessibilityFeatures.modify' (For modifications; Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission.) - * Important: This API works only on Chrome OS. - * @since Availability: Since Chrome 37. */ namespace accessibilityFeatures { interface AccessibilityFeaturesGetArg { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ + /** Whether to return the value that applies to the incognito session (default false). */ incognito?: boolean; } + type LevelOfControl = + 'not_controllable' | 'controlled_by_other_extensions' | + 'controllable_by_this_extension' | 'controlled_by_this_extension'; + interface AccessibilityFeaturesCallbackArg { /** The value of the setting. */ value: any; @@ -41,11 +71,13 @@ declare namespace chrome { * • controllable_by_this_extension: can be controlled by this extension * • controlled_by_this_extension: controlled by this extension */ - levelOfControl: 'not_controllable' | 'controlled_by_other_extensions' | 'controllable_by_this_extension' | 'controlled_by_this_extension'; - /** Optional. Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ + levelOfControl: LevelOfControl; + /** Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ incognitoSpecific?: boolean; } + type Scope = 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + interface AccessibilityFeaturesSetArg { /** * The value of the setting. @@ -53,26 +85,24 @@ declare namespace chrome { */ value: any; /** - * Optional. - * The scope of the ChromeSetting. One of + * The scope of the ChromeSetting. One of * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), * • regular_only: setting for the regular profile only (not inherited by the incognito profile), * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + scope?: Scope; } interface AccessibilityFeaturesClearArg { /** - * Optional. - * The scope of the ChromeSetting. One of + * The scope of the ChromeSetting. One of * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), * • regular_only: setting for the regular profile only (not inherited by the incognito profile), * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + scope?: Scope; } interface AccessibilityFeaturesSetting { @@ -104,83 +134,85 @@ declare namespace chrome { /** * Spoken feedback (text-to-speech). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var spokenFeedback: AccessibilityFeaturesSetting; + const spokenFeedback: AccessibilityFeaturesSetting; /** * Enlarged cursor. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var largeCursor: AccessibilityFeaturesSetting; + const largeCursor: AccessibilityFeaturesSetting; /** * Sticky modifier keys (like shift or alt). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var stickyKeys: AccessibilityFeaturesSetting; + const stickyKeys: AccessibilityFeaturesSetting; /** * High contrast rendering mode. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var highContrast: AccessibilityFeaturesSetting; + const highContrast: AccessibilityFeaturesSetting; /** * Full screen magnification. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var screenMagnifier: AccessibilityFeaturesSetting; + const screenMagnifier: AccessibilityFeaturesSetting; /** * Auto mouse click after mouse stops moving. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var autoclick: AccessibilityFeaturesSetting; + const autoclick: AccessibilityFeaturesSetting; /** * Virtual on-screen keyboard. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var virtualKeyboard: AccessibilityFeaturesSetting; + const virtualKeyboard: AccessibilityFeaturesSetting; /** * Caret highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var caretHighlight: AccessibilityFeaturesSetting; + const caretHighlight: AccessibilityFeaturesSetting; /** * Cursor highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var cursorHighlight: AccessibilityFeaturesSetting; + const cursorHighlight: AccessibilityFeaturesSetting; /** * Focus highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var focusHighlight: AccessibilityFeaturesSetting; + const focusHighlight: AccessibilityFeaturesSetting; /** * Select-to-speak. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var selectToSpeak: AccessibilityFeaturesSetting; + const selectToSpeak: AccessibilityFeaturesSetting; /** * Switch access. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var switchAccess: AccessibilityFeaturesSetting; + const switchAccess: AccessibilityFeaturesSetting; /** * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 42. */ - export var animationPolicy: AccessibilityFeaturesSetting; + const animationPolicy: AccessibilityFeaturesSetting; } - //////////////////// - // Alarms - //////////////////// + //////////// + // Alarms // + //////////// /** - * Use the chrome.alarms API to schedule code to run periodically or at a specified time in the future. - * Permissions: 'alarms' + * @requires Permissions: 'alarms' * @since Availability: Since Chrome 22. + * @description + * Use the chrome.alarms API to schedule code to run + * periodically or at a specified time in the future. */ namespace alarms { interface AlarmCreateInfo { - /** Optional. Length of time in minutes after which the onAlarm event should fire. */ + /** Length of time in minutes after which the onAlarm event should fire. */ delayInMinutes?: number; - /** Optional. If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ + /** If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ periodInMinutes?: number; - /** Optional. Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ + /** Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ when?: number; } interface Alarm { - /** Optional. If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ + /** If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ periodInMinutes?: number; /** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. Date.now() + n). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */ scheduledTime: number; @@ -198,7 +230,7 @@ declare namespace chrome { * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. */ - export function create(alarmInfo: AlarmCreateInfo): void; + function create(alarmInfo: AlarmCreateInfo): void; /** * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. * If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. @@ -209,64 +241,92 @@ declare namespace chrome { * @param name Optional name to identify this alarm. Defaults to the empty string. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. */ - export function create(name: string, alarmInfo: AlarmCreateInfo): void; + function create(name: string, alarmInfo: AlarmCreateInfo): void; /** * Gets an array of all the alarms. * @param callback The callback parameter should be a function that looks like this: * @example function(array of Alarm alarms) {...}; */ - export function getAll(callback: (alarms: Alarm[]) => void): void; + function getAll(callback: (alarms: Alarm[]) => void): void; /** * Clears all alarms. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clearAll(callback?: (wasCleared: boolean) => void): void; + function clearAll(callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm with the given name. * @param name The name of the alarm to clear. Defaults to the empty string. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clear(name?: string, callback?: (wasCleared: boolean) => void): void; + function clear(name?: string, callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm without a name. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clear(callback: (wasCleared: boolean) => void): void; + function clear(callback: (wasCleared: boolean) => void): void; /** * Retrieves details about the specified alarm. * @param callback The callback parameter should be a function that looks like this: * @example function( Alarm alarm) {...}; */ - export function get(callback: (alarm: Alarm) => void): void; + function get(callback: (alarm: Alarm) => void): void; /** * Retrieves details about the specified alarm. * @param name The name of the alarm to get. Defaults to the empty string. * @param callback The callback parameter should be a function that looks like this: * @example function( Alarm alarm) {...}; */ - export function get(name: string, callback: (alarm: Alarm) => void): void; + function get(name: string, callback: (alarm: Alarm) => void): void; /** Fired when an alarm has elapsed. Useful for event pages. */ - export var onAlarm: AlarmEvent; + const onAlarm: AlarmEvent; } - //////////////////// - // App Runtime - //////////////////// - + ///////////////// + // App Runtime // + ///////////////// /** - * Use the chrome.app.runtime API to manage the app lifecycle. - * The app runtime manages app installation, controls the event page, and can shut down the app at anytime. * @since Availability: Since Chrome 24. + * @description + * Use the chrome.app.runtime API to manage the app lifecycle. + * The app runtime manages app installation, controls the event page, + * and can shut down the app at anytime. */ namespace app.runtime { - type LaunchSource = 'untracked' | 'app_launcher' | 'new_tab_page' | 'reload' | 'restart' | - 'load_and_launch' | 'command_line' | 'file_handler' | 'url_handler' | 'system_tray' | - 'about_page' | 'keyboard' | 'extensions_page' | 'management_api' | 'ephemeral_app' | - 'background' | 'kiosk' | 'chrome_internal' | 'test' | 'installed_notification' | 'context_menu'; + /** + * @todo TODO UNDOCUMENTED? + */ + enum PlayStoreStatus { + ENABLED = 'enabled', + AVAILABLE = 'available', + UNKNOWN = 'unknown' + } + enum LaunchSource { + ABOUT_PAGE = "about_page", + APP_LAUNCHER = "app_launcher", + BACKGROUND = "background", + CHROME_INTERNAL = "chrome_internal", + COMMAND_LINE = "command_line", + CONTEXT_MENU = "context_menu", + EPHEMERAL_APP = "ephemeral_app", + EXTENSIONS_PAGE = "extensions_page", + FILE_HANDLER = "file_handler", + INSTALLED_NOTIFICATION = "installed_notification", + KEYBOARD = "keyboard", + KIOSK = "kiosk", + LOAD_AND_LAUNCH = "load_and_launch", + MANAGEMENT_API = "management_api", + NEW_TAB_PAGE = "new_tab_page", + RELOAD = "reload", + RESTART = "restart", + SYSTEM_TRAY = "system_tray", + TEST = "test", + UNTRACKED = "untracked", + URL_HANDLER = "url_handler" + } interface EmbedRequest { /** @@ -285,6 +345,10 @@ declare namespace chrome { type actionType = 'new_note'; + const ActionType: { + NEW_NOTE: actionType + } + interface LaunchData { /** * The ID of the file or URL handler that the app is being invoked with. @@ -319,7 +383,7 @@ declare namespace chrome { /** * Contains data that specifies the ActionType this app was launched with. This is null if the app was not launched with a specific action intent. * ______________________________________________________________________________ - * | enum of 'new_note' | actionType | new_note | + * | type of 'new_note' | actionType | new_note | * | | | The user wants to quickly take a new note. | * |____________________|____________|____________________________________________| * @since Since Chrome 54. @@ -338,41 +402,36 @@ declare namespace chrome { type?: string; } - interface EmbedRequestedEvent extends chrome.events.Event<(request: EmbedRequest) => void> { } - - interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> { } - - interface RestartedEvent extends chrome.events.Event<() => void> { } - /** * Fired when an embedding app requests to embed this app. This event is only available on dev channel with the flag --enable-app-view. * @since Since Chrome 38. */ - export var onEmbedRequest: EmbedRequestedEvent; + const onEmbedRequest: chrome.events.Event<(request: EmbedRequest) => void>; /** * Fired when an app is launched from the launcher. */ - export var onLaunched: LaunchedEvent; + const onLaunched: chrome.events.Event<(launchData: LaunchData) => void>; /** * Fired at Chrome startup to apps that were running when Chrome last shut down, * or when apps have been requested to restart from their previous state for other reasons * (e.g. when the user revokes access to an app's retained files the runtime will restart the app). * In these situations if apps do not have an onRestarted handler they will be sent an onLaunched event instead. */ - export var onRestarted: RestartedEvent; + const onRestarted: chrome.events.Event<() => void>; } //////////////////// // App Window //////////////////// /** + * @since Availability: Since Chrome 24. + * @description * Use the chrome.app.window API to create windows. * Windows have an optional frame with title bar and size controls. * They are not associated with any Chrome browser windows. * See the Window State Sample for a demonstration of these options. - * @since Availability: Since Chrome 24. */ - namespace app.window { + namespace app { interface ContentBounds { left?: number; top?: number; @@ -448,7 +507,7 @@ declare namespace chrome { * For none, the -webkit-app-region CSS property can be used to apply draggability to the app's window. * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. */ - type?: 'chrome'; + type: 'chrome'; /** * Allows the frame color to be set. Frame coloring is only available if the frame type is chrome. * @since Frame coloring is new in Chrome 36. @@ -468,6 +527,13 @@ declare namespace chrome { inactiveColor?: string; } + enum State { + NORMAL = 'normal', + FULLSCREEN = 'fullscreen', + MAXIMIZED = 'maximized', + MINIMIZED = 'minimized' + } + interface CreateWindowOptions { /** * Id to identify the window. @@ -545,7 +611,7 @@ declare namespace chrome { /** * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. */ - state?: 'normal' | 'fullscreen' | 'maximized' | 'minimized'; + state?: State; /** * If true, the window will be created in a hidden state. Call show() on the window to show it once it has been created. Defaults to false. */ @@ -578,7 +644,6 @@ declare namespace chrome { */ visibleOnAllWorkspaces?: boolean; } - interface AppWindow { /** Focus the window. */ focus: () => void; @@ -627,7 +692,7 @@ declare namespace chrome { hide: () => void; /** * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. - * @description Get the window's inner bounds as a ContentBounds object. + * Get the window's inner bounds as a ContentBounds object. */ getBounds: () => ContentBounds; /** @@ -676,52 +741,81 @@ declare namespace chrome { onRestored: WindowEvent; } interface WindowEvent extends chrome.events.Event<() => void> { } - /** - * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. - * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). - * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. - * - * @param url - * @param [options] - * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; - */ - export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; - /** - * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). - */ - export function current(): AppWindow; - /** - * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. - */ - export function get(id: string): AppWindow; - /** - * Gets an array of all currently created app windows. This method is new in Chrome 33. - */ - export function getAll(): AppWindow[]; - /** - * Whether the current platform supports windows being visible on all workspaces. - */ - export function canSetVisibleOnAllWorkspaces(): boolean; - } + interface WindowParams extends AppWindow { + id: string; + frameId?: integer; + existingWindow?: boolean; + [key: string]: any; + } + + interface ChromeAppWindow extends AppWindow { + /** + * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. + * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). + * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. + * + * @param url + * @param [options] + * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; + */ + create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; + /** + * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). + */ + current(): AppWindow; + /** + * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. + */ + get(id: string): AppWindow; + /** + * Gets an array of all currently created app windows. This method is new in Chrome 33. + */ + getAll(): AppWindow[]; + /** + * Whether the current platform supports windows being visible on all workspaces. + */ + canSetVisibleOnAllWorkspaces(): boolean; + + + /** + * Undocumented + * @todo TODO Find info + * definition app.window.initializeAppWindow(state: object) + * @internal + */ + initializeAppWindow(state: WindowParams): void; + } + const window: ChromeAppWindow; + } //////////////////// // Audio //////////////////// /** - * The chrome.audio API is provided to allow users to get information about and control the audio devices attached to the system. - * This API is currently only implemented for ChromeOS. * @since Since Chrome 59. + * @requires Permissions: 'audio' + * @description + * The chrome.audio API is provided to allow users to get information + * about and control the audio devices attached to the system. + * This API is currently only implemented for ChromeOS. */ namespace audio { - export type StreamType = 'INPUT' | 'OUTPUT'; + type StreamType = 'INPUT' | 'OUTPUT'; + type DeviceType = + 'HEADPHONE' | 'MIC' | 'USB' | + 'BLUETOOTH' | 'HDMI' | 'INTERNAL_SPEAKER' | + 'INTERNAL_MIC' | 'FRONT_MIC' | 'REAR_MIC' | + 'KEYBOARD_MIC' | 'HOTWORD' | 'LINEOUT' | + 'POST_MIX_LOOPBACK' | 'POST_DSP_LOOPBACK' | 'OTHER'; + interface AudioDeviceInfo { /** The unique identifier of the audio device. */ id: string; /** Stream type associated with this device. */ streamType: StreamType; /** Type of the device. */ - deviceType: 'HEADPHONE' | 'MIC' | 'USB' | 'BLUETOOTH' | 'HDMI' | 'INTERNAL_SPEAKER' | 'INTERNAL_MIC' | 'FRONT_MIC' | 'REAR_MIC' | 'KEYBOARD_MIC' | 'HOTWORD' | 'LINEOUT' | 'POST_MIX_LOOPBACK' | 'POST_DSP_LOOPBACK' | 'OTHER'; + deviceType: DeviceType; /** The user-friendly name (e.g. 'USB Microphone'). */ displayName: string; /** Device name. */ @@ -750,35 +844,24 @@ declare namespace chrome { * The audio device's desired sound level. Defaults to the device's current sound level. * If used with audio input device, represents audio device gain. * If used with audio output device, represents audio device volume. - * - * Type: integer */ - level?: number; + level?: integer; } + /** @todo TODO INTEGRATE */ interface OnLevelChangedEvent { - /** - * The callback parameter should be a function that looks like this: - * function(object event) {...}; - * @param {(event: { - * deviceId: string, - * level: number - * }) => void} callback - */ addListener(callback: (event: { deviceId: string, level: number }) => void): void; } + /** @todo TODO INTEGRATE */ interface OnMuteChangedEvent { - /** - * The callback parameter should be a function that looks like this: - * function(object event) {...}; - */ addListener(callback: (event: { streamType: StreamType[], isMuted: boolean }) => void): void; } + /** @todo TODO INTEGRATE */ interface OnDeviceListChangedEvent { /** * The callback parameter should be a function that looks like this: @@ -801,42 +884,44 @@ declare namespace chrome { isActive?: boolean; } /** - * @description Gets a list of audio devices filtered based on |filter|. + * Gets a list of audio devices filtered based on |filter|. */ - export function getDevices(filter: Filter, callback: (devices: AudioDeviceInfo[]) => void): void; - export function getDevices(callback: (devices: AudioDeviceInfo[]) => void): void; + function getDevices(filter: Filter, callback: (devices: AudioDeviceInfo[]) => void): void; + function getDevices(callback: (devices: AudioDeviceInfo[]) => void): void; /** Sets lists of active input and/or output devices. */ - export function setDevices(ids: DeviceIdLists[] | string[], callback: () => void): void; + function setDevices(ids: DeviceIdLists[] | string[], callback: () => void): void; /** Sets the properties for the input or output device. */ - export function setProperties(id: string, properties: SetDeviceProperties, callback: () => void): void; + function setProperties(id: string, properties: SetDeviceProperties, callback: () => void): void; /** - * @description Gets the system-wide mute state for the specified stream type. + * Gets the system-wide mute state for the specified stream type. * @param {StreamType} streamType Stream type for which mute state should be fetched. - * @param {(value: boolean) => {}} callback Callback reporting whether mute is set or not for specified stream type. + * @param {(value: boolean)=> void} callback Callback reporting whether mute is set or not for specified stream type. */ - export function getMute(streamType: StreamType, callback: (value: boolean) => void): void; + function getMute(streamType: StreamType, callback: (value: boolean) => void): void; /** - * @description Sets mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type. + * Sets mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type. * @param {StreamType} streamType Stream type for which mute state should be set. * @param {boolean} isMuted New mute value. - * @param {() => {}} [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; + * @param {()=> void} [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; */ - export function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; + function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; /** Fired when sound level changes for an active audio device. */ - export var onLevelChanged: OnLevelChangedEvent; + const onLevelChanged: OnLevelChangedEvent; /** Fired when the mute state of the audio input or output changes. Note that mute state is system-wide and the new value applies to every audio device with specified stream type. */ - export var onMuteChanged: OnMuteChangedEvent; + const onMuteChanged: OnMuteChangedEvent; /** Fired when audio devices change, either new devices being added, or existing devices being removed. */ - export var onDeviceListChanged: OnDeviceListChangedEvent; + const onDeviceListChanged: OnDeviceListChangedEvent; } - //////////////////// - // Bluetooth - //////////////////// + /////////////// + // Bluetooth // + /////////////// /** - * Use the chrome.bluetooth API to connect to a Bluetooth device. All functions report failures via chrome.runtime.lastError. - * Manifest: 'bluetooth': {...} * @since Chrome 37 + * @requires Manifest: 'bluetooth': {...} + * @description + * Use the chrome.bluetooth API to connect to a Bluetooth device. + * All functions report failures via chrome.runtime.lastError. */ namespace bluetooth { interface AdapterState { @@ -851,6 +936,14 @@ declare namespace chrome { /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } + type DeviceType = + 'computer' | 'phone' | 'modem' | + 'audio' | 'carAudio' | 'video' | + 'peripheral' | 'joystick' | 'gamepad' | + 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + + type DeviceVendorIdSource = 'bluetooth' | 'usb'; + interface Device { /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; @@ -859,7 +952,7 @@ declare namespace chrome { /** The class of the device, a bit-field defined by http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband. */ deviceClass?: number; /** The Device ID record of the device, where available. */ - vendorIdSource?: 'bluetooth' | 'usb'; + vendorIdSource?: DeviceVendorIdSource; vendorId?: number; productId?: number; deviceId?: number; @@ -868,7 +961,7 @@ declare namespace chrome { * This is obtained from the |deviceClass| field and only represents a small fraction of the possible device types. * When in doubt you should use the |deviceClass| field directly. */ - type?: 'computer' | 'phone' | 'modem' | 'audio' | 'carAudio' | 'video' | 'peripheral' | 'joystick' | 'gamepad' | 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + type?: DeviceType; /** Indicates whether or not the device is paired with the system. */ paired?: boolean; /** Indicates whether the device is currently connected to the system. */ @@ -906,47 +999,67 @@ declare namespace chrome { addListener(callback: (event: T) => void): void; } + type DeviceFilterType = 'all' | 'known'; + /** * Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. */ interface DeviceFilter { /** Type of filter to apply to the device list. Default is all. */ - filterType?: 'all' | 'known'; + filterType?: DeviceFilterType; /** Maximum number of bluetoth devices to return. Default is 0 (no limit) if unspecified. */ limit?: number; } /** Get information about the Bluetooth adapter. */ - export function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; + function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; + /** Get information about a Bluetooth device known to the system. */ - export function getDevice(deviceAddress: string, callback: (deviceInfo: Device) => void): void; + function getDevice(deviceAddress: string, callback: (deviceInfo: Device) => void): void; + + /** + * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. + * @param callback Called when the search is completed. + */ + function getDevices(callback: (devices: Device[]) => void): void; + /** * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. * @param filter Since Chrome 67. Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. * @param callback Called when the search is completed. */ - export function getDevices(filter: DeviceFilter, callback: (deviceInfo: Device) => void): void; + function getDevices(filter: DeviceFilter, callback: (devices: Device[]) => void): void; + /** * Start discovery. Newly discovered devices will be returned via the onDeviceAdded event. Previously discovered devices already known to the adapter must be obtained using getDevices and will only be updated using the |onDeviceChanged| event if information about them changes. * Discovery will fail to start if this application has already called startDiscovery. Discovery can be resource intensive: stopDiscovery should be called as soon as possible. */ - export function startDiscovery(callback: () => void): void; + function startDiscovery(callback: () => void): void; + /** Stop discovery. */ - export function stopDiscovery(callback: () => void): void; + function stopDiscovery(callback: () => void): void; + /** Fired when the state of the Bluetooth adapter changes. */ - export var onAdapterStateChanged: BluetoothEvent; + const onAdapterStateChanged: BluetoothEvent; + /** Fired when information about a new Bluetooth device is available. */ - export var onDeviceAdded: BluetoothEvent; + const onDeviceAdded: BluetoothEvent; + /** Fired when information about a known Bluetooth device has changed. */ - export var onDeviceChanged: BluetoothEvent; + const onDeviceChanged: BluetoothEvent; + /** Fired when a Bluetooth device that was previously discovered has been out of range for long enough to be considered unavailable again, and when a paired device is removed. */ - export var onDeviceRemoved: BluetoothEvent; + const onDeviceRemoved: BluetoothEvent; } + /** - * The chrome.bluetoothLowEnergy API is used to communicate with Bluetooth Smart (Low Energy) devices using the Generic Attribute Profile (GATT). - * Manifest: 'bluetooth': {...} * @since Chrome 37 - * Important: This API works only on Chrome OS. - * Note: With Chrome 56, users can select nearby Bluetooth Low Energy devices to provide to web sites that use the Web Bluetooth API. + * @requires Manifest: 'bluetooth': {...} + * @requires Important: This API works only on Chrome OS. + * @requires Note: With Chrome 56, users can select nearby Bluetooth Low Energy devices to provide to web sites that use the Web Bluetooth API. + * @description + * The chrome.bluetoothLowEnergy API is used to communicate + * with Bluetooth Smart (Low Energy) devices using the + * Generic Attribute Profile (GATT). */ namespace bluetoothLowEnergy { interface Service { @@ -966,22 +1079,21 @@ declare namespace chrome { */ deviceAddress?: string; } - enum CharacteristicProperties { - 'broadcast', - 'read', - 'writeWithoutResponse', - 'write', - 'notify', - 'indicate', - 'authenticatedSignedWrites', - 'extendedProperties', - 'reliableWrite', - 'writableAuxiliaries', - 'encryptRead', - 'encryptWrite', - 'encryptAuthenticatedRead', - 'encryptAuthenticatedWrite' - } + type CharacteristicProperties = + 'broadcast' | + 'read' | + 'writeWithoutResponse' | + 'write' | + 'notify' | + 'indicate' | + 'authenticatedSignedWrites' | + 'extendedProperties' | + 'reliableWrite' | + 'writableAuxiliaries' | + 'encryptRead' | + 'encryptWrite' | + 'encryptAuthenticatedRead' | + 'encryptAuthenticatedWrite'; interface Characteristic { /** The UUID of the characteristic, e.g. 00002a37-0000-1000-8000-00805f9b34fb. */ uuid: string; @@ -994,14 +1106,14 @@ declare namespace chrome { /** The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication. */ value?: ArrayBuffer; } - enum DescriptorPermissions { - 'read', - 'write', - 'encryptedRead', - 'encryptedWrite', - 'encryptedAuthenticatedRead', - 'encryptedAuthenticatedWrite' - } + type DescriptorPermissions = + 'read' | + 'write' | + 'encryptedRead' | + 'encryptedWrite' | + 'encryptedAuthenticatedRead' | + 'encryptedAuthenticatedWrite'; + interface Descriptor { /** The UUID of the characteristic descriptor, e.g. 00002902-0000-1000-8000-00805f9b34fb. */ uuid: string; @@ -1049,9 +1161,7 @@ declare namespace chrome { /** Optional flag for sending an indication instead of a notification. */ shouldIndicate: boolean; } - enum AdvertisementType { - 'broadcast', 'peripheral' - } + type AdvertisementType = 'broadcast' | 'peripheral'; interface Advertisement { /** Type of advertisement. */ type: AdvertisementType; @@ -1098,7 +1208,7 @@ declare namespace chrome { */ function getService(serviceId: string, callback: (result: Service) => void): void; /** - * @description Create a locally hosted GATT service. This service can be registered to be available on a local GATT server. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * Create a locally hosted GATT service. This service can be registered to be available on a local GATT server. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param service The service to create. * @param callback Called with the created services's unique ID. @@ -1118,7 +1228,7 @@ declare namespace chrome { */ function getCharacteristic(characteristicId: string, callback: (result: Characteristic) => void): void; /** - * @description Create a locally hosted GATT characteristic. This characteristic must be hosted under a valid service. If the service ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * Create a locally hosted GATT characteristic. This characteristic must be hosted under a valid service. If the service ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param characteristic The characteristic to create. * @param serviceId ID of the service to create this characteristic for. @@ -1226,7 +1336,7 @@ declare namespace chrome { * @param serviceId Unique ID of a created service. * @param callback Callback with the result of the register operation. */ - function registerService(serviceId: string, callback: () => void): void; + function registerService(serviceId: string, callback: (result: any) => void): void; /** * Unregister the given service with the local GATT server. * If the service ID is invalid, the lastError will be set. @@ -1237,7 +1347,7 @@ declare namespace chrome { * @param serviceId Unique ID of a current registered service. * @param callback Callback with the result of the register operation. */ - function unregisterService(serviceId: string, callback: () => void): void; + function unregisterService(serviceId: string, callback: (result: any) => void): void; /** * Remove the specified service, unregistering it if it was registered. * If the service ID is invalid, the lastError will be set. @@ -1286,7 +1396,7 @@ declare namespace chrome { /** * Set's the interval betweeen two consecutive advertisements. * Note: This is a best effort. - * The actual interval may vary non-trivially from the requested intervals. + * The actual interval may consty non-trivially from the requested intervals. * On some hardware, there is a minimum interval of 100ms. * The minimum and maximum values cannot exceed the the range allowed by the Bluetooth 4.2 specification. * @since Since Chrome 55. @@ -1302,16 +1412,16 @@ declare namespace chrome { */ function sendRequestResponse(response: IResponse): void; /** Fired whan a new GATT service has been discovered on a remote device. */ - var onServiceAdded: chrome.events.Event<(service: Service) => void>; + const onServiceAdded: chrome.events.Event<(service: Service) => void>; /** * Fired when the state of a remote GATT service changes. * This involves any characteristics and/or descriptors * that get added or removed from the service, as well as - * "ServiceChanged" notifications from the remote device. + * 'ServiceChanged' notifications from the remote device. */ - var onServiceChanged: chrome.events.Event<(service: Service) => void>; + const onServiceChanged: chrome.events.Event<(service: Service) => void>; /** Fired when a GATT service that was previously discovered on a remote device has been removed. */ - var onServiceRemoved: chrome.events.Event<(service: Service) => void>; + const onServiceRemoved: chrome.events.Event<(service: Service) => void>; /** * Fired when the value of a remote GATT characteristic changes, * either as a result of a read request, @@ -1319,14 +1429,14 @@ declare namespace chrome { * This event will only be sent if the app has enabled notifications * by calling startCharacteristicNotifications. */ - var onCharacteristicValueChanged: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicValueChanged: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when the value of a remote GATT characteristic descriptor changes, * usually as a result of a read request. * This event exists mostly for convenience and will always be sent after * a successful call to readDescriptorValue. */ - var onDescriptorValueChanged: chrome.events.Event<(descriptor: Descriptor) => void>; + const onDescriptorValueChanged: chrome.events.Event<(descriptor: Descriptor) => void>; /** * Fired when a connected central device requests to read the value of * a characteristic registered on the local GATT server. @@ -1336,7 +1446,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onCharacteristicReadRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicReadRequest: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when a connected central device requests to write the value of * a characteristic registered on the local GATT server. @@ -1346,7 +1456,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onCharacteristicWriteRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicWriteRequest: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when a connected central device requests to read the value of * a descriptor registered on the local GATT server. @@ -1356,7 +1466,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onDescriptorReadRequest: chrome.events.Event<(descriptor: Descriptor) => void>; + const onDescriptorReadRequest: chrome.events.Event<(descriptor: Descriptor) => void>; /** * Fired when a connected central device requests to write the value of * a descriptor registered on the local GATT server. @@ -1365,22 +1475,341 @@ declare namespace chrome { * and the bluetooth:peripheral permissions set to true. * The peripheral permission may not be available to all apps. */ - var onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; - } - /** - * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. - * @since Chrome 37 - * Manifest: 'bluetooth': {...} - * Important: This API works only on OS X, Windows and Chrome OS. - */ - namespace bluetoothSocket { - /* NOT IMPLEMENTED YET */ + const onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; } - //////////////////// - // Browser - //////////////////// /** + * @since Chrome 37 + * @requires Manifest: 'bluetooth': {...} + * @requires Important: This API works only on OS X, Windows and Chrome OS. + * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. + */ + namespace bluetoothSocket { + interface SocketProperties { + /** + * Flag indicating whether the socket is left open when + * the event page of the application is unloaded + * (see Manage App Lifecycle). The default value is false. + * When the application is loaded, any sockets previously + * opened with persistent=true can be fetched with $ref:getSockets. + */ + persistent?: boolean; + /** An application-defined string associated with the socket. */ + name?: string; + /** + * @default 4096 + * @description + * The size of the buffer used to receive data. + * */ + bufferSize?: integer; + } + interface ListenOptions { + /** + * The RFCOMM Channel used by listenUsingRfcomm. + * If specified, this channel must not be previously + * in use or the method call will fail. When not specified, + * an unused channel will be automatically allocated. + */ + channel?: integer; + /** + * The L2CAP PSM used by listenUsingL2cap. + * If specified, this PSM must not be previously + * in use or the method call with fail. When not specified, + * an unused PSM will be automatically allocated. + * */ + psm?: integer; + /** + * Length of the socket's listen queue. + * The default value depends on the operating system's host subsystem. + * */ + backlog?: number; + } + interface SocketInfo { + /** + * The socket identifier. + * */ + socketId: integer; + /** + * Flag indicating if the socket remains + * open when the event page of the application + * is unloaded (see SocketProperties.persistent). + * The default value is 'false'. + */ + persistent: boolean; + /** + * Application-defined string associated with the socket. + */ + name?: string; + /** + * The size of the buffer used to receive data. + * If no buffer size has been specified explictly, + * the value is not provided. + */ + bufferSize?: integer; + /** + * Flag indicating whether a connected socket + * blocks its peer from sending more data, or + * whether connection requests on a listening + * socket are dispatched through the onAccept + * event or queued up in the listen queue backlog. + * See setPaused. The default value is 'false'. + */ + paused: boolean; + /** + * Flag indicating whether the socket is connected to a remote peer. + */ + connected: boolean; + /** + * If the underlying socket is connected, + * contains the Bluetooth address of the device it is connected to. + */ + address?: string; + /** + * If the underlying socket is connected, + * contains information about the service + * UUID it is connected to, otherwise if + * the underlying socket is listening, + * contains information about the service + * UUID it is listening on. + */ + uuid?: string; + } + + interface CreateInfo { + /** + * The ID of the newly created socket. + * Note that socket IDs created from this + * API are not compatible with socket IDs + * created from other APIs, such as the + * sockets.tcp API. + */ + socketId: integer; + } + interface OnAcceptInfoData { + /** The server socket identifier. */ + socketId: integer; + /** + * The client socket identifier, i.e. the socket + * identifier of the newly established connection. + * This socket identifier should be used only with + * functions from the chrome.bluetoothSocket namespace. + * Note the client socket is initially paused and must + * be explictly un-paused by the application to start + * receiving data. + */ + clientSocketId: integer; + } + type OnAcceptErrorCode = + 'system_error' | + 'not_listening'; + interface OnAcceptErrorEventData { + /** The server socket identifier. */ + socketId: integer; + /** The error message */ + errorMessage: string; + /** + * An error code indicating what went wrong. + * + * system_error + * > A system error occurred and the connection may be unrecoverable. + * not_listening + * > The socket is not listening. + */ + error: OnAcceptErrorCode; + } + interface OnReceiveEventData { + /** The socket identifier. */ + socketId: integer; + /** The data received, with a maxium size of bufferSize. */ + data: ArrayBuffer; + } + type OnReceiveErrorCode = + 'disconnected' | + 'system_error' | + 'not_connected'; + interface OnReceiveErrorEventData { + /** The server socket identifier. */ + socketId: integer; + /** The error message */ + errorMessage: string; + /** + * An error code indicating what went wrong. + * + * disconnected + * > The connection was disconnected. + * system_error + * > A system error occurred and the connection may be unrecoverable. + * not_connected + * > The socket has not been connected. + */ + error: OnAcceptErrorCode; + } + interface OnAcceptEvent extends chrome.events.Event<(info: OnAcceptInfoData) => void> { } + interface OnAcceptErrorEvent extends chrome.events.Event<(info: OnAcceptErrorEventData) => void> { } + interface OnReceiveEvent extends chrome.events.Event<(info: OnReceiveEventData) => void> { } + interface OnReceiveErrorEvent extends chrome.events.Event<(info: OnReceiveErrorEventData) => void> { } + /** + * Creates a Bluetooth socket. + * @param callback Called when the socket has been created + * */ + function create(callback: (createInfo: CreateInfo) => void): void; + /** + * Creates a Bluetooth socket. + * @param properties The socket properties (optional) + * @param callback Called when the socket has been created + */ + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + /** + * Updates the socket properties. + * @param socketId The socket identifier. + * @param properties The properties to update. + * @param [callback] Called when the properties are updated. + */ + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; + /** + * Enables or disables a connected socket from + * receiving messages from its peer, or a listening + * socket from accepting new connections. The default + * value is 'false'. Pausing a connected socket is + * typically used by an application to throttle data + * sent by its peer. When a connected socket is paused, + * no onReceiveevent is raised. When a socket is connected + * and un-paused, onReceive events are raised again when + * messages are received. When a listening socket is paused, + * new connections are accepted until its backlog is full + * then additional connection requests are refused. + * onAccept events are raised only when the socket is un-paused. + * + * @param socketId The socket identifier. + * @param paused Flag indicating whether a connected socket + * blocks its peer from sending more data, or + * whether connection requests on a listening + * socket are dispatched through the onAccept + * event or queued up in the listen queue backlog. + * See setPaused. The default value is 'false'. + * @param [callback] Callback from the setPaused method. + */ + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingRfcomm(socketId: integer, uuid: string, callback: () => void): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param options Optional additional options for the service. + * @param callback Called when listen operation completes. + */ + function listenUsingRfcomm(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingL2cap(socketId: integer, uuid: string, callback: () => void): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param options Optional additional options for the service. + * @param callback Called when listen operation completes. + */ + function listenUsingL2cap(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void; + /** + * Connects the socket to a remote Bluetooth device. + * When the connect operation completes successfully, + * onReceive events are raised when data is received + * from the peer. If a network error occur while the + * runtime is receiving packets, a onReceiveError + * event is raised, at which point no more onReceive + * event will be raised for this socket until the + * setPaused(false) method is called. + * + * @param socketId The socket identifier. + * @param address The address of the Bluetooth device. + * @param uuid The UUID of the service to connect to. + * @param callback Called when the connect attempt is complete. + */ + function connect(socketId: integer, address: string, uuid: string, callback: () => void): void; + /** + * Disconnects the socket. The socket identifier remains valid. + * @param socketId The socket identifier. + * @param [callback] Called when the disconnect attempt is complete. + */ + function disconnect(socketId: integer, callback?: () => void): void; + /** + * Disconnects and destroys the socket. + * Each socket created should be closed after use. + * The socket id is no longer valid as soon at the + * function is called. However, the socket is guaranteed + * to be closed only when the callback is invoked. + * + * @param socketId The socket identifier. + * @param callback Called when the `close` operation completes + */ + function close(socketId: integer, callback: () => void): void; + /** + * Sends data on the given Bluetooth socket. + * @param socketId The socket identifier. + * @param data The data to send. + * @param [callback] Called with the number of bytes sent. + */ + function send(socketId: integer, data: ArrayBuffer, callback?: (bytesSent: number) => void): void; + /** + * Retrieves the state of the given socket. + * @param socketId The socket identifier. + * @param callback Called when the socket state is available. + * Callback returning object containing the socket information. + */ + function getInfo(socketId: integer, callback: (socketInfo: SocketInfo) => void): void; + /** + * Retrieves the list of currently opened sockets owned by the application. + * @param callback Called when the list of sockets is available. + * Returns an array of socket info. + */ + function getSockets(callback: (sockets: SocketInfo[]) => void): void; + /** + * Event raised when a connection has been established + * for a given socket. + */ + const onAccept: OnAcceptEvent; + /** + * Event raised when a network error occurred while the + * runtime was waiting for new connections on the given + * socket. Once this event is raised, the socket is set + * to paused and no more onAccept events are raised for + * this socket. + */ + const onAcceptError: OnAcceptErrorEvent; + /** + * Event raised when data has been received for a given socket. + */ + const onReceive: OnReceiveEvent; + /** + * Event raised when a network error occured while the runtime + * was waiting for data on the socket. Once this event is raised, + * the socket is set to paused and no more onReceive events are + * raised for this socket. + */ + const onReceiveError: OnReceiveErrorEvent; + } + + ///////////// + // Browser // + ///////////// + /** + * @since Availability: Since Chrome 42. + * @requires Permissions: 'browser' + * @description * Use the chrome.browser API to interact with the Chrome browser associated with * the current application and Chrome profile. */ @@ -1398,7 +1827,7 @@ declare namespace chrome { * @param callback Called when the tab was successfully * created, or failed to be created. If failed, runtime.lastError will be set. */ - export function openTab(options: Options, callback: () => void): void; + function openTab(options: Options, callback: () => void): void; /** * Opens a new tab in a browser window associated with the current application @@ -1406,24 +1835,77 @@ declare namespace chrome { * a new one is opened prior to creating the new tab. Since Chrome 42 only. * @param options Configures how the tab should be opened. */ - export function openTab(options: Options): void; + function openTab(options: Options): void; } - //////////////////// - // Commands - //////////////////// + /////////////// + // Clipboard // + /////////////// /** - * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. - * Availability: Since Chrome 25. - * Manifest: 'commands': {...} + * @requires(dev) **Dev** channel only. + * @requires Permissions: "clipboard" + * @description + * *This API is* **experimental**. *It is* **only** *available to Chrome users on the* **dev** *channel.* + * The chrome.clipboard API is provided to allow users to access data of the clipboard. + * This is a temporary solution for chromeos platform apps until open-web alternative is available. + * It will be deprecated once open-web solution is available. + * @see[Docs]{@link https://developer.chrome.com/apps/clipboard} + */ + namespace clipboard { + interface AdditionalItems { + /** Type of the additional data item. */ + type: 'textPlain' | 'textHtml'; + /** + * Content of the additional data item. + * Either the plain text string if *type* is "textPlain" or + * markup string if *type* is "textHtml". + * The data can not exceed 2MB. + */ + data: string; + } + /** + * **Dev channel only.** + * Sets image data to clipboard + * @param imageData The encoded image data. *Since Chrome 69. Warning: this is the current Beta channel.* + * @param type The type of image being passed. *Since Chrome 69. Warning: this is the current Beta channel.* + * @param [additionalItems] Additional data items for describing image data. + * The callback is called with chrome.runtime.lastError set to error code if there is an error. + * Requires clipboard and clipboardWrite permissions. + * *Since Chrome 69. Warning: this is the current Beta channel.* + * @param [callback] + */ + function setImageData(imageData: ArrayBuffer, type: 'png' | 'jpeg', additionalItems?: AdditionalItems, callback?: () => void): void; + + /** + * **Dev channel only.** + * Fired when clipboard data changes. + * Requires clipboard and clipboardRead permissions for adding listener to + * chrome.clipboard.onClipboardDataChanged event. After this event fires, the + * clipboard data is available by calling document.execCommand('paste'). + */ + const onClipboardDataChanged: chrome.events.Event<() => void>; + } + + ////////////// + // Commands // + ////////////// + /** + * @since Availability: Since Chrome 35. + * @requires Manifest: 'commands': {...} + * @description + * Use the commands API to add keyboard shortcuts that + * trigger actions in your app, for example, an + * action to open the browser action or send a command + * to the app. + * @see[Usage]{@link https://developer.chrome.com/apps/commands} */ namespace commands { interface Command { - /** Optional. The name of the Extension Command */ + /** The name of the Extension Command */ name?: string; - /** Optional. The Extension Command description */ + /** The Extension Command description */ description?: string; - /** Optional. The shortcut active for this command, or blank if not active. */ + /** The shortcut active for this command, or blank if not active. */ shortcut?: string; } @@ -1432,239 +1914,338 @@ declare namespace chrome { /** * Returns all the registered extension commands for this extension and their shortcut (if active). * @param callback Called to return the registered commands. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Command commands) {...}; */ - export function getAll(callback: (commands: Command[]) => void): void; + function getAll(callback: (commands: Command[]) => void): void; /** Fired when a registered command is activated using a keyboard shortcut. */ - export var onCommand: CommandEvent; + const onCommand: CommandEvent; } - //////////////////// - // Context Menus - //////////////////// + /////////////////// + // Context Menus // + /////////////////// /** - * Use the chrome.contextMenus API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. - * Availability: Since Chrome 6. - * Permissions: 'contextMenus' + * @since Availability: Since Chrome 24. + * @requires Permissions: 'contextMenus' + * @description + * Use the chrome.contextMenus API to add items to Google Chrome's context menu. + * You can choose what types of objects your context menu additions apply to, + * such as images, hyperlinks, and pages. + * + * Context menu items can appear in any document (or frame within a document), + * even those with file:// or chrome:// URLs. To control which documents your + * items can appear in, specify the documentUrlPatterns field when you call the + * create() or update() method. + * + * You can create as many context menu items as you need, + * but if more than one from your app is visible at once, + * Google Chrome automatically collapses them into a single parent menu. */ namespace contextMenus { + /** + * @since Chrome 38. + * @default 6 + * @description + * The maximum number of top level extension items that + * can be added to an extension action context menu. + * Any items beyond this limit will be ignored. + */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is used to add menu items to the context menu that appears when clicking on the app icon in the launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported in a launcher context menu. **/ - export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio' | 'launcher' | 'browser_action' | 'page_action'; + type ContextType = + 'all' | + 'page' | + 'frame' | + 'selection' | + 'link' | + 'editable' | + 'image' | + 'video' | + 'audio' | + 'launcher' | + 'browser_action' | + 'page_action'; /** * The type of menu item. **/ - export type ItemType = 'normal' | 'checkbox' | 'radio' | 'separator'; + type ItemType = + 'normal' | + 'checkbox' | + 'radio' | + 'separator'; + type MediaType = + 'image' | + 'video' | + 'audio'; interface OnClickData { /** - * Optional. - * @since Since Chrome 35. - * The text for the context selection, if any. - */ - selectionText?: string; - /** - * Optional. - * @since Since Chrome 35. - * A flag indicating the state of a checkbox or radio item after it is clicked. - */ - checked?: boolean; - /** - * @since Since Chrome 35. * The ID of the menu item that was clicked. - */ - menuItemId: any; - /** - * Optional. * @since Since Chrome 35. - * The URL of the frame of the element where the context menu was clicked, if it was in a frame. */ - frameUrl?: string; + menuItemId: integer | string; + /** + * The parent ID, if any, for the item clicked. * @since Since Chrome 35. - * A flag indicating whether the element is editable (text input, textarea, etc.). */ - editable: boolean; + parentMenuItemId?: integer | string; + /** - * Optional. + * One of 'image', 'video', or 'audio' if the context menu was + * activated on one of these types of elements. * @since Since Chrome 35. - * One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements. */ - mediaType?: string; + mediaType?: MediaType; + /** - * Optional. - * @since Since Chrome 35. - * A flag indicating the state of a checkbox or radio item before it was clicked. - */ - wasChecked?: boolean; - /** - * @since Since Chrome 35. - * The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where there is no current page, such as in a launcher context menu. - */ - pageUrl: string; - /** - * Optional. - * @since Since Chrome 35. * If the element is a link, the URL it points to. + * @since Since Chrome 35. */ linkUrl?: string; + /** - * Optional. - * @since Since Chrome 35. - * The parent ID, if any, for the item clicked. - */ - parentMenuItemId?: any; - /** - * Optional. - * @since Since Chrome 35. * Will be present for elements with a 'src' URL. + * @since Since Chrome 35. */ srcUrl?: string; + + /** + * The URL of the page where the menu item was clicked. + * This property is not set if the click occured in a + * context where there is no current page, such as in + * a launcher context menu. + * @since Since Chrome 35. + */ + pageUrl: string; + + /** + * The URL of the frame of the element where the context menu was clicked, + * if it was in a frame. + * @since Since Chrome 35. + */ + frameUrl?: string; + + /** + * The ID of the frame of the element where the context menu was clicked, + * if it was in a frame. + * @since Since Chrome 35. + */ + frameId?: integer; + + /** + * The text for the context selection, if any. + * @since Since Chrome 35. + */ + selectionText?: string; + + /** + * A flag indicating whether the element is editable (text input, textarea, etc.). + * @since Since Chrome 35. + */ + editable: boolean; + + /** + * A flag indicating the state of a checkbox or radio item before it was clicked. + * @since Since Chrome 35. + */ + wasChecked?: boolean; + + /** + * A flag indicating the state of a checkbox or radio item after it is clicked. + * @since Since Chrome 35. + */ + checked?: boolean; } interface CreateProperties { - /** Optional. Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. */ - documentUrlPatterns?: string[]; - /** Optional. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. */ - checked?: boolean; - /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ - title?: string; - /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ - contexts?: string[]; + /** The type of menu item. Defaults to 'normal' if not specified. */ + type?: ItemType; + /** - * Optional. - * Whether this context menu item is enabled or disabled. Defaults to true. - * @since Since Chrome 20. + * The unique ID to assign to this item. + * Mandatory for event pages. + * Cannot be the same as another ID for this extension. */ - enabled?: boolean; - /** Optional. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: string[]; + id?: string; + + /** + * The text to be displayed in the item; + * this is required unless type is 'separator'. + * When the context is 'selection', you can use + * %s within the string to show the selected text. + * For example, if this parameter's value is + * 'Translate '%s' to Pig Latin' and the user + * selects the word 'cool', the context menu + * item for the selection is 'Translate 'cool' + * to Pig Latin'. + **/ + title?: string; + + /** + * The initial state of a checkbox or radio item: + * true for selected and false for unselected. + * Only one radio item can be selected at a time + * in a given group of radio items. + **/ + checked?: boolean; + + /** + * List of contexts this menu item will appear in. + * Defaults to ['page'] if not specified. + **/ + contexts?: ContextType[]; + + /** + * Whether the item is visible in the menu. + * @since Since Chrome 62. + */ + visible?: boolean; + /** - * Optional. * A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for chrome.contextMenus.onClicked. * @param info Information sent when a context menu item is clicked. */ onclick?: (info: OnClickData) => void; - /** Optional. The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: any; - /** Optional. The type of menu item. Defaults to 'normal' if not specified. */ - type?: string; + + /** The ID of a parent menu item; this makes the item a child of a previously added item. */ + parentId?: integer | string; + /** - * Optional. - * @since Since Chrome 21. - * @description The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. - */ - id?: string; + * Lets you restrict the item to apply only to documents whose URL + * matches one of the given patterns. (This applies to frames as well.) + * For details on the format of a pattern, see Match Patterns. + **/ + documentUrlPatterns?: string[]; + /** - * @description Whether the item is visible in the menu. - * @since Since Chrome 62 + * Similar to documentUrlPatterns, + * but lets you filter based on the src attribute + * of img/audio/video tags and the href of anchor tags. + **/ + targetUrlPatterns?: string[]; + + /** + * Whether this context menu item is enabled or disabled. + * @default true */ - visible?: boolean; + enabled?: boolean; } interface UpdateProperties { - documentUrlPatterns?: string[]; - checked?: boolean; + type?: ItemType; title?: string; - contexts?: string[]; + checked?: boolean; + contexts?: ContextType[]; /** - * @since Chrome 20 - **/ - enabled?: boolean; - targetUrlPatterns?: string[]; - onclick?: (info: OnClickData) => void; - /** Optional. Note: You cannot change an item to be a child of one of its own descendants. */ - parentId?: any; - type?: string; - /** - * @description Whether the item is visible or not. - * @since Since Chrome 62 + * Whether the item is visible in the menu. + * @since Chrome 62. */ visible?: boolean; + /** + * Information sent when a context menu item is clicked. + * @since Chrome 44 + */ + onclick?: (info: OnClickData) => void; + /** Note: You cannot change an item to be a child of one of its own descendants. */ + parentId?: integer | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; } interface MenuClickedEvent extends chrome.events.Event<(info: OnClickData) => void> { } /** - * Since Chrome 38. - * The maximum number of top level extension items that can be added to an extension action context menu. Any items beyond this limit will be ignored. + * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). + * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. */ - export var ACTION_MENU_TOP_LEVEL_LIMIT: number; + function create(createProperties: CreateProperties, callback?: () => void): void; + + /** + * Updates a previously created context menu item. + * @param id The ID of the item to update. + * @param updateProperties The properties to update. Accepts the same values as the create function. + * @param callback Called when the context menu has been updated. + */ + function update(id: integer | string, updateProperties: UpdateProperties, callback?: () => void): void; + + /** + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param callback Called when the context menu has been removed. + */ + function remove(menuItemId: integer | string, callback?: () => void): void; /** * Removes all context menu items added by this extension. * @param callback Called when removal is complete. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function removeAll(callback?: () => void): void; - /** - * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). - * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function create(createProperties: CreateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: string, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: number, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: string, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: number, callback?: () => void): void; + function removeAll(callback?: () => void): void; - /** - * Since Chrome 21. - * Fired when a context menu item is clicked. - */ - export var onClicked: MenuClickedEvent; + /** Fired when a context menu item is clicked. */ + const onClicked: MenuClickedEvent; } //////////////////// - // Document Scan + // DesktopCapture // //////////////////// /** - * Use the chrome.documentScan API to discover and retrieve images from attached paper document scanners. - * Availability: Since Chrome 44. - * Permissions: 'documentScan' - * Important: This API works only on Chrome OS. + * Desktop Capture API that can be used to capture content of screen, + * individual windows or tabs. + * @since Availability: Since Chrome 34. + * @requires Permissions: "desktopCapture" + */ + namespace desktopCapture { + const DesktopCaptureSourceType: { + SCREEN: "screen", + WINDOW: "window", + TAB: "tab", + AUDIO: "audio" + } + + /** + * Shows desktop media picker UI with the specified set of sources. + * @param sources Set of sources that should be shown to the user. + * @param callback The callback parameter should be a function that looks like this: + * function(string streamId) {...}; + * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. + */ + function chooseDesktopMedia + (sources: Array, callback: (streamId: string) => void): number; + /** + * Hides desktop media picker dialog shown by chooseDesktopMedia(). + * @param desktopMediaRequestId Id returned by chooseDesktopMedia() + */ + function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; + } + + /////////////////// + // Document Scan // + /////////////////// + /** + * Use the chrome.documentScan API to discover and retrieve + * images from attached paper document scanners. + * + * The Document Scan API is designed to allow apps to view + * the content of paper documents on an attached document scanner. + * + * *Note: This API depends on OS features that may not be available* + * *depending on the underlying operating system. As of this writing only* + * *Chrome OS for certain USB-attached devices is known to successfully work.* + * + * @since Availability: Since Chrome 44. + * @requires Permissions: 'documentScan' + * @requires Important: This API works only on Chrome OS. */ namespace documentScan { interface DocumentScanOptions { - /** Optional. The MIME types that are accepted by the caller. */ + /** The MIME types that are accepted by the caller. */ mimeTypes?: string[]; - /** Optional. The number of scanned images allowed (defaults to 1). */ + /** The number of scanned images allowed (defaults to 1). */ maxImages?: number; } @@ -1679,72 +2260,101 @@ declare namespace chrome { * Performs a document scan. On success, the PNG data will be sent to the callback. * @param options Object containing scan parameters. * @param callback Called with the result and data from the scan. - * The callback parameter should be a function that looks like this: - * function(object result) {...}; */ - export function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; + function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; } - //////////////////// - // Events - //////////////////// + //////////// + // Events // + //////////// /** - * The chrome.events namespace contains common types used by APIs dispatching events to notify you when something interesting happens. - * Availability: Since Chrome 21. + * The chrome.events namespace contains common types used by APIs + * dispatching events to notify you when something interesting happens. + * + * An Event is an object that allows you to be notified when something interesting happens. + * Here's an example of using the chrome.alarms.onAlarm event to be notified whenever an alarm has elapsed: + * @example + * chrome.alarms.onAlarm.addListener(function(alarm) { + * appendToLog('alarms.onAlarm --' + * + ' name: ' + alarm.name + * + ' scheduledTime: ' + alarm.scheduledTime); + * }); + * @description + * As the example shows, you register for notification using addListener(). + * The argument to addListener() is always a function that you define to + * handle the event, but the parameters to the function depend on which + * event you're handling. Checking the documentation for alarms.onAlarm, + * you can see that the function has a single parameter: an alarms.Alarm + * object that has details about the elapsed alarm. + * @since Availability: Since Chrome 25. */ namespace events { - /** Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ + /** Filters URLs for constious criteria. See event filtering. All criteria are case sensitive. */ interface UrlFilter { - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ - schemes?: string[]; /** - * Optional. - * Since Chrome 23. - * Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. + * Matches if the host name of the URL contains a specified string. + * To test whether a host name component has a prefix 'foo', + * use hostContains: '.foo'. This matches 'www.foobar.com' and + * 'foo.com', because an implicit dot is added at the beginning of + * the host name. Similarly, hostContains can be used to match + * against component suffix ('foo.') and to exactly match against + * components ('.foo.'). Suffix- and exact-matching for the last + * components need to be done separately using hostSuffix, because + * no implicit dot is added at the end of the host name. + **/ + hostContains?: string; + /** Matches if the host name of the URL is equal to a specified string. */ + hostEquals?: string; + /** Matches if the host name of the URL starts with a specified string. */ + hostPrefix?: string; + /** Matches if the host name of the URL ends with a specified string. */ + hostSuffix?: string; + /** Matches if the path segment of the URL contains a specified string. */ + pathContains?: string; + /** Matches if the path segment of the URL starts with a specified string. */ + pathEquals?: string; + /** Matches if the path segment of the URL ends with a specified string. */ + pathPrefix?: string; + /** Matches if the path segment of the URL is equal to a specified string. */ + pathSuffix?: string; + /** Matches if the query segment of the URL contains a specified string. */ + queryContains?: string; + /** Matches if the query segment of the URL is equal to a specified string. */ + queryEquals?: string; + /** Matches if the query segment of the URL starts with a specified string. */ + queryPrefix?: string; + /** Matches if the query segment of the URL ends with a specified string. */ + querySuffix?: string; + /** Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlContains?: string; + /** Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlEquals?: string; + /** Matches if the URL (without fragment identifier) matches a specified regular expression. + * Port numbers are stripped from the URL if they match the default port number. + * The regular expressions use the RE2 syntax. + * @see[RE2 syntax docs]{@link https://github.com/google/re2/blob/master/doc/syntax.txt} */ urlMatches?: string; - /** Optional. Matches if the path segment of the URL contains a specified string. */ - pathContains?: string; - /** Optional. Matches if the host name of the URL ends with a specified string. */ - hostSuffix?: string; - /** Optional. Matches if the host name of the URL starts with a specified string. */ - hostPrefix?: string; - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ - hostContains?: string; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlContains?: string; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ - querySuffix?: string; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlPrefix?: string; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ - hostEquals?: string; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlEquals?: string; - /** Optional. Matches if the query segment of the URL contains a specified string. */ - queryContains?: string; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ - pathPrefix?: string; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ - pathEquals?: string; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ - pathSuffix?: string; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ - queryEquals?: string; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ - queryPrefix?: string; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlSuffix?: string; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ - ports?: any[]; /** - * Optional. - * Since Chrome 28. - * Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. + * Matches if the URL without query segment and fragment identifier matches a specified regular expression. + * Port numbers are stripped from the URL if they match the default port number. + * The regular expressions use the RE2 syntax. + * @see[RE2 syntax docs]{@link https://github.com/google/re2/blob/master/doc/syntax.txt} + * @since Since Chrome 28. */ originAndPathMatches?: string; + /** Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlPrefix?: string; + /** Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlSuffix?: string; + /** Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ + schemes?: string[]; + /** + * Matches if the port of the URL is contained in any of the specified port lists. + * For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. + */ + ports?: Array; } - /** An object which allows the addition and removal of listeners for a Chrome event. */ interface Event { /** @@ -1772,9 +2382,11 @@ declare namespace chrome { */ getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void; /** - * @param callback Listener whose registration status shall be tested. + * Has this event this provided listener? + * @param listener Listener whose registration status shall be tested. + * @return If it has the provided listener */ - hasListener(callback: T): boolean; + hasListener(callback: T | Function): boolean; /** * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. @@ -1786,151 +2398,183 @@ declare namespace chrome { /** * Unregisters currently registered rules. * @param callback Called when rules were unregistered. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ removeRules(callback?: () => void): void; /** * Registers rules to handle events. * @param rules Rules to be registered. These do not replace previously registered rules. * @param callback Called with registered rules. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Rule rules) {...}; * Parameter rules: Rules that were registered, the optional parameters are filled with values. */ addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void; /** * Deregisters an event listener callback from an event. * @param callback Listener that shall be unregistered. - * The callback parameter should be a function that looks like this: - * function() {...}; */ removeListener(callback: T): void; + /** + * Has this event listeners? + */ hasListeners(): boolean; } /** Description of a declarative rule for handling events. */ interface Rule { - /** Optional. Optional priority of this rule. Defaults to 100. */ - priority?: number; - /** List of conditions that can trigger the actions. */ - conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ + /** Identifier that allows referencing this rule. */ id?: string; - /** List of actions that are triggered if one of the condtions is fulfilled. */ - actions: any[]; + /** - * Optional. - * Since Chrome 28. * Tags can be used to annotate rules and perform operations on sets of rules. + * @since Since Chrome 28. */ tags?: string[]; + + /** List of conditions that can trigger the actions. */ + conditions: any[]; + + /** List of actions that are triggered if one of the condtions is fulfilled. */ + actions: any[]; + + /** + * Optional priority of this rule. + * @default 100 + */ + priority?: integer; } } - //////////////////// - // Extension Types - //////////////////// + ///////////////////// + // Extension Types // + ///////////////////// /** * Primary for extensions, but also used in apps. * https://developer.chrome.com/extensions/extensionTypes#type-ImageDetails + * @since Chrome 39. **/ namespace extensionTypes { /** * The format of an image. **/ - export type ImageFormat = 'jpeg' | 'png'; + type ImageFormat = + 'jpeg' | + 'png'; /** * Details about the format and quality of an image. */ interface ImageDetails { - /** - * @description The format of the resulting image. Default is 'jpeg'. - * @type {ImageFormat} - * @memberof ImageDetails - */ + /** The format of the resulting image. Default is 'jpeg'. */ format?: ImageFormat; + /** - * @description When format is 'jpeg', controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. - * @type {number} - * @memberof ImageDetails + * When format is 'jpeg', controls the quality of the resulting image. + * This value is ignored for PNG images. As quality is decreased, + * the resulting image will have more visual artifacts, + * and the number of bytes needed to store it will decrease. */ quality?: number; } /** * The soonest that the JavaScript or CSS will be injected into the tab. **/ - export type RunAt = 'document_start' | 'document_end' | 'document_idle'; + type RunAt = + 'document_start' | + 'document_end' | + 'document_idle'; /** * The origin of injected CSS. **/ - export type CSSOrigin = 'author' | 'user'; + type CSSOrigin = + 'author' | + 'user'; /** - * @description Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @interface InjectDetails + * Internal interfaces, not to be used directly + * @private + * @internal */ - interface InjectDetails { + namespace _internal_ { + /** + * Partial, use these interfaces instead: + * @see InjectCodeDetails + * @see InjectFileDetails + */ + interface InjectDetailsBase { + /** + * If allFrames is true, implies that the JavaScript or CSS should be + * injected into all frames of current page. By default, it's false + * and is only injected into the top frame. If true and frameId is set, + * then the code is inserted in the selected frame and all of its child frames. + */ + allFrames?: boolean; + /** + * The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). + * @see[frame ref]{@link https://developer.chrome.com/apps/webNavigation#frame_ids} + * @since Since Chrome 50. + */ + frameId?: number; + /** + * If matchAboutBlank is true, then the code is also injected in about:blank + * and about:srcdoc frames if your extension has access to its parent document. + * Code cannot be inserted in top-level about:-frames. By default it is false. + */ + matchAboutBlank?: boolean; + /** + * The soonest that the JavaScript or CSS will be injected into the tab. + * @default 'document_idle' + */ + runAt: RunAt; + /** + * The origin of the CSS to inject. + * This may only be specified for CSS, not JavaScript. + * @default 'author' + * @since Since Chrome 66. + */ + cssOrigin: CSSOrigin; + } + } + + interface InjectFileDetails extends _internal_.InjectDetailsBase { + /** JavaScript or CSS file to inject. */ + file: string; + } + + interface InjectCodeDetails extends _internal_.InjectDetailsBase { /** * JavaScript or CSS code to inject. - * Warning: - * Be careful using the code parameter. Incorrect use of it may open your extension to cross site scripting attacks. - * @type {string} - * @memberof InjectDetails + * **Warning** + * Be careful using the code parameter. + * Incorrect use of it may open your app + * to cross site scripting attacks. + * @see[More information]{https://en.wikipedia.org/wiki/Cross-site_scripting} */ - code?: string; - /** - * @description JavaScript or CSS file to inject. - * @type {string} - * @memberof InjectDetails - */ - file?: string; - /** - * @description If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame. If true and frameId is set, then the code is inserted in the selected frame and all of its child frames. - * @type {boolean} - * @memberof InjectDetails - */ - allFrames?: boolean; - /** - * @description The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). - * @since Since Chrome 50. - * @type {number} - * @memberof InjectDetails - */ - frameId?: number; - /** - * @description If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false. - * @type {boolean} - * @memberof InjectDetails - */ - matchAboutBlank?: boolean; - /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. - * @type {RunAt} - * @memberof InjectDetails - */ - runAt: RunAt; - /** - * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to 'author'. - * @since Since Chrome 66. - * @type {CSSOrigin} - * @memberof InjectDetails - */ - cssOrigin: CSSOrigin; + code: string; } } - //////////////////// - // FileSystem - //////////////////// + //////////////// + // FileSystem // + //////////////// /** * Use the chrome.fileSystem API to create, read, navigate, and write to the user's local file system. * With this API, Chrome Apps can read and write to a user-selected location. * For example, a text editor app can use the API to read and write local documents. * All failures are notified via chrome.runtime.lastError. + * @since Availability: Since Chrome 24. + * @requires Permissions: + * 'fileSystem' + * {'fileSystem': ['write']} + * {'fileSystem': ['write', 'retainEntries', 'directory']} */ namespace fileSystem { - + type ChildChangeType = + 'created' | + 'removed' | + 'changed'; + type ChooseEntryOptionsTypes = + 'openFile' | + 'openWritableFile' | + 'saveFile' | + 'openDirectory'; interface AcceptOptions { /** * This is the optional text description for this option. @@ -1943,7 +2587,7 @@ declare namespace chrome { */ mimeTypes?: string[]; /** - * Extensions to accept, e.g. 'jpg' | 'gif' | 'crx'. + * Extensions to accept, e.g. 'jpg', 'gif', 'crx'. */ extensions?: string[]; } @@ -1952,16 +2596,26 @@ declare namespace chrome { /** * Type of the prompt to show. The default is 'openFile'. * openFile - * - Prompts the user to open an existing file and returns a FileEntry on success. From Chrome 31 onwards, the FileEntry will be writable if the application has the 'write' permission under 'fileSystem'; otherwise, the FileEntry will be read-only. + * - Prompts the user to open an existing file and returns a FileEntry on success. + * From Chrome 31 onwards, the FileEntry will be writable if the application has + * the 'write' permission under 'fileSystem'; otherwise, the FileEntry will be read-only. * openWritableFile - * - Prompts the user to open an existing file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * - Prompts the user to open an existing file and returns a writable FileEntry on success. + * Calls using this type will fail with a runtime error if the application doesn't have the + * 'write' permission under 'fileSystem'. * saveFile - * - Prompts the user to open an existing file or a new file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * - Prompts the user to open an existing file or a new file and returns a writable FileEntry + * on success. Calls using this type will fail with a runtime error if the application doesn't + * have the 'write' permission under 'fileSystem'. * openDirectory - * - Prompts the user to open a directory and returns a DirectoryEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'directory' permission under 'fileSystem'. If the application has the 'write' permission under 'fileSystem', the returned DirectoryEntry will be writable; otherwise it will be read-only. New in Chrome 31. + * - Prompts the user to open a directory and returns a DirectoryEntry on success. Calls using + * this type will fail with a runtime error if the application doesn't have the 'directory' + * permission under 'fileSystem'. If the application has the 'write' permission under + * 'fileSystem', the returned DirectoryEntry will be writable; otherwise it will be read-only. + * New in Chrome 31. */ - type?: 'openFile' | 'openWritableFile' | 'saveFile' | 'openDirectory'; - /** The suggested file name that will be presented to the user as the default name to read or write. This is optional. */ + type?: ChooseEntryOptionsTypes; + /** The suggested file name that will be presented to the user as the default name to read or write. */ suggestedName?: string; /** The optional list of accept options for this file opener. Each option will be presented as a unique group to the end-user. */ accepts?: AcceptOptions[]; @@ -1972,17 +2626,23 @@ declare namespace chrome { acceptsAllTypes?: boolean; /** * Whether to accept multiple files. This is only supported for openFile and openWritableFile. - * The callback to chooseEntry will be called with a list of entries if this is set to true. Otherwise it will be called with a single Entry. + * The callback to chooseEntry will be called with a list of entries if this is set to true. + * Otherwise it will be called with a single Entry. + * @since Chrome 30. */ acceptsMultiple?: boolean; } - type ChildChangeType = 'created' | 'removed' | 'changed'; - + /** + * @since Chrome 44. + */ interface Volume { /** The ID of the requested volume. */ volumeId: string; - /** Whether the requested file system should be writable. The default is read-only. */ + /** + * Whether the requested file system should be writable. The default is read-only. + * @default false + **/ writable?: boolean; } @@ -1990,33 +2650,37 @@ declare namespace chrome { * Get the display path of an Entry object. * The display path is based on the full path of the file or directory on the local file system, but may be made more readable for display purposes. */ - export function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void; + function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void; /** * Get a writable Entry from another Entry. This call will fail with a runtime error if the application does not have the 'write' permission under 'fileSystem'. * If entry is a DirectoryEntry, this call will fail if the application does not have the 'directory' permission under 'fileSystem'. */ - export function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void; + function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void; /** Gets whether this Entry is writable or not. */ - export function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void; + function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(callback: (entry: Entry) => void): void; + function chooseEntry(callback: (entry: Entry) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void; + function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void; + function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; + function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; /** Returns the file entry with the given id if it can be restored. This call will fail with a runtime error otherwise. */ - export function restoreEntry(id: string, callback: (entry: Entry) => void): void; - /** Returns whether the app has permission to restore the entry with the given id. */ - export function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; + function restoreEntry(id: string, callback: (entry: Entry) => void): void; + /** + * Returns whether the app has permission to restore the entry with the given id. + * @since Chrome 29. + **/ + function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; /** * Returns an id that can be passed to restoreEntry to regain access to a given file entry. * Only the 500 most recently used entries are retained, where calls to retainEntry and restoreEntry count as use. * If the app has the 'retainEntries' permission under 'fileSystem', entries are retained indefinitely. * Otherwise, entries are retained only while the app is running and across restarts. + * @since Chrome 29. * */ - export function retainEntry(entry: Entry): string; + function retainEntry(entry: Entry): string; /** * Requests access to a file system for a volume represented by options.volumeId. * If options.writable is set to true, then the file system will be writable. @@ -2025,16 +2689,22 @@ declare namespace chrome { * Available to kiosk apps running in kiosk session only. * For manual-launch kiosk mode, a confirmation dialog will be shown on top of the active app window. * In case of an error, fileSystem will be undefined, and chrome.runtime.lastError will be set. + * @since Chrome 44. */ - export function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; + function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; /** * Returns a list of volumes available for requestFileSystem(). * The 'fileSystem': {'requestFileSystem'} manifest permission is required. * Available to kiosk apps running in the kiosk session only. * In case of an error, volumes will be undefined, and chrome.runtime.lastError will be set. + * @since Chrome 44. */ - export function getVolumeList(callback: (volumes: Volume[]) => void): void; - export var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; + function getVolumeList(callback: (volumes: Volume[]) => void): void; + /** + * Called when a list of available volumes is changed. + * @since Chrome 44. + */ + const onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; } @@ -2042,76 +2712,161 @@ declare namespace chrome { // File System Provider //////////////////// /** - * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. - * Availability: Since Chrome 40. - * Permissions: 'fileSystemProvider' - * Important: This API works only on Chrome OS. + * Use the chrome.fileSystemProvider API to create file systems, + * that can be accessible from the file manager on Chrome OS. + * @since Availability: Since Chrome 40. + * @requires Permissions: 'fileSystemProvider' + * @requires Important: This API works only on Chrome OS. + * @requires Manifest: + * Requires an section in addition to the permission. + * The file_system_provider section must be declared as follows: + * **configurable (boolean)** - optional + * Whether configuring via onConfigureRequested is supported. By default: false. + * **multiple_mounts (boolean)** - optional + * Whether multiple (more than one) mounted file systems are supported. By default: false. + * **watchable (boolean)** - optional + * Whether setting watchers and notifying about changes is supported. By default: false. + * **source (type of 'file', 'device', or 'network') - required** + * Source of data for mounted file systems. + * @description + * Files app uses above information in order to render related UI elements approprietly. + * For example, if configurable is set to true, then a menu item for configuring volumes + * will be rendered. Similarly, if multiple_mounts is set to true, then Files app will + * allow to add more than one mount points from the UI. If watchable is false, then a + * refresh button will be rendered. Note, that if possible you should add support for + * watchers, so changes on the file system can be reflected immediately and automatically. + * @see[More information]{@link https://developer.chrome.com/apps/fileSystemProvider} */ namespace fileSystemProvider { - interface OpenedFileInfo { - /** A request ID to be be used by consecutive read/write and close requests. */ - openRequestId: number; - /** The path of the opened file. */ - filePath: string; - /** Whether the file was opened for reading or writing. */ - mode: string; - } - - interface FileWatchersInfo { - /** The path of the entry being observed. */ - entryPath: string; - /** Whether watching should include all child entries recursively. It can be true for directories only. */ - recursive: boolean; - /** Optional. Tag used by the last notification for the watcher. */ - lastTag?: string; - } + /** + * Error codes used by providing extensions in response to requests + * as well as in case of errors when calling methods of the API. + * For success, 'OK' must be used. + * */ + type ProviderError = + 'OK' | + 'FAILED' | + 'IN_USE' | + 'EXISTS' | + 'NOT_FOUND' | + 'ACCESS_DENIED' | + 'TOO_MANY_OPENED' | + 'NO_MEMORY' | + 'NO_SPACE' | + 'NOT_A_DIRECTORY' | + 'INVALID_OPERATION' | + 'SECURITY' | + 'ABORT' | + 'NOT_A_FILE' | + 'NOT_EMPTY' | + 'INVALID_URL' | + 'IO'; + /** Mode of opening a file. Used by onOpenFileRequested. */ + type OpenFileMode = + 'READ' | + 'WRITE'; + /** Type of a change detected on the observed directory. */ + type ChangeType = + 'CHANGED' | + 'DELETED'; + /** + * List of common actions. 'SHARE' is for sharing files with others. + * 'SAVE_FOR_OFFLINE' for pinning (saving for offline access). + * 'OFFLINE_NOT_NECESSARY' for notifying that the file doesn't + * need to be stored for offline access anymore. + * Used by onGetActionsRequested and onExecuteActionRequested. + */ + type CommonActionId = + 'SAVE_FOR_OFFLINE' | + 'OFFLINE_NOT_NECESSARY' | + 'SHARE'; interface EntryMetadata { - /** True if it is a directory. */ - isDirectory: boolean; - /** Name of this entry (not full path name). Must not contain '/'. For root it must be empty. */ - name: string; - /** File size in bytes. */ - size: number; + /** True if it is a directory. Must be provided if requested in options */ + isDirectory?: boolean; + /** + * Name of this entry (not full path name). + * Must not contain '/'. + * For root it must be empty. + * Must be provided if requested in options. + **/ + name?: string; + /** File size in bytes. Must be provided if requested in options. */ + size?: double; /** The last modified time of this entry. */ - modificationTime: any; - /** Optional. Mime type for the entry. */ + modificationTime?: Date; + /** Mime type for the entry. */ mimeType?: string; - /** Optional. Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. Optional, but can be provided only when explicitly requested by the onGetMetadataRequested event. */ + /** + * Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. + * Optional, but can be provided only when explicitly requested + * by the onGetMetadataRequested event. + */ thumbnail?: string; } interface FileSystemInfo { /** The identifier of the file system. */ fileSystemId: string; + /** A human-readable name for the file system. */ displayName: string; - /** Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ + + /** + * Whether the file system supports operations which may + * change contents of the file system (such as creating, deleting or writing to files). + */ writable: boolean; + /** * The maximum number of files that can be opened at once. If 0, then not limited. * @since Since Chrome 42. */ - openedFilesLimit: number; + openedFilesLimit: integer; + /** * List of currently opened files. * @since Since Chrome 42. */ openedFiles: OpenedFileInfo[]; + /** - * Optional. - * Whether the file system supports the tag field for observing directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Whether the file system supports the tag field for observing directories. + * @since Since Chrome 45. */ supportsNotifyTag?: boolean; + /** * List of watchers. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * @since Since Chrome 45. */ watchers: FileWatchersInfo[]; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ + interface OpenedFileInfo { + /** A request ID to be be used by consecutive read/write and close requests. */ + openRequestId: integer; + /** The path of the opened file. */ + filePath: string; + /** Whether the file was opened for reading or writing. */ + mode: OpenFileMode; + } + + interface FileWatchersInfo { + /** The path of the entry being observed. */ + entryPath: string; + + /** + * Whether watching should include all child entries recursively. + * It can be true for directories only. + */ + recursive: boolean; + + /** Tag used by the last notification for the watcher. */ + lastTag?: string; + } + + /** @since Since Chrome 45. */ interface GetActionsRequestedOptions { /** The identifier of the file system related to this operation. */ fileSystemId: string; @@ -2121,15 +2876,14 @@ declare namespace chrome { entryPath: string; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ interface Action { /** The identifier of the action. Any string or CommonActionId for common actions. */ - id: string; - /** Optional. The title of the action. It may be ignored for common actions. */ + id: CommonActionId | string; + /** The title of the action. It may be ignored for common actions. */ title?: string; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ + /** @since Since Chrome 45. */ interface ExecuteActionRequestedOptions { /** The identifier of the file system related to this operation. */ fileSystemId: string; @@ -2146,20 +2900,27 @@ declare namespace chrome { fileSystemId: string; /** A human-readable name for the file system. */ displayName: string; - /** Optional. Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ + /** + * Whether the file system supports operations which may change contents + * of the file system (such as creating, deleting or writing to files). + */ writable?: boolean; /** - * Optional. - * The maximum number of files that can be opened at once. If not specified, or 0, then not limited. + * The maximum number of files that can be opened at once. If not specified, or 0, then not limited. * @since Since Chrome 41. */ - openedFilesLimit?: number; + openedFilesLimit?: integer; /** - * Optional. - * Whether the file system supports the tag field for observed directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Whether the file system supports the tag field for observed directories. + * @since Since Chrome 45. */ supportsNotifyTag?: boolean; + /** + * Whether the framework should resume the file system at the next sign-in session. + * @default true + * @since Since Chrome 64. + */ + persistent?: boolean; } interface UnmountOptions { @@ -2171,7 +2932,7 @@ declare namespace chrome { /** The path of the changed entry. */ entryPath: string; /** The type of the change which happened to the entry. */ - changeType: string; + changeType: ChangeType; } interface NotificationOptions { @@ -2181,241 +2942,543 @@ declare namespace chrome { observedPath: string; /** Mode of the observed entry. */ recursive: boolean; - /** The type of the change which happened to the observed entry. If it is DELETED, then the observed entry will be automatically removed from the list of observed entries. */ - changeType: string; - /** Optional. List of changes to entries within the observed directory (including the entry itself) */ + /** + * The type of the change which happened to the observed entry. + * If it is DELETED, then the observed entry will be automatically + * removed from the list of observed entries. + */ + changeType: ChangeType; + /** List of changes to entries within the observed directory (including the entry itself) */ changes?: NotificationChange[]; - /** Optional. Tag for the notification. Required if the file system was mounted with the supportsNotifyTag option. Note, that this flag is necessary to provide notifications about changes which changed even when the system was shutdown. */ + /** + * Tag for the notification. + * Required if the file system was mounted with the supportsNotifyTag option. + * Note, that this flag is necessary to provide notifications about changes + * which changed even when the system was shutdown. + */ tag?: string; } + /** + * Internal interfaces, not for use + * @private + * @internal + */ + namespace _internal_ { + /** + * @private + * @internal + */ + interface RequestedEventOptions { + /** The identifier of the file system related to this operation. */ + fileSystemId: string; + /** The unique identifier of this request. */ + requestId: integer; + } - interface RequestedEventOptions { - /** The identifier of the file system related to this operation. */ - fileSystemId: string; - /** The unique identifier of this request. */ - requestId: number; + /** + * @private + * @internal + */ + interface EntryPathRequestedEventOptions extends RequestedEventOptions { + /** The path of the entry to which this operation is related to. */ + entryPath: string; + } + + /** + * @private + * @internal + */ + interface FilePathRequestedEventOptions extends RequestedEventOptions { + /** The path of the entry for the operation */ + filePath: string; + } } - - interface EntryPathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry to which this operation is related to. */ - entryPath: string; + interface UnmountRequestedEventOptions extends _internal_.RequestedEventOptions { } - - interface MetadataRequestedEventOptions extends EntryPathRequestedEventOptions { - /** Set to true if the thumbnail is requested. */ + interface MetadataRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { + /** + * Set to true if is_directory value is requested + * @since Chrome 49. + */ + isDirectory: boolean; + /** + * Set to true if is_directory value is requested. + * @since Chrome 49. + */ + name: boolean; + /** + * Set to true if size value is requested. + * @since Chrome 49. + */ + size: boolean; + /** + * Set to true if modificationTime value is requested + * @since Chrome 49. + */ + modificationTime: boolean; + /** + * Set to true if mimeType value is requested. + * @since Chrome 49. + */ + mimeType: boolean; + /** + * Set to true if the thumbnail is requested. + */ thumbnail: boolean; } - - interface DirectoryPathRequestedEventOptions extends RequestedEventOptions { + interface GetActionsRequestedEventOptions extends _internal_.RequestedEventOptions { + /** The path of the entry to which this operation is related to. */ + entryPaths: string[]; + } + interface ReadDirectoryRequestedEventOptions extends _internal_.RequestedEventOptions { /** The path of the directory which is to be operated on. */ directoryPath: string; + /** + * Set to true if is_directory value is requested + * @since Chrome 49. + */ + isDirectory: boolean; + /** + * Set to true if is_directory value is requested. + * @since Chrome 49. + */ + name: boolean; + /** + * Set to true if size value is requested. + * @since Chrome 49. + */ + size: boolean; + /** + * Set to true if modificationTime value is requested + * @since Chrome 49. + */ + modificationTime: boolean; + /** + * Set to true if mimeType value is requested. + * @since Chrome 49. + */ + mimeType: boolean; + /** + * Set to true if the thumbnail is requested. + */ + thumbnail: boolean; } - - interface FilePathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry for the operation */ - filePath: string; - } - - interface OpenFileRequestedEventOptions extends FilePathRequestedEventOptions { + interface OpenFileRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { /** Whether the file will be used for reading or writing. */ - mode: string; + mode: OpenFileMode; } - - interface OpenedFileRequestedEventOptions extends RequestedEventOptions { + interface CloseFileRequestedEventOptions extends _internal_.RequestedEventOptions { /** A request ID used to open the file. */ - openRequestId: number; + openRequestId: integer; } - - interface OpenedFileOffsetRequestedEventOptions extends OpenedFileRequestedEventOptions { + interface ReadFileRequestedEventOptions extends _internal_.RequestedEventOptions { + /** A request ID used to open the file. */ + openRequestId: integer; /** Position in the file (in bytes) to start reading from. */ - offset: number; + offset: double; /** Number of bytes to be returned. */ - length: number; + length: double; } - - interface DirectoryPathRecursiveRequestedEventOptions extends DirectoryPathRequestedEventOptions { + interface CreateDirectoryRequestedEventOptions extends _internal_.RequestedEventOptions { + /** The path of the directory which is to be operated on. */ + directoryPath: string; /** Whether the operation is recursive (for directories only). */ recursive: boolean; } - - interface EntryPathRecursiveRequestedEventOptions extends EntryPathRequestedEventOptions { + interface DeleteEntryRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { /** Whether the operation is recursive (for directories only). */ recursive: boolean; } - - interface SourceTargetPathRequestedEventOptions extends RequestedEventOptions { + interface CreateFileRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { + } + interface CopyEntryRequestedEventOptions extends _internal_.RequestedEventOptions { /** The source path for the operation. */ sourcePath: string; /** The destination path for the operation. */ targetPath: string; } - - interface FilePathLengthRequestedEventOptions extends FilePathRequestedEventOptions { - /** Number of bytes to be retained after the operation completes. */ - length: number; + interface MoveEntryRequestedEventOptions extends CopyEntryRequestedEventOptions { } - - interface OpenedFileIoRequestedEventOptions extends OpenedFileRequestedEventOptions { + interface TruncateRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { + /** Number of bytes to be retained after the operation completes. */ + length: double; + } + interface WriteFileRequestedEventOptions extends _internal_.RequestedEventOptions { + /** A request ID used to open the file. */ + openRequestId: integer; /** Position in the file (in bytes) to start operating from. */ offset: number; /** Buffer of bytes to be operated on the file. */ data: ArrayBuffer; } - - interface OperationRequestedEventOptions extends RequestedEventOptions { + interface AbortRequestedEventOptions extends _internal_.RequestedEventOptions { /** An ID of the request to which this operation is related. */ - operationRequestId: number; + operationRequestId: integer; + } + interface ConfigureRequestedEventOptions extends _internal_.RequestedEventOptions { + } + interface WatcherRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { + /** + * Mode of the watcher. + * Whether observing should include all child entries recursively. + * It can be true for directories only. + */ + recursive: boolean; + } + interface ExecuteActionRequestedEventOptions extends GetActionsRequestedEventOptions { + /** The identifier of the action to be executed. */ + actionId: string; } - interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> { } - - interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } - - interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } - - interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> { } + ///\/\/|\/\/\\\ + /// METHODS \\\ + ///\/\/|\/\/\\\ /** - * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. + * Mounts a file system with the given fileSystemId and displayName. + * displayName will be shown in the left panel of the Files app. + * displayName can contain any characters including '/', but cannot be an empty string. + * displayName must be descriptive but doesn't have to be unique. + * The fileSystemId must not be an empty string. + * * Depending on the type of the file system being mounted, the source option must be set appropriately. + * * In case of an error, runtime.lastError will be set with a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function mount(options: MountOptions, callback?: () => void): void; + function mount(options: MountOptions, callback?: () => void): void; + /** - * Unmounts a file system with the given fileSystemId. It must be called after onUnmountRequested is invoked. Also, the providing extension can decide to perform unmounting if not requested (eg. in case of lost connection, or a file error). + * Unmounts a file system with the given fileSystemId. + * It must be called after onUnmountRequested is invoked. + * Also, the providing extension can decide to perform unmounting if not requested + * (eg. in case of lost connection, or a file error). + * * In case of an error, runtime.lastError will be set with a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function unmount(options: UnmountOptions, callback?: () => void): void; + function unmount(options: UnmountOptions, callback?: () => void): void; + /** * Returns all file systems mounted by the extension. * @param callback Callback to receive the result of getAll function. - * The callback parameter should be a function that looks like this: - * function(array of FileSystemInfo fileSystems) {...}; */ - export function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; + function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; + /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. * @param callback Callback to receive the result of get function. - * The callback parameter should be a function that looks like this: - * function(FileSystemInfo fileSystem) {...}; */ - export function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; + function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; + /** - * Notifies about changes in the watched directory at observedPath in recursive mode. If the file system is mounted with supportsNofityTag, then tag must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with getAll. + * Notifies about changes in the watched directory at observedPath in recursive mode. + * If the file system is mounted with supportsNofityTag, then tag must be provided, + * and all changes since the last notification always reported, even if the system was shutdown. + * The last tag can be obtained with getAll. + * * To use, the file_system_provider.notify manifest option must be set to true. - * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to '123', then it should call notify for all changes which happened since the change tagged as '123'. It cannot be an empty string. - * Not all providers are able to provide a tag, but if the file system has a changelog, then the tag can be eg. a change number, or a revision number. - * Note that if a parent directory is removed, then all descendant entries are also removed, and if they are watched, then the API must be notified about the fact. Also, if a directory is renamed, then all descendant entries are in fact removed, as there is no entry under their original paths anymore. + * + * Value of tag can be any string which is unique per call, + * so it's possible to identify the last registered notification. + * Eg. if the providing extension starts after a reboot, + * and the last registered notification's tag is equal to '123', + * then it should call notify for all changes which happened since + * the change tagged as '123'. It cannot be an empty string. + * + * Not all providers are able to provide a tag, but if the file system has a changelog, + * then the tag can be eg. a change number, or a revision number. + * + * Note that if a parent directory is removed, then all descendant entries are also removed, + * and if they are watched, then the API must be notified about the fact. + * Also, if a directory is renamed, then all descendant entries are in fact removed, + * as there is no entry under their original paths anymore. + * * In case of an error, runtime.lastError will be set will a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; + * @since Since Chrome 45. */ - export function notify(options: NotificationOptions, callback: () => void): void; + function notify(options: NotificationOptions, callback: () => void): void; + + ///\/\/\/\/\\\ + /// EVENTS \\\ + ///\/\/\/\/\\\ + + /** + * Raised when unmounting for the file system with the fileSystemId identifier is requested. + * In the response, the unmount API method must be called together with successCallback. + * If unmounting is not possible (eg. due to a pending operation), then errorCallback must be called. + */ + const onUnmountRequested: chrome.events.Event<( + options: UnmountRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when metadata of a file or a directory at entryPath is requested. + * The metadata must be returned with the successCallback call. + * In case of an error, errorCallback must be called. + */ + const onGetMetadataRequested: chrome.events.Event<( + options: MetadataRequestedEventOptions, + successCallback: (metadata: EntryMetadata) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when a list of actions for a set of files or directories at entryPaths is requested. + * All of the returned actions must be applicable to each entry. + * If there are no such actions, an empty array should be returned. + * The actions must be returned with the successCallback call. + * In case of an error, errorCallback must be called. + * @since Since Chrome 48. + **/ + const onGetActionsRequested: chrome.events.Event<( + options: GetActionsRequestedEventOptions, + successCallback: (actions: Action[]) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when contents of a directory at directoryPath are requested. + * The results must be returned in chunks by calling the successCallback several times. + * In case of an error, errorCallback must be called. + */ + const onReadDirectoryRequested: chrome.events.Event<( + options: ReadDirectoryRequestedEventOptions, + successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when opening a file at filePath is requested. + * If the file does not exist, then the operation must fail. + * Maximum number of files opened at once can be specified with MountOptions. + */ + const onOpenFileRequested: chrome.events.Event<( + options: OpenFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when opening a file previously opened + * with openRequestId is requested to be closed. + */ + const onCloseFileRequested: chrome.events.Event<( + options: CloseFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void> + + /** + * Raised when reading contents of a file opened previously with openRequestId is requested. + * The results must be returned in chunks by calling successCallback several times. + * In case of an error, errorCallback must be called. + */ + const onReadFileRequested: chrome.events.Event<( + options: ReadFileRequestedEventOptions, + successCallback: (data: ArrayBuffer, hasMore: boolean) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when creating a directory is requested. + * The operation must fail with the EXISTS error if the target directory already exists. + * If recursive is true, then all of the missing directories on the directory path must be created. + */ + const onCreateDirectoryRequested: chrome.events.Event<( + options: CreateDirectoryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when deleting an entry is requested. + * If recursive is true, and the entry is a directory, + * then all of the entries inside must be recursively deleted as well. + */ + const onDeleteEntryRequested: chrome.events.Event<( + options: DeleteEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when creating a file is requested. + * If the file already exists, then errorCallback must be called with the 'EXISTS' error code. + */ + const onCreateFileRequested: chrome.events.Event<( + options: CreateFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when copying an entry (recursively if a directory) is requested. + * If an error occurs, then errorCallback must be called. + */ + const onCopyEntryRequested: chrome.events.Event<( + options: CopyEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when moving an entry (recursively if a directory) is requested. + * If an error occurs, then errorCallback must be called. + */ + const onMoveEntryRequested: chrome.events.Event<( + options: MoveEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when truncating a file to a desired length is requested. + * If an error occurs, then errorCallback must be called. + */ + const onTruncateRequested: chrome.events.Event<( + options: TruncateRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; - /** Raised when unmounting for the file system with the fileSystemId identifier is requested. In the response, the unmount API method must be called together with successCallback. If unmounting is not possible (eg. due to a pending operation), then errorCallback must be called. */ - export var onUnmountRequested: RequestedEvent; - /** Raised when metadata of a file or a directory at entryPath is requested. The metadata must be returned with the successCallback call. In case of an error, errorCallback must be called. */ - export var onGetMetadataRequested: MetadataRequestedEvent; - /** Raised when contents of a directory at directoryPath are requested. The results must be returned in chunks by calling the successCallback several times. In case of an error, errorCallback must be called. */ - export var onReadDirectoryRequested: DirectoryPathRequestedEvent; - /** Raised when opening a file at filePath is requested. If the file does not exist, then the operation must fail. Maximum number of files opened at once can be specified with MountOptions. */ - export var onOpenFileRequested: OpenFileRequestedEvent; - /** Raised when opening a file previously opened with openRequestId is requested to be closed. */ - export var onCloseFileRequested: OpenedFileRequestedEvent; - /** Raised when reading contents of a file opened previously with openRequestId is requested. The results must be returned in chunks by calling successCallback several times. In case of an error, errorCallback must be called. */ - export var onReadFileRequested: OpenedFileOffsetRequestedEvent; - /** Raised when creating a directory is requested. The operation must fail with the EXISTS error if the target directory already exists. If recursive is true, then all of the missing directories on the directory path must be created. */ - export var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; - /** Raised when deleting an entry is requested. If recursive is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ - export var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; - /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the 'EXISTS' error code. */ - export var onCreateFileRequested: FilePathRequestedEvent; - /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - export var onCopyEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when moving an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - export var onMoveEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when truncating a file to a desired length is requested. If an error occurs, then errorCallback must be called. */ - export var onTruncateRequested: FilePathLengthRequestedEvent; /** Raised when writing contents to a file opened previously with openRequestId is requested. */ - export var onWriteFileRequested: OpenedFileIoRequestedEvent; - /** Raised when aborting an operation with operationRequestId is requested. The operation executed with operationRequestId must be immediately stopped and successCallback of this abort request executed. If aborting fails, then errorCallback must be called. Note, that callbacks of the aborted operation must not be called, as they will be ignored. Despite calling errorCallback, the request may be forcibly aborted. */ - export var onAbortRequested: OperationRequestedEvent; + const onWriteFileRequested: chrome.events.Event<( + options: WriteFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when showing a configuration dialog for fileSystemId is requested. If it's handled, the file_system_provider.configurable manfiest option must be set to true. + * Raised when aborting an operation with operationRequestId is requested. + * The operation executed with operationRequestId must be immediately stopped + * and successCallback of this abort request executed. If aborting fails, + * then errorCallback must be called. Note, that callbacks of the aborted + * operation must not be called, as they will be ignored. Despite calling + * errorCallback, the request may be forcibly aborted. + */ + const onAbortRequested: chrome.events.Event<( + options: AbortRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when showing a configuration dialog for fileSystemId is requested. + * If it's handled, the file_system_provider.configurable manfiest option must be set to true. * @since Since Chrome 44. */ - export var onConfigureRequested: RequestedEvent; + const onConfigureRequested: chrome.events.Event<( + options: ConfigureRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when showing a dialog for mounting a new file system is requested. If the extension/app is a file handler, then this event shouldn't be handled. Instead app.runtime.onLaunched should be handled in order to mount new file systems when a file is opened. For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. + * Raised when showing a dialog for mounting a new file system is requested. + * If the extension/app is a file handler, then this event shouldn't be handled. + * Instead app.runtime.onLaunched should be handled in order to mount new file systems when a file is opened. + * For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. * @since Since Chrome 44. */ - export var onMountRequested: OptionlessRequestedEvent; + const onMountRequested: chrome.events.Event<( + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when setting a new directory watcher is requested. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Raised when setting a new directory watcher is requested. + * If an error occurs, then errorCallback must be called. + * @since Since Chrome 45. */ - export var onAddWatcherRequested: EntryPathRecursiveRequestedEvent; + const onAddWatcherRequested: chrome.events.Event<( + options: WatcherRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when the watcher should be removed. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Raised when the watcher should be removed. + * If an error occurs, then errorCallback must be called. + * @since Since Chrome 45. */ - export var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; + const onRemoveWatcherRequested: chrome.events.Event<( + options: WatcherRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when executing an action for a set of files or directories is\ requested. + * After the action is completed, successCallback must be called. + * On error, errorCallback must be called. + * @since Since Chrome 48. + */ + const onExecuteActionRequested: chrome.events.Event<( + options: ExecuteActionRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; } - //////////////////// - // Google Cloud Messaging - //////////////////// + //////////////////////////// + // Google Cloud Messaging // + //////////////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and receive messages through the Google Cloud Messaging Service. - * Availability: Since Chrome 35. - * Permissions: 'gcm' + * Use chrome.gcm to enable apps and extensions to send and receive + * messages through the Google Cloud Messaging Service. + * @deprecated + * As of April 10, 2018, Google has deprecated GCM. + * The GCM server and client APIs are deprecated and will be removed as soon as April 11, 2019. + * Migrate GCM apps to Firebase Cloud Messaging (FCM), + * which inherits the reliable and scalable GCM infrastructure, + * plus many new features. See the migration guide to learn more. + * @see[Migration guide]{@link https://developers.google.com/cloud-messaging/android/android-migrate-fcm} + * @see[GCM Imlementation guide]{@link https://developers.google.com/cloud-messaging/chrome/client} + * @since Availability: Since Chrome 35. + * @requires Permissions: 'gcm' */ namespace gcm { + /** + * The maximum size (in bytes) of all key/value pairs in a message. + * @default 4096 + */ + const MAX_MESSAGE_SIZE: integer; + interface IGCMData { 'collapse_key'?: never; 'goog'?: never; 'goog.'?: never; + 'GOOG'?: never; + 'GOOG.'?: never; 'google'?: never; 'GOOGLE'?: never; [key: string]: any; } + interface OutgoingMessage { /** The ID of the server to send the message to as assigned by Google API Console. */ destinationId: string; /** The ID of the message. It must be unique for each message in scope of the applications. See the Cloud Messaging documentation for advice for picking and handling an ID. */ messageId: string; - /** Optional. Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ - timeToLive?: number; + /** Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ + timeToLive?: integer; /** - * @description Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes. Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. + * Message data to send to the server. + * + * Case-insensitive goog. and google, + * as well as case-sensitive collapse_key + * are disallowed as key prefixes. + * + * Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. **/ data: IGCMData; } @@ -2439,21 +3502,12 @@ declare namespace chrome { interface GcmError { /** The error message describing the problem. */ errorMessage: string; - /** Optional. The ID of the message with this error, if error is related to a specific message. */ + /** The ID of the message with this error, if error is related to a specific message. */ messageId?: string; /** Additional details related to the error, when available. */ detail: Object; } - interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> { } - - interface MessageDeletionEvent extends chrome.events.Event<() => void> { } - - interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> { } - - /** The maximum size (in bytes) of all key/value pairs in a message. Default: 4096 */ - export var MAX_MESSAGE_SIZE: number; - /** * Registers the application with GCM. The registration ID will be returned by the callback. If register is called again with the same list of senderIds, the same registration ID will be returned. * @param senderIds A list of server IDs that are allowed to send messages to the application. It should contain at least one and no more than 100 sender IDs. @@ -2462,14 +3516,14 @@ declare namespace chrome { * function(string registrationId) {...}; * Parameter registrationId: A registration ID assigned to the application by the GCM. */ - export function register(senderIds: string[], callback: (registrationId: string) => void): void; + function register(senderIds: string[], callback: (registrationId: string) => void): void; /** * Unregisters the application from GCM. * @param callback A function called after the unregistration completes. Unregistration was successful if runtime.lastError is not set. * The callback parameter should be a function that looks like this: * function() {...}; */ - export function unregister(callback: () => void): void; + function unregister(callback: () => void): void; /** * Sends a message according to its contents. * @param message A message to send to the other party via GCM. @@ -2478,46 +3532,440 @@ declare namespace chrome { * function(string messageId) {...}; * Parameter messageId: The ID of the message that the callback was issued for. */ - export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; + function send(message: OutgoingMessage, callback: (messageId: string) => void): void; /** Fired when a message is received through GCM. */ - export var onMessage: MessageReceptionEvent; + const onMessage: chrome.events.Event<(message: IncomingMessage) => void>; /** Fired when a GCM server had to delete messages sent by an app server to the application. See Messages deleted event section of Cloud Messaging documentation for details on handling this event. */ - export var onMessagesDeleted: MessageDeletionEvent; + const onMessagesDeleted: chrome.events.Event<() => void>; /** Fired when it was not possible to send a message to the GCM server. */ - export var onSendError: GcmErrorEvent; + const onSendError: chrome.events.Event<(error: GcmError) => void>; } - //////////////////// - // HID - //////////////////// + ///////// + // HID // + ///////// /** - * Use the chrome.hid API to interact with connected HID devices. This API provides access to HID operations from within the context of an app. Using this API, apps can function as drivers for hardware devices. Errors generated by this API are reported by setting runtime.lastError and executing the function's regular callback. The callback's regular parameters will be undefined in this case. - * @since Chrome 38 + * Use the chrome.hid API to interact with connected HID devices. + * This API provides access to HID operations from within the context of an app. + * Using this API, apps can function as drivers for hardware devices. + * Errors generated by this API are reported by setting runtime.lastError + * and executing the function's regular callback. The callback's regular + * parameters will be undefined in this case. + * + * @requires Permissions: 'hid' + * @since Available since Chrome 38. */ namespace hid { - /** NOT YET IMPLEMENTED */ + interface Collection { + /** HID usage page identifier. */ + usagePage: integer; + /** Page-defined usage identifier. */ + usage: integer; + /** Report IDs which belong to the collection and to its children. */ + reportIds: integer[]; + } + interface HidDeviceInfo { + /** Opaque device ID. */ + deviceId: integer; + /** Vendor ID. */ + vendorId: integer; + /** Product ID. */ + productId: integer; + /** + * The product name read from the device, if available. + * @since Chrome 46 + * */ + productName: string; + /** + * The serial number read from the device, if available. + * @since Chrome 46 + */ + serialNumber: string; + /** + * Top-level collections from this device's report descriptors. + */ + collections: Collection[]; + /** Top-level collection's maximum input report size. */ + maxInputReportSize: integer; + /** Top-level collection's maximum output report size. */ + maxOutputReportSize: integer; + /** Top-level collection's maximum feature report size. */ + maxFeatureReportSize: integer; + /** + * Raw device report descriptor (not available on Windows). + * @since Chrome 42 + * */ + reportDescriptor: ArrayBuffer; + } + /** @since Chrome 39. */ + interface DeviceFilter { + /** Device vendor ID. */ + vendorId?: integer; + /** Device product ID, only checked only if the vendor ID matches. */ + productId?: integer; + /** HID usage page identifier. */ + usagePage?: integer; + /** HID usage identifier, checked only if the HID usage page matches. */ + usage?: integer; + } + interface DeviceOptions { + /** + * Equivalent to setting DeviceFilter.vendorId. + * @deprecated Deprecated since Chrome 39 + */ + vendorId?: chrome.deprecated; + /** + * Equivalent to setting DeviceFilter.productId. + * @deprecated Deprecated since Chrome 39. + */ + productId?: chrome.deprecated; + /** + * A device matching any given filter will be returned. + * An empty filter list will return all devices the app has permission for. + * @since Chrome 39 + */ + filters?: DeviceFilter[]; + } + interface UserSelectedDevicePickerOptions { + /** + * Allow the user to select multiple devices. + */ + multiple?: boolean; + /** + * Filter the list of devices presented to the user. + * If multiple filters are provided devices matching any filter will be displayed. + */ + filters?: DeviceFilter[]; + } + + /** + * Enumerate connected HID devices. + * @param options The properties to search for on target devices. + * @param callback + */ + function getDevices(options: DeviceOptions, callback: (devices: HidDeviceInfo[]) => void): void; + + /** + * @requires(dev) **Dev channel only!** + * @see[Learn more]{@link https://developer.chrome.com/apps/api_index#dev_apis} + * @description + * Presents a device picker to the user and returns + * HidDeviceInfo objects for the devices selected. If the user + * cancels the picker devices will be empty. A user gesture is + * required for the dialog to display. Without a user gesture, + * the callback will run as though the user cancelled. If multiple + * filters are provided devices matching any filter will be displayed. + * @param callback Invoked with a list of chosen Devices. + */ + function getUserSelectedDevices(callback: (devices: HidDeviceInfo) => void): void; + + /** + * @since Since Chrome 45. + * @requires(dev) **Dev channel only!** + * @see[Learn more]{@link https://developer.chrome.com/apps/api_index#dev_apis} + * Presents a device picker to the user and returns + * HidDeviceInfo objects for the devices selected. If the user + * cancels the picker devices will be empty. A user gesture is + * required for the dialog to display. Without a user gesture, + * the callback will run as though the user cancelled. If multiple + * filters are provided devices matching any filter will be displayed. + * @param options Configuration of the device picker dialog box. + * @param callback Invoked with a list of chosen Devices. + */ + function getUserSelectedDevices(options: UserSelectedDevicePickerOptions, callback: (devices: HidDeviceInfo) => void): void; + + /** + * Open a connection to an HID device for communication. + * @param deviceId The HidDeviceInfo.deviceId of the device to open. + * @param callback The callback function returns an object, containing the connectionId. + * The connectionId is the opaque ID used to identify this connection in all other functions. + */ + function connect(deviceId: number, callback: (connection: { connectionId: number }) => void): void; + + /** + * Disconnect from a device. + * Invoking operations on a device after calling this is safe but has no effect. + * @param connectionId The connectionId returned by connect. + * @param [callback] + */ + function disconnect(connectionId: integer, callback?: () => void): void; + + /** + * Receive the next input report from the device. + * @param connectionId The connectionId returned by connect. + * @param callback The callback will return these parameters: + * * reportId - The report ID or 0 if none. + * * data - The report data, the report ID prefix (if present) is removed. + */ + function receive(connectionId: integer, callback: (reportId: integer, data: ArrayBuffer) => void): void; + + /** + * Send an output report to the device. + * Note: Do not include a report ID prefix in data. It will be added if necessary. + * @param connectionId The connectionId returned by connect. + * @param reportId reportId - The report ID or 0 if none. + * @param data The report data. + * @param callback + */ + function send(connectionId: integer, reportId: integer, data: ArrayBuffer, callback: () => void): void; + + /** + * Request a feature report from the device. + * @param connectionId The connectionId returned by connect. + * @param reportId The report ID, or 0 if none. + * @param callback Will provide `data` which contain the report data, including a report ID prefix if one is sent by the device. + */ + function receiveFeatureReport(connectionId: integer, reportId: integer, callback: (data: ArrayBuffer) => void): void; + + /** + * Send a feature report to the device. + * Note: Do not include a report ID prefix in data. It will be added if necessary. + * @param connectionId The connectionId returned by connect. + * @param reportId The report ID to use, or 0 if none. + * @param data The report data. + * @param callback + */ + function sendFeatureReport(connectionId: integer, reportId: integer, data: ArrayBuffer, callback: () => void): void; + + /** + * Event generated when a device is added to the system. + * Events are only broadcast to apps and extensions that + * have permission to access the device. Permission may + * have been granted at install time or when the user + * accepted an optional permission. + * @since Chrome 41. + * @see[permissions.request]{@link https://developer.chrome.com/apps/permissions#method-request} + */ + const onDeviceAdded: chrome.events.Event<(device: HidDeviceInfo) => void>; + + /** + * Event generated when a device is removed from the system. + * The callback will contain the deviceId property of the device passed to onDeviceAdded. + * @since Chrome 41. + * @see[See onDeviceAdded for which events are delivered]{@link https://developer.chrome.com/apps/hid#event-onDeviceAdded}. + */ + const onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; } - //////////////////// - // i18n - //////////////////// + ///////////////////////////////// + // i18n - Internationalization // + ///////////////////////////////// /** - * Use the chrome.i18n infrastructure to implement internationalization across your whole app or extension. - * @since Chrome 5. + * Use the chrome.i18n infrastructure to implement internationalization across your whole app. + * Content scripts: Fully supported. + * @see[Docs]{@link https://developer.chrome.com/apps/i18n} + * @since Chrome 25. */ namespace i18n { + /** + * An ISO language code such as en or fr. + * For a complete list of languages supported by this method, see kLanguageInfoTable. + * For an unknown language, und will be returned, + * which means that [percentage] of the text is unknown to CLD + * @since Chrome 47. + */ + type LanguageCode = kLanguageInfoTable | 'und'; + /** + * @see[Source]{@link https://github.com/chromium/chromium/blob/master/ui/base/l10n/l10n_util.cc} + */ + type kLanguageInfoTable = + 'af' | // Afrikaans + 'am' | // Amharic + 'an' | // Aragonese + 'ar' | // Arabic + 'ast' | // Asturian + 'az' | // Azerbaijani + 'be' | // Belarusian + 'bg' | // Bulgarian + 'bh' | // Bihari + 'bn' | // Bengali + 'br' | // Breton + 'bs' | // Bosnian + 'ca' | // Catalan + 'ceb' | // Cebuano + 'ckb' | // Kurdish (Arabci), Sorani + 'co' | // Corsican + 'cs' | // Czech + 'cy' | // Welsh + 'da' | // Danish + 'de' | // German + 'de-AT' | // German (Austria) + 'de-CH' | // German (Switzerland) + 'de-DE' | // German (Germany) + 'de-LI' | // German (Liechtenstein) + 'el' | // Greek + 'en' | // English + 'en-AU' | // English (Australia) + 'en-CA' | // English (Canada) + 'en-GB' | // English (UK) + 'en-IN' | // English (India) + 'en-NZ' | // English (New Zealand) + 'en-US' | // English (US) + 'en-ZA' | // English (South Africa) + 'eo' | // Esperanto + // TODO(jungshik) : Do we want to list all es-Foo for Latin-American + // Spanish speaking countries? + 'es' | // Spanish + 'es-419' | // Spanish (Latin America) + 'es-AR' | // Spanish (Argentina) + 'es-CL' | // Spanish (Chile) + 'es-CO' | // Spanish (Colombia) + 'es-CR' | // Spanish (Costa Rica) + 'es-ES' | // Spanish (Spain) + 'es-HN' | // Spanish (Honduras) + 'es-MX' | // Spanish (Mexico) + 'es-PE' | // Spanish (Peru) + 'es-US' | // Spanish (US) + 'es-UY' | // Spanish (Uruguay) + 'es-VE' | // Spanish (Venezuela) + 'et' | // Estonian + 'eu' | // Basque + 'fa' | // Persian + 'fi' | // Finnish + 'fil' | // Filipino + 'fo' | // Faroese + 'fr' | // French + 'fr-CA' | // French (Canada) + 'fr-CH' | // French (Switzerland) + 'fr-FR' | // French (France) + 'fy' | // Frisian + 'ga' | // Irish + 'gd' | // Scots Gaelic + 'gl' | // Galician + 'gn' | // Guarani + 'gu' | // Gujarati + 'ha' | // Hausa + 'haw' | // Hawaiian + 'he' | // Hebrew + 'hi' | // Hindi + 'hmn' | // Hmong + 'hr' | // Croatian + 'ht' | // Haitian Creole + 'hu' | // Hungarian + 'hy' | // Armenian + 'ia' | // Interlingua + 'id' | // Indonesian + 'ig' | // Igbo + 'is' | // Icelandic + 'it' | // Italian + 'it-CH' | // Italian (Switzerland) + 'it-IT' | // Italian (Italy) + 'ja' | // Japanese + 'jv' | // Javanese + 'ka' | // Georgian + 'kk' | // Kazakh + 'km' | // Cambodian + 'kn' | // Kannada + 'ko' | // Korean + 'ku' | // Kurdish + 'ky' | // Kyrgyz + 'la' | // Latin + 'lb' | // Luxembourgish + 'ln' | // Lingala + 'lo' | // Laothian + 'lt' | // Lithuanian + 'lv' | // Latvian + 'mg' | // Malagasy + 'mi' | // Maori + 'mk' | // Macedonian + 'ml' | // Malayalam + 'mn' | // Mongolian + 'mo' | // Moldavian + 'mr' | // Marathi + 'ms' | // Malay + 'mt' | // Maltese + 'my' | // Burmese + 'nb' | // Norwegian (Bokmal) + 'ne' | // Nepali + 'nl' | // Dutch + 'nn' | // Norwegian (Nynorsk) + 'no' | // Norwegian + 'ny' | // Nyanja + 'oc' | // Occitan + 'om' | // Oromo + 'or' | // Oriya + 'pa' | // Punjabi + 'pl' | // Polish + 'ps' | // Pashto + 'pt' | // Portuguese (pt-BR and pt-PT are used) + 'pt-BR' | // Portuguese (Brazil) + 'pt-PT' | // Portuguese (Portugal) + 'qu' | // Quechua + 'rm' | // Romansh + 'ro' | // Romanian + 'ru' | // Russian + 'sd' | // Sindhi + 'sh' | // Serbo-Croatian + 'si' | // Sinhalese + 'sk' | // Slovak + 'sl' | // Slovenian + 'sm' | // Samoan + 'sn' | // Shona + 'so' | // Somali + 'sq' | // Albanian + 'sr' | // Serbian + 'st' | // Sesotho + 'su' | // Sundanese + 'sv' | // Swedish + 'sw' | // Swahili + 'ta' | // Tamil + 'te' | // Telugu + 'tg' | // Tajik + 'th' | // Thai + 'ti' | // Tigrinya + 'tk' | // Turkmen + 'to' | // Tonga + 'tr' | // Turkish + 'tt' | // Tatar + 'tw' | // Twi + 'ug' | // Uighur + 'uk' | // Ukrainian + 'ur' | // Urdu + 'uz' | // Uzbek + 'vi' | // Vietnamese + 'wa' | // Walloon + 'xh' | // Xhosa + 'yi' | // Yiddish + 'yo' | // Yoruba + 'zh' | // Chinese + 'zh-CN' | // Chinese (China) + 'zh-HK' | // Chinese (Hong Kong) + 'zh-TW' | // Chinese (Taiwan) + 'zu' | // Zulu + // Aliases: + 'ar_001' | + 'en_001' | + 'en_150' | + 'zh_hans_cn' | + 'zh_hant_hk' | + 'zh_hant_mo' | + 'zh_hans_sg' | + 'zh_hant_tw'; + + /** Allow array of strings with length 1 to 9 */ + type StringSubstitutions = + [string] | + [string, string] | + [string, string, string] | + [string, string, string, string] | + [string, string, string, string, string] | + [string, string, string, string, string, string] | + [string, string, string, string, string, string, string] | + [string, string, string, string, string, string, string, string] | + [string, string, string, string, string, string, string, string, string]; + /** Holds detected ISO language code and its percentage in the input string */ interface DetectedLanguage { /** - * @description An ISO language code such as 'en' or 'fr'. - * @description For a complete list of languages supported by this method: + * An ISO language code such as 'en' or 'fr'. + * For a complete list of languages supported by this method: * @see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}. - * @description For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ - language: string; + * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ + language: kLanguageInfoTable; /** The percentage of the detected language */ - percentage: number; + percentage: integer; } /** Holds detected language reliability and array of DetectedLanguage */ @@ -2525,60 +3973,75 @@ declare namespace chrome { /** CLD detected language reliability */ isReliable: boolean; - /** Array of detectedLanguage */ + /** Array of DetectedLanguage */ languages: DetectedLanguage[]; } /** - * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. - * @param callback The callback parameter should be a function that looks like this: - * function(array of string languages) {...}; - * Parameter languages: Array of the accept languages of the browser, such as en-US,en,zh-CN + * Gets the accept-languages of the browser. + * This is different from the locale used by the browser; + * to get the locale, use i18n.getUILanguage. */ - export function getAcceptLanguages(callback: (languages: string[]) => void): void; + function getAcceptLanguages(callback: (languages: LanguageCode[]) => void): void; /** - * Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the getMessage() call is wrong — for example, messageName is not a string or the substitutions array has more than 9 elements — this method returns undefined. + * Gets the localized string for the specified message. + * If the message is missing, this method returns an empty string (''). + * If the format of the getMessage() call is wrong — for example, + * messageName is not a string or the substitutions array has + * more than 9 elements — this method returns undefined. + * * @param messageName The name of the message, as specified in the messages.json file. - * @param substitutions Optional. Up to 9 substitution strings, if the message requires any. + * @param substitutions Up to 9 substitution strings, if the message requires any. */ - export function getMessage(messageName: string, substitutions?: any): string | undefined; + function getMessage(messageName: string, substitutions?: StringSubstitutions): string | undefined; /** - * Gets the browser UI language of the browser. This is different from i18n.getAcceptLanguages which returns the preferred user languages. + * Gets the browser UI language of the browser. + * This is different from i18n.getAcceptLanguages which returns the preferred user languages. * @since Chrome 35. */ - export function getUILanguage(): string; + function getUILanguage(): string; - /** Detects the language of the provided text using CLD. + /** + * Detects the language of the provided text using CLD. * @param text User input string to be translated. - * @param callback The callback parameter should be a function that looks like this: function(object result) {...}; + * @param callback + * @since Chrome 47. */ - export function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; + function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; } - //////////////////// - // Identity - //////////////////// + ////////////// + // Identity // + ////////////// /** * Use the chrome.identity API to get OAuth2 access tokens. - * Permissions: 'identity' + * @requires Permissions: 'identity' + * @see[Identity User]{@link https://developer.chrome.com/apps/app_identity} * @since Chrome 29. */ namespace identity { /** @since Chrome 32. */ interface AccountInfo { - /** A unique identifier for the account. This ID will not change for the lifetime of the account. */ + /** + * A unique identifier for the account. + * This ID will not change for the lifetime of the account. + */ id: string; } interface TokenDetails { /** - * Optional. - * Fetching a token may require the user to sign-in to Chrome, or approve the application's requested scopes. If the interactive flag is true, getAuthToken will prompt the user as necessary. When the flag is false or omitted, getAuthToken will return failure any time a prompt would be required. + * Fetching a token may require the user to sign-in to Chrome, + * or approve the application's requested scopes. + * If the interactive flag is true, getAuthToken will prompt the user as necessary. + * When the flag is false or omitted, getAuthToken will return failure any time + * a prompt would be required. */ interactive?: boolean; /** * Optional. - * The account ID whose token should be returned. If not specified, the primary account for the profile will be used. + * The account ID whose token should be returned. + * If not specified, the primary account for the profile will be used. * account is only supported when the 'enable-new-profile-management' flag is set. * @since Chrome 37. */ @@ -2593,9 +4056,17 @@ declare namespace chrome { } interface UserInfo { - /** An email address for the user account signed into the current profile. Empty if the user is not signed in or the identity.email manifest permission is not specified. */ + /** + * An email address for the user account signed into the current profile. + * Empty if the user is not signed in or the identity.email manifest permission is not specified. + */ email: string; - /** A unique identifier for the account. This ID will not change for the lifetime of the account. Empty if the user is not signed in or (in M41+) the identity.email manifest permission is not specified. */ + /** + * A unique identifier for the account. + * This ID will not change for the lifetime of the account. + * Empty if the user is not signed in or (in M41+) the identity.email + * manifest permission is not specified. + */ id: string; } @@ -2605,7 +4076,9 @@ declare namespace chrome { } interface WebAuthFlowOptions { - /** The URL that initiates the auth flow. */ + /** + * The URL that initiates the auth flow. + */ url: string; /** * Optional. @@ -2616,75 +4089,97 @@ declare namespace chrome { interactive?: boolean; } - interface SignInChangeEvent extends chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void> { } - /** + * @requires(dev) **Dev channel only.** + * @description * Retrieves a list of AccountInfo objects describing the accounts present on the profile. * getAccounts is only supported on dev channel. - * Dev channel only. */ - export function getAccounts(callback: (accounts: AccountInfo[]) => void): void; + function getAccounts(callback: (accounts: AccountInfo[]) => void): void; + /** - * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. - * The Identity API caches access tokens in memory, so it's ok to call getAuthToken non-interactively any time a token is required. The token cache automatically handles expiration. - * For a good user experience it is important interactive token requests are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests, or Chrome sign in screens if they are not signed in, with with no context. In particular, do not use getAuthToken interactively when your app is first launched. + * Gets an OAuth2 access token using the client ID and + * scopes specified in the oauth2 section of manifest.json. + * + * The Identity API caches access tokens in memory, + * so it's ok to call getAuthToken non-interactively any time a token is required. + * The token cache automatically handles expiration. + * + * For a good user experience it is important interactive token requests are initiated by + * UI in your app explaining what the authorization is for. Failing to do this will cause + * your users to get authorization requests, or Chrome sign in screens if they are not + * signed in, with with no context. In particular, do not use getAuthToken interactively + * when your app is first launched. + * * @param details Token options. - * @param callback Called with an OAuth2 access token as specified by the manifest, or undefined if there was an error. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string token) {...}; + * @param [callback] Called with an OAuth2 access token as specified by the manifest, + * or undefined if there was an error. */ - export function getAuthToken(details: TokenDetails, callback?: (token: string) => void): void; + function getAuthToken(details: TokenDetails, callback?: (token: string) => void): void; + /** * Retrieves email address and obfuscated gaia id of the user signed into a profile. - * This API is different from identity.getAccounts in two ways. The information returned is available offline, and it only applies to the primary account for the profile. + * This API is different from identity.getAccounts in two ways. + * The information returned is available offline, and it only applies to the primary account for the profile. * @since Chrome 37. */ - export function getProfileUserInfo(callback: (userInfo: UserInfo) => void): void; + function getProfileUserInfo(callback: (userInfo: UserInfo) => void): void; + /** * Removes an OAuth2 access token from the Identity API's token cache. - * If an access token is discovered to be invalid, it should be passed to removeCachedAuthToken to remove it from the cache. The app may then retrieve a fresh token with getAuthToken. + * If an access token is discovered to be invalid, + * it should be passed to removeCachedAuthToken to remove it from the cache. + * The app may then retrieve a fresh token with getAuthToken. * @param details Token information. * @param callback Called when the token has been removed from the cache. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function removeCachedAuthToken(details: TokenInformation, callback?: () => void): void; + function removeCachedAuthToken(details: TokenInformation, callback?: () => void): void; + /** * Starts an auth flow at the specified URL. - * This method enables auth flows with non-Google identity providers by launching a web view and navigating it to the first URL in the provider's auth flow. When the provider redirects to a URL matching the pattern https://.chromiumapp.org/*, the window will close, and the final redirect URL will be passed to the callback function. - * For a good user experience it is important interactive auth flows are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests with no context. In particular, do not launch an interactive auth flow when your app is first launched. + * This method enables auth flows with non-Google identity providers by launching + * a web view and navigating it to the first URL in the provider's auth flow. + * When the provider redirects to a URL matching the pattern https://.chromiumapp.org/*, + * the window will close, and the final redirect URL will be passed to the callback function. + * For a good user experience it is important interactive auth flows are initiated by UI in + * your app explaining what the authorization is for. Failing to do this will cause your + * users to get authorization requests with no context. + * In particular, do not launch an interactive auth flow when your app is first launched. * @param details WebAuth flow options. * @param callback Called with the URL redirected back to your application. * The callback parameter should be a function that looks like this: * function(string responseUrl) {...}; */ - export function launchWebAuthFlow(details: WebAuthFlowOptions, callback: (responseUrl?: string) => void): void; + function launchWebAuthFlow(details: WebAuthFlowOptions, callback: (responseUrl?: string) => void): void; + /** * Generates a redirect URL to be used in launchWebAuthFlow. * The generated URLs match the pattern https://.chromiumapp.org/*. * @since Chrome 33. - * @param path Optional. The path appended to the end of the generated URL. + * @param path The path appended to the end of the generated URL. */ - export function getRedirectURL(path?: string): string; + function getRedirectURL(path?: string): string; /** * Fired when signin state changes for an account on the user's profile. * @since Chrome 33. */ - export var onSignInChanged: SignInChangeEvent; + const onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; } - //////////////////// - // Idle - //////////////////// + ////////// + // Idle // + ////////// /** * Use the chrome.idle API to detect when the machine's idle state changes. - * Permissions: 'idle' - * @since Chrome 6. + * @requires Permissions: 'idle' + * @since Chrome 25. */ namespace idle { - interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> { } - + type IdleState = + 'active' | + 'idle' | + 'locked'; /** * Returns 'locked' if the system is locked, 'idle' if the user has not generated any input for a specified number of seconds, or 'active' otherwise. * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. @@ -2692,88 +4187,481 @@ declare namespace chrome { * @param callback The callback parameter should be a function that looks like this: * function( IdleState newState) {...}; */ - export function queryState(detectionIntervalInSeconds: number, callback: (newState: string) => void): void; + function queryState(detectionIntervalInSeconds: integer, callback: (newState: IdleState) => void): void; /** - * Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds. + * Sets the interval, in seconds, used to determine when the system is in an idle state for + * onStateChanged events. + * The default interval is 60 seconds. * @since Chrome 25. * @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state. */ - export function setDetectionInterval(intervalInSeconds: number): void; + function setDetectionInterval(intervalInSeconds: integer): void; - /** Fired when the system changes to an active, idle or locked state. The event fires with 'locked' if the screen is locked or the screensaver activates, 'idle' if the system is unlocked and the user has not generated any input for a specified number of seconds, and 'active' when the user generates input on an idle system. */ - export var onStateChanged: IdleStateChangedEvent; + /** + * Fired when the system changes to an active, idle or locked state. + * The event fires with 'locked' if the screen is locked or the screensaver activates, + * 'idle' if the system is unlocked and the user has not generated any input for a + * specified number of seconds, and 'active' when the user generates input on an idle system. + */ + const onStateChanged: chrome.events.Event<(newState: IdleState) => void>; } - //////////////////// - // InstanceID - //////////////////// + //////////////// + // InstanceID // + //////////////// /** * Use chrome.instanceID to access the Instance ID service. + * @requires Permissions: 'gcm' * @since Chrome 46 */ namespace instanceID { - /** NOT YET IMPLEMENTED */ + interface TokenParams { + /** + * Identifies the entity that is authorized to access resources associated with this Instance ID. + * It can be a project ID from Google developer console. + */ + authorizedEntity: string; + /** + * Identifies authorized actions that the authorized entity can take. + * E.g. for sending GCM messages, GCM scope should be used. + */ + scope: string; + /** + * Allows including a small number of string key/value pairs that will + * be associated with the token and may be used in processing the request. + */ + options?: { [key: string]: string }; + } + interface DeleteTokenParams { + /** + * The authorized entity that is used to obtain the token. + */ + authorizedEntity: string; + /** + * The scope that is used to obtain the token. + */ + scope: string; + } + /** + * Retrieves an identifier for the app instance. + * The instance ID will be returned by the callback. + * The same ID will be returned as long as the application + * identity has not been revoked or expired. + * @param callback Function called when the retrieval completes. + * It should check runtime.lastError for error when instanceID is empty. + * Will be provided with instanceID: An Instance ID assigned to the app instance. + */ + function getID(callback: (instanceId: string) => void): void; + /** + * Retrieves the time when the InstanceID has been generated. + * The creation time will be returned by the callback. + * @param callback Function called when the retrieval completes. + * It should check runtime.lastError for error when creationTime is zero. + * Provides `creationTime` (double) + * > The time when the Instance ID has been generated, represented in milliseconds since the epoch. + */ + function getCreationTime(callback: (creationTime: number) => void): void; + /** + * Return a token that allows the authorized entity to access the service defined by scope. + * @param getTokenParams Parameters for getToken. + * @param callback Function called when the retrieval completes. It should check runtime.lastError for error when token is empty. + */ + function getToken(getTokenParams: TokenParams, callback: (token: string) => void): void; + /** + * Revokes a granted token. + * @param deleteTokenParams Parameters for deleteToken. + * @param callback Function called when the token deletion completes. + * The token was revoked successfully if runtime.lastError is not set. + */ + function deleteToken(deleteTokenParams: DeleteTokenParams, callback: () => void): void; + /** + * Fired when all the granted tokens need to be refreshed. + * @param callback Function called when the deletion completes. + * The instance identifier was revoked successfully if runtime.lastError is not set. + */ + function deleteID(callback: () => void): void; + /** Fired when all the granted tokens need to be refreshed. */ + const onTokenRefresh: chrome.events.Event<() => void>; + } + + //////////////// + // Management // + //////////////// + /** + * The chrome.management API provides ways to manage the list of extensions/apps + * that are installed and running. It is particularly useful for extensions that + * override the built-in New Tab page. + * @requires Permissions: "management" + */ + namespace management { + /** Information about an installed extension, app, or theme. */ + interface ExtensionInfo { + /** + * Optional. + * A reason the item is disabled. + * @since Chrome 17. + */ + disabledReason?: string; + /** Optional. The launch url (only present for apps). */ + appLaunchUrl?: string; + /** + * The description of this extension, app, or theme. + * @since Chrome 9. + */ + description: string; + /** + * Returns a list of API based permissions. + * @since Chrome 9. + */ + permissions: string[]; + /** + * Optional. + * A list of icon information. Note that this just reflects what was declared in the manifest, and the actual image at that url may be larger or smaller than what was declared, so you might consider using explicit width and height attributes on img tags referencing these images. See the manifest documentation on icons for more details. + */ + icons?: IconInfo[]; + /** + * Returns a list of host based permissions. + * @since Chrome 9. + */ + hostPermissions: string[]; + /** Whether it is currently enabled or disabled. */ + enabled: boolean; + /** + * Optional. + * The URL of the homepage of this extension, app, or theme. + * @since Chrome 11. + */ + homepageUrl?: string; + /** + * Whether this extension can be disabled or uninstalled by the user. + * @since Chrome 12. + */ + mayDisable: boolean; + /** + * How the extension was installed. + * @since Chrome 22. + */ + installType: string; + /** The version of this extension, app, or theme. */ + version: string; + /** The extension's unique identifier. */ + id: string; + /** + * Whether the extension, app, or theme declares that it supports offline. + * @since Chrome 15. + */ + offlineEnabled: boolean; + /** + * Optional. + * The update URL of this extension, app, or theme. + * @since Chrome 16. + */ + updateUrl?: string; + /** + * The type of this extension, app, or theme. + * @since Chrome 23. + */ + type: 'packaged_app' | string; + /** The url for the item's options page, if it has one. */ + optionsUrl: string; + /** The name of this extension, app, or theme. */ + name: string; + /** + * A short version of the name of this extension, app, or theme. + * @since Chrome 31. + */ + shortName: string; + /** + * True if this is an app. + * @deprecated since Chrome 33. Please use management.ExtensionInfo.type. + */ + isApp: boolean; + /** + * Optional. + * The app launch type (only present for apps). + * @since Chrome 37. + */ + launchType?: string; + /** + * Optional. + * The currently available launch types (only present for apps). + * @since Chrome 37. + */ + availableLaunchTypes?: string[]; + } + + /** Information about an icon belonging to an extension, app, or theme. */ + interface IconInfo { + /** The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is disabled, for example), append ?grayscale=true to the URL. */ + url: string; + /** A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16. */ + size: number; + } + + interface UninstallOptions { + /** + * Optional. + * Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false for self uninstalls. If an extension uninstalls another extension, this parameter is ignored and the dialog is always shown. + */ + showConfirmDialog?: boolean; + } + + interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> { } + + interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + /** + * Enables or disables an app or extension. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param enabled Whether this item should be enabled or disabled. + * @param [callback] + */ + function setEnabled(id: string, enabled: boolean, callback?: () => void): void; + /** + * Returns a list of permission warnings for the given extension id. + * @since Chrome 15. + * @param id The ID of an already installed extension. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of string permissionWarnings) {...}; + */ + function getPermissionWarningsById(id: string, callback?: (permissionWarnings: string[]) => void): void; + /** + * Returns information about the installed extension, app, or theme that has the given ID. + * @param id The ID from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function get(id: string, callback?: (result: ExtensionInfo) => void): void; + /** + * Returns a list of information about installed extensions and apps. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of ExtensionInfo result) {...}; + */ + function getAll(callback?: (result: ExtensionInfo[]) => void): void; + /** + * Returns a list of permission warnings for the given extension manifest string. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @param manifestStr Extension manifest JSON string. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of string permissionWarnings) {...}; + */ + function getPermissionWarningsByManifest(manifestStr: string, callback?: (permissionWarnings: string[]) => void): void; + /** + * Launches an application. + * @param id The extension id of the application. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function launchApp(id: string, callback?: () => void): void; + /** + * Uninstalls a currently installed app or extension. + * @since Chrome 21. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstall(id: string, options?: UninstallOptions, callback?: () => void): void; + /** + * Uninstalls a currently installed app or extension. + * @deprecated since Chrome 21. The options parameter was added to this function. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstall(id: string, callback?: () => void): void; + /** + * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 39. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function getSelf(callback?: (result: ExtensionInfo) => void): void; + /** + * Uninstalls the calling extension. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 26. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstallSelf(options?: UninstallOptions, callback?: () => void): void; + /** + * Uninstalls the calling extension. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 26. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstallSelf(callback?: () => void): void; + /** + * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. + * @since Chrome 37. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function createAppShortcut(id: string, callback?: () => void): void; + /** + * Set the launch type of an app. + * @since Chrome 37. + * @param id This should be the id from an app item of management.ExtensionInfo. + * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function setLaunchType(id: string, launchType: string, callback?: () => void): void; + /** + * Generate an app for a URL. Returns the generated bookmark app. + * @since Chrome 37. + * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". + * @param title The title of the generated app. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function generateAppForLink(url: string, title: string, callback?: (result: ExtensionInfo) => void): void; + + /** Fired when an app or extension has been disabled. */ + var onDisabled: ManagementDisabledEvent; + /** Fired when an app or extension has been uninstalled. */ + var onUninstalled: ManagementUninstalledEvent; + /** Fired when an app or extension has been installed. */ + var onInstalled: ManagementInstalledEvent; + /** Fired when an app or extension has been enabled. */ + var onEnabled: ManagementEnabledEvent; } //////////////////// // mDNS //////////////////// /** - * Use the chrome.mdns API to discover services over mDNS. This comprises a subset of the features of the NSD spec: http://www.w3.org/TR/discovery-api/ + * Use the chrome.mdns API to discover services over mDNS. + * This comprises a subset of the features of the NSD spec: + * @see[NSD Spec]{@link http://www.w3.org/TR/discovery-api/} + * @requires Permissions: 'mdns' * @since Chrome 31 */ namespace mdns { - /** NOT YET IMPLEMENTED */ + interface Service { + /** The service name of an mDNS advertised service, .. */ + serviceName: string; + /** The host:port pair of an mDNS advertised service. */ + serviceHostPort: string; + /** The IP address of an mDNS advertised service. */ + ipAddress: string; + /** Metadata for an mDNS advertised service. */ + serviceData: string[]; + } + /** + * The maximum number of service instances that will be + * included in onServiceList events. If more instances + * are available, they may be truncated from the + * onServiceList event. + * @default 2048 + * @since Chrome 44. + */ + const MAX_SERVICE_INSTANCES_PER_EVENT: number; + /** + * Immediately issues a multicast DNS query for all service types. + * |callback| is invoked immediately. + * At a later time, queries will be sent, + * and any service events will be fired. + * @since Chrome 45. + * @param callback Callback invoked after ForceDiscovery() has started. + */ + function forceDiscovery(callback: () => void): void; + /** + * Event fired to inform clients of the current complete + * set of known available services. Clients should only + * need to store the list from the most recent event. + * The service type that the extension is interested in + * discovering should be specified as the event filter + * with the 'serviceType' key. Not specifying an event + * filter will not start any discovery listeners. + */ + const onServiceList: chrome.events.Event<(services: Service[]) => void>; + } //////////////////// // Media Galleries //////////////////// + /** + * Use the chrome.mediaGalleries API to access media files (audio, images, video) + * from the user's local disks (with the user's consent). + * @since Available since Chrome 24. + * @requires Permissions: {'mediaGalleries': ['accessType1' | 'accessType2', ...]} + * {'mediaGalleries': ['accessType1' | 'accessType2', ..., 'allAutoDetected']} + * @see[More information]{@link https://developer.chrome.com/apps/mediaGalleries} + */ namespace mediaGalleries { + type Interactive = + 'no' | + 'yes' | + 'if_needed'; interface MediaFileSystemsOptions { - interactive?: 'no' | 'yes' | 'if_needed'; + /** + * Whether to prompt the user for permission to additional media galleries before returning + * the permitted set. Default is silent. If the value 'yes' is passed, or if the application + * has not been granted access to any media galleries and the value 'if_needed' is passed, + * then the media gallery configuration dialog will be displayed. + * + * **no** + * Do not act interactively. + * **yes** + * Ask the user to manage permitted media galleries. + * **if_needed** + * Ask the user to manage permitted galleries only if the return set would otherwise be empty. + */ + interactive?: Interactive; } - interface MediaFileSystemMetadata { + /** The name of the file system. */ name: string; + /** A unique and persistent id for the media gallery. */ galleryId: string; + /** If the media gallery is on a removable device, a unique id for the device while the device is online. */ deviceId?: string; + /** True if the media gallery is on a removable device. */ isRemovable: boolean; + /** True if the device the media gallery is on was detected as a media device. i.e. a PTP or MTP device, or a DCIM directory is present. */ isMediaDevice: boolean; + /** True if the device is currently available. */ isAvailable: boolean; } + type MetadataOptionsType = + 'all' | + 'mimeTypeAndTags' | + 'mimeTypeOnly'; + interface MetadataOptions { - metadataType: 'all' | 'mimeTypeAndTags' | 'mimeTypeOnly'; + metadataType: MetadataOptionsType; } interface RawTag { + /** + * Describes format of container or codec of stream, i.e. 'mp3' | 'h264'. + */ type: string; + /** + * An unfiltered string->string dictionary of tags for the stream. + */ tags: { [name: string]: string; }; } interface Metadata { - // The browser sniffed mime type. + /** The browser sniffed mime type. */ mimeType: string; - // Defined for images and video. In pixels. - height?: number; - width?: number; - // Defined for images only. - xResolution?: number; - yResolution?: number; - // Defined for audio and video. In seconds. - duration?: number; - // Defined for images and video. In degrees. - rotation?: number; - // Defined for images only. - cameraMake?: string; - cameraModel?: string; - exposureTimeSeconds?: number; - flashFired?: boolean; - fNumber?: number; - focalLengthMm?: number; - isoEquivalent?: number; - // Defined for audio and video only. + /** Defined for images and video. In pixels. */ + height?: integer; + width?: integer; + /** Defined for audio and video. In seconds. */ + duration?: integer; + /** Defined for images and video. In degrees. */ + rotation?: integer; + /** Defined for audio and video only. */ album?: string; artist?: string; comment?: string; @@ -2783,9 +4671,16 @@ declare namespace chrome { language?: string; title?: string; track?: number; - // All the metadata in the media file. For formats with multiple streams, stream order will be preserved. Container metadata is the first element. + /** + * All the metadata in the media file. + * For formats with multiple streams, stream order will be preserved. + * Container metadata is the first element. + */ rawTags: RawTag[]; - // The images embedded in the media file's metadata. This is most often used for album art or video thumbnails. + /** + * The images embedded in the media file's metadata. + * This is most often used for album art or video thumbnails. + */ attachedImages: Blob[]; } @@ -2794,167 +4689,793 @@ declare namespace chrome { success: boolean; } + type GalleryChangedType = + 'contents_changed' | + 'watch_dropped'; + interface GalleryChangedEventArgs { - type: 'contents_changed' | 'watch_dropped'; + type: GalleryChangedType; galleryId: string; } + type ScanProgressType = + 'start' | + 'cancel' | + 'finish' | + 'error'; + interface ScanProgressEventArgs { - // The type of progress event, i.e. start, finish, etc. - type: 'start' | 'cancel' | 'finish' | 'error'; - // The number of Galleries found. - galleryCount?: number; - // Appoximate number of media files found; some file types can be either audio or video and are included in both counts. - audioCount?: number; - imageCount?: number; - videoCount?: number; + /** The type of progress event, i.e. start, finish, etc. */ + type: ScanProgressType; + /** The number of Galleries found. */ + galleryCount?: integer; + /** + * Appoximate number of media files found; + * some file types can be either audio or video + * and are included in both counts. + */ + audioCount?: integer; + imageCount?: integer; + videoCount?: integer; } - export function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void; - export function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void; - export function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void; - export function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void; - export function startMediaScan(): void; - export function cancelMediaScan(): void; - export function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void; - export function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata; - export function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void; - export function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void; - export function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void; - export function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void; - export function removeGalleryWatch(galleryId: string): void; - export function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void; - export function removeAllGalleryWatch(): void; - - export var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; - export var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; + /** + * Get the media galleries configured in this user agent. + * If none are configured or available, the callback will receive an empty array. + */ + function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Get the media galleries configured in this user agent. + * If none are configured or available, the callback will receive an empty array. + */ + function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Present a directory picker to the user and add the selected directory as a gallery. + * If the user cancels the picker, selectedFileSystemName will be empty. + * A user gesture is required for the dialog to display. + * Without a user gesture, the callback will run as though the user canceled. + * @since Since Chrome 34. + */ + function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void; + /** + * @deprecated Deprecated since Chrome 51. The user can manually drop access to galleries via the permissions dialog. + * @description Give up access to a given media gallery. + */ + function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Start a scan of the user's hard disks for directories containing media. + * The scan may take a long time so progress and completion is communicated by events. + * No permission is granted as a result of the scan, see addScanResults. + */ + function startMediaScan(): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Cancel any pending media scan. + * Well behaved apps should provide a way for the user to cancel scans they start. + */ + function cancelMediaScan(): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Show the user the scan results and let them add any or all of them as galleries. + * This should be used after the 'finish' onScanProgress() event has happened. + * All galleries the app has access to are returned, not just the newly added galleries. + */ + function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Get metadata about a specific media file system + * @since Since Chrome 26. + */ + function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata; + /** + * @deprecated Deprecated since Chrome 51. Use getMediaFileSystemMetadata instead + * Get metadata for all available media galleries. + */ + function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void; + /** + * Gets the media-specific metadata for a media file. + * This should work for files in media galleries as well as other DOM filesystems. + * @since Chrome 38. + */ + function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void; + /** + * Gets the media-specific metadata for a media file. + * This should work for files in media galleries as well as other DOM filesystems. + * @since Chrome 38. + */ + function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void; + /** + * Adds a gallery watch for the gallery with the specified gallery ID. + * The given callback is then fired with a success or failure result. + * @since Chrome 39. + */ + function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void; + /** + * Removes a gallery watch for the gallery with the specified gallery ID. + * @since Chrome 39. + */ + function removeGalleryWatch(galleryId: string): void; + /** + * @deprecated Deprecated since Chrome 51. Applications should store their own gallery watches as they are added. + * Notifies which galleries are being watched via the given callback. + */ + function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void; + /** + * @deprecated Deprecated since Chrome 51. Use removeGalleryWatch instead. + * Removes all gallery watches. + */ + function removeAllGalleryWatch(): void; + /** + * Fired when a media gallery is changed or a gallery watch is dropped + * @since Since Chrome 38. + */ + const onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * The pending media scan has changed state. See details for more information. + */ + const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } //////////////////////////////////// // Open Network Configuration (ONC) //////////////////////////////////// /** - * The chrome.networking.onc API is used for configuring network connections (Cellular, Ethernet, VPN, WiFi or WiMAX). This API is available in Chrome OS kiosk sessions. - * Network connection configurations are specified following Open Network Configuration (ONC) specification. - * NOTE: Most dictionary properties and enum values use UpperCamelCase to match the ONC specification instead of the JavaScript lowerCamelCase convention. + * @requires(CrOS kiosk mode) This API is available in Chrome OS kiosk sessions. + * @requires Permissions: 'networking.onc' + * @since Since Chrome 59 + * @description + * The chrome.networking.onc API is used for configuring network connections + * (Cellular, Ethernet, VPN, WiFi or WiMAX). + * Network connection configurations are specified following + * @see[Open Network Configuration (ONC) specification.]{@link https://chromium.googlesource.com/chromium/src/+/master/components/onc/docs/onc_spec.md} + * @description + * **NOTE** + * Most dictionary properties and type values use UpperCamelCase to match + * the ONC specification instead of the JavaScript lowerCamelCase convention. */ namespace networking.onc { - export type ActivationStateType = 'Activated' | 'Activating' | 'NotActivated' | 'PartiallyActivated'; - export type CaptivePortalStatus = 'Unknown' | 'Offline' | 'Online' | 'Portal' | 'ProxyAuthRequired'; - export type ConnectionStateType = 'Connected' | 'Connecting' | 'NotConnected'; - export type IPConfigType = 'DHCP' | 'Static'; - export type NetworkType = 'All' | 'Cellular' | 'Ethernet' | 'VPN' | 'Wireless' | 'WiFi' | 'WiMAX'; - export type ProxySettingsType = 'Direct' | 'Manual' | 'PAC' | 'WPAD'; - interface ManagedBoolean { - /** - * @description The active value currently used by the network configuration manager (e.g. Shill). - * @type {boolean} - * @memberof ManagedBoolean - */ - Active?: boolean, - /** - * @description The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedBoolean - */ - Effective?: string, - /** - * @description The property value provided by the user policy. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserPolicy?: boolean, - /** - * @description The property value provided by the device policy. - * @type {boolean} - * @memberof ManagedBoolean - */ - DevicePolicy?: boolean, - /** - * @description The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserSettings?: boolean, - /** - * @description The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {boolean} - * @memberof ManagedBoolean - */ - SharedSettings?: boolean, - /** - * @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserEditable?: boolean, - /** - * @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedBoolean - */ - DeviceEditable?: boolean + type ActivationStateType = 'Activated' | 'Activating' | 'NotActivated' | 'PartiallyActivated'; + type CaptivePortalStatus = 'Unknown' | 'Offline' | 'Online' | 'Portal' | 'ProxyAuthRequired'; + type ConnectionStateType = 'Connected' | 'Connecting' | 'NotConnected' + type IPConfigType = 'DHCP' | 'Static' + type NetworkType = 'All' | 'Cellular' | 'Ethernet' | 'VPN' | 'Wireless' | 'WiFi' | 'WiMAX' + type ProxySettingsType = 'Direct' | 'Manual' | 'PAC' | 'WPAD'; + /** + * Partial classes for internal use + * @internal + * @private + */ + namespace _internal_ { + type ObjectFunction = 'unknown' | 'getter' | 'setter'; + interface NetworkConfigBase< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full', + OF extends ObjectFunction = 'unknown'> { + /** For cellular networks, cellular network properties. */ + Cellular?: IF extends 'partial' ? CellularBase : CellularProperties; + /** For Ethernet networks, the Ethernet network properties. */ + Ethernet?: IF extends 'partial' ? { Authentication: string; } : EthernetProperties; + /** The network GUID. */ + GUID?: string; + /** The network's IP address configuration type. */ + IPAddressConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + /** A user friendly network name. */ + Name?: M extends 'managed' ? ManagedDOMString : string; + /** The IP configuration type for the name servers used by the network. */ + NameServersConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + /** The network priority. */ + Priority?: M extends 'managed' ? ManagedLong : integer; + /** The network type. */ + Type?: NetworkType; + /** For VPN networks, the network VPN properties. */ + VPN?: IF extends 'partial' ? { Type: string; } : VPNProperties; + /** For WiFi networks, the network WiFi properties. */ + WiFi?: IF extends 'partial' ? WiFiPropertiesBase : WiFiProperties; + /** For WiMAX networks, the network WiMAX properties. */ + WiMAX?: IF extends 'partial' ? { SignalStrength?: integer } : WiMAXProperties; + } } - interface ManagedLong { + interface ManagedType { + /** The active value currently used by the network configuration manager (e.g. Shill). */ + Active?: T; + /** The source from which the effective property value was determined. */ + Effective?: string; + /** The property value provided by the user policy. */ + UserPolicy?: T; + /** The property value provided by the device policy. */ + DevicePolicy?: T; + /** The property value set by the logged in user. Only provided if *UserEditable* is true. */ + UserSetting?: T; + /** The value set for all users of the device. Only provided if *DeviceEditiable* is true. */ + SharedSetting?: T; /** - * @description The active value currently used by the network configuration manager (e.g. Shill). - * @type {number} - * @memberof ManagedLong + * Whether a UserPolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). + * @default false */ - Active?: number, + UserEditable?: boolean; /** - * @description The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedLong + * Whether a DevicePolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). + * @default false */ - Effective?: string, - /** - * @description The property value provided by the user policy. - * @type {number} - * @memberof ManagedLong - */ - UserPolicy?: number, - /** - * @description The property value provided by the device policy. - * @type {number} - * @memberof ManagedLong - */ - DevicePolicy?: number, - /** - * @description The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {number} - * @memberof ManagedLong - */ - UserSettings?: number, - /** - * @description The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {number} - * @memberof ManagedLong - */ - SharedSettings?: number, - /** - * @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedLong - */ - UserEditable?: boolean, - /** - * @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedLong - */ - DeviceEditable?: boolean + DeviceEditable?: boolean; } + interface ManagedBoolean extends ManagedType { } + interface ManagedLong extends ManagedType { } + interface ManagedDOMString extends ManagedType { } + interface ManagedDOMStringList extends ManagedType { } + interface ManagedIPConfigType extends ManagedType { } + + interface CellularProviderProperties { + /** The operator name. */ + Name: string; + /** Cellular network ID as a simple concatenation of the network's MCC (Mobile Country Code) and MNC (Mobile Network Code). */ + Code: string; + /** The two-letter country code. */ + Country?: string; + } + interface IssuerSubjectPattern { + /** If set, the value against which to match the certificate subject's common name. */ + CommonName?: string; + /** If set, the value against which to match the certificate subject's common location. */ + Locality?: string; + /** + * If set, the value against which to match the certificate subject's organizations. + * At least one organization should match the value. + */ + Organization?: string; + /** + * If set, the value against which to match the certificate subject's organizational units. + * At least one organizational unit should match the value. + */ + OrganizationalUnit?: string; + } + interface CertPattern { + /** + * List of URIs to which the user can be directed in case + * no certificates that match this pattern are found. + */ + EnrollmentURI?: string[]; + /** + * If set, pattern against which X.509 issuer settings should be matched. + */ + Issuer?: IssuerSubjectPattern; + /** + * List of certificate issuer CA certificates. + * A certificate must be signed by one of them in order to match this pattern. + */ + IssuerCARef?: string[]; + /** + * If set, pattern against which X.509 subject settings should be matched. + */ + IssuerSubjectPattern?: IssuerSubjectPattern; + } + type ClientCertType = 'Ref' | 'Pattern'; + interface EAPProperties { + AnonymousIdentity?: string; + ClientCertPattern?: CertPattern; + /** @since Chrome 60. */ + ClientCertPKCS11Id?: string; + ClientCertRef?: string; + ClientCertType?: ClientCertType; + Identity?: string; + Inner?: string; + /** The outer EAP type. Required by ONC, but may not be provided when translating from Shill. */ + Outer?: string; + Password?: string; + SaveCredentials?: boolean; + ServerCAPEMs?: string[]; + ServerCARefs?: string[]; + /** @since Chrome 60. */ + SubjectMatch?: ManagedDOMString; + UseProactiveKeyCaching?: boolean; + UseSytemCAs?: boolean; + } + interface FoundNetworkProperties { + /** Network availability. */ + Status: string; + /** Network ID. */ + NetworkId: string; + /** Access technology used by the network. */ + Technology: string; + /** The network operator's short-format name. */ + ShortName?: string; + /** The network operator's long-format name. */ + LongName?: string; + } + type IPConfigurationType = 'IPv4' | 'IPv6'; + interface IPConfigProperties { + /** Gateway address used for the IP configuration. */ + Gateway?: S; + /** The IP address for a connection. Can be IPv4 or IPv6 address, depending on value of Type. */ + IPAddress?: S; + /** Array of addresses used for name servers. */ + NameServers?: SL; + /** The routing prefix. */ + RoutingPrefix?: L; + /** The IP configuration type. Can be IPv4 or IPv6. */ + Type?: M extends 'managed' ? ManagedType : IPConfigurationType; + /** The URL for WEb Proxy Auto-Discovery, as reported over DHCP. */ + WebProxyAutoDiscoveryUrl?: S; + } + interface PaymentPortalPost { + /** The HTTP method to use for the payment portal. */ + Method: 'POST'; + /** The post data to send to the payment portal. */ + PostData?: string; + /** The payment portal URL. */ + Url?: string; + } + interface PaymentPortal { + /** The HTTP method to use for the payment portal. */ + Method: string; + /** The payment portal URL. */ + Url?: string; + } + interface ProxyLocation { + /** The proxy IP address host. */ + Host?: string; + /** The port to use for the proxy */ + Port?: integer; + } + interface ManagedProxyLocation { + /** The proxy IP address host. */ + Host?: ManagedDOMString; + /** The port to use for the proxy */ + Port?: ManagedLong; + } + interface ManualProxySettings { + /** Settings for HTTP proxy. */ + HTTPProxy?: P; + /** Settings for secure HTTP proxy. */ + SecureHTTPProxy?: P; + /** Settings for FTP proxy. */ + FTPProxy?: P; + /** Settings for SOCKS proxy. */ + SOCKS?: P; + } + interface ProxySettings { + /** The type of proxy settings. */ + Type: M extends 'managed' ? ManagedType : ProxySettingsType; + /** Manual proxy settings - used only for *Manual* proxy settings. */ + Manual?: ManualProxySettings; + /** Domains and hosts for which manual proxy settings are excluded. */ + ExcludeDomains?: SL; + /** URL for proxy auto-configuration file. */ + PAC?: S; + } + interface SIMLockStatus { + /** The status of SIM lock - possible values are 'sim-pin', 'sim-puk' and ''. */ + LockType: 'sim-pin' | 'sim-puk' | ''; + /** Whether SIM lock is enabled. */ + LockEnabled: boolean; + /** Number of PIN lock tries allowed before PUK is required to unlock the SIM. */ + RetriesLeft?: integer; + } + interface ThirdPartyVPNProperties { + /** ID of the third-party VPN provider extension. */ + ExtensionID: string; + /** The VPN provider name. */ + ProviderName?: string; + } + interface ManagedThirdPartyVPNProperties { + /** ID of the third-party VPN provider extension. */ + ExtensionID: ManagedDOMString; + /** The VPN provider name. */ + ProviderName?: string; + } + interface CellularBase { + /** Carrier account activation state. */ + ActivationState?: ActivationStateType; + /** If the modem is registered on a network, the network technology currently in use. */ + NetworkTechnology?: string; + /** The roaming state of the cellular modem on the current network. */ + RoamingState?: string; + /** Whether a SIM card is present. */ + SIMPresent?: boolean; + /** The current network signal strength. */ + SignalStrength?: integer; + } + interface CellularProperties extends CellularBase { + /** Whether the cellular network should be connected automatically (when in range). */ + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + /** The cellular network activation type. */ + ActivationType?: string; + /** Whether roaming is allowed for the network. */ + AllowRoaming?: boolean; + /** The name of the carrier for which the cellular device is configured. */ + Carrier?: M extends 'managed' ? ManagedDOMString : string; + /** Cellular device technology family - CDMA or GSM. */ + Family?: 'CDMA' | 'GSM'; + /** The firmware revision loaded in the cellular modem. */ + FirmwareRevision?: string; + /** The list of networks found during the most recent network scan. */ + FoundNetworks?: FoundNetworkProperties[]; + /** The cellular modem hardware revision. */ + HardwareRevision?: string; + /** Information about the operator that issued the SIM card currently installed in the modem. */ + HomeProvider?: CellularProviderProperties; + /** The cellular modem manufacturer. */ + MAnufacturer?: string; + /** The cellular modem model ID. */ + ModelID?: string; + /** Online payment portal a user can use to sign-up for or modify a mobile data plan. */ + PaymentPortal?: PaymentPortal | PaymentPortalPost; + /** The revision of the Preferred Roaming List loaded in the modem. */ + PRLVersion?: integer; + /** + * @since Chrome 63. + * True when a cellular network scan is in progress. + */ + Scanning?: boolean; + /** Information about the operator on whose network the modem is currently registered. */ + ServingOperator?: CellularProviderProperties; + /** The state of SIM lock for GSM family networks. */ + SIMLockStatus?: SIMLockStatus; + /** Whether the cellular network supports scanning. */ + SupportNetworkScan?: boolean; + /** A list of supported carriers. */ + SupportedCarriers?: string[]; + } + type EthernetAuthenticationType = 'None' | '8021X'; + interface EthernetProperties { + /** Whether the Ethernet network should be connected automatically. */ + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + /** The authentication used by the Ethernet network. Possible values are None and 8021X. */ + Authentication?: M extends 'managed' ? ManagedType : EthernetAuthenticationType; + /** Network's EAP settings. Required for 8021X authentication. */ + EAP?: EAPProperties; + } + interface VPNProperties { + /** Whether the VPN network should be connected automatically. */ + AutoConnect?: B; + /** The VPN host. */ + Host?: S; + /** + * The VPN type. + * This cannot be an enum because of 'L2TP-IPSec'. + * This is optional for NetworkConfigProperties which is passed to + * *setProperties* which may be used to set only specific properties. + */ + Type?: S; + } + interface WiFiPropertiesBase { + /** The BSSID of the associated access point.. */ + BSSID?: string; + /** + * The WiFi service operating frequency in MHz. + * For connected networks, the current frequency on which the network is connected. + * Otherwise, the frequency of the best available BSS. + */ + Frequency?: integer; + /** HEX-encoded copy of the network SSID. */ + HexSSID?: S; + /** The network security type. */ + Security?: S; + /** The network SSID. */ + SSID?: S; + /** The network signal strength. */ + SignalStrength?: integer; + } + interface WiFiProperties + extends WiFiPropertiesBase { + /** + * Whether ARP polling of default gateway is allowed. + * @default true + */ + AllowGatewayARPPolling?: B; + /** Whether the WiFi network should be connected automatically when in range. */ + AutoConnect?: B; + /** The network EAP properties. Required for WEP-8021X and WPA-EAP networks. */ + EAP?: EAPProperties; + /** Contains all operating frequency recently seen for the WiFi network. */ + FrequencyList?: integer[]; + /** Whether the network SSID will be broadcast. */ + HiddenSSID?: B; + /** Signal-to-noise value (in dB) below which roaming to a new network should be attempted. */ + RoamTreshold?: L; + /** + * @since Chrome 66. + * The passphrase for WEP/WPA/WPA2 connections. + * *This property can only be set!* + */ + Passphrase?: OF extends 'setter' ? string : never; + } + interface WiMAXProperties { + /** Whether the network should be connected automatically. */ + AutoConnect?: B; + /** The network EAP properties. */ + EAP?: EAPProperties; + /** The network signal strength. */ + SignalStrength?: integer; + } + type ManagedObject = 'managed' | 'unmanaged'; + type InterfaceType = 'partial' | 'full'; + + interface NetworkConfigProperties + extends _internal_.NetworkConfigBase<'unmanaged', 'full', OF> { } + + interface NetworkProperties< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full'> extends _internal_.NetworkConfigBase { + /** Whether the network is connectable. */ + Connectable?: boolean; + /** The network's current connection state. */ + ConnectionState?: ConnectionStateType; + /** The last recorded network error state. */ + ErrorState?: string; + /** The network's IP configuration. */ + IPConfigs?: IPConfigProperties[]; + /** The network's MAC address. */ + MacAddress?: string; + /** The network's proxy settings. */ + ProxySettings?: ProxySettings; + /** + * For a connected network, whether the network connectivity to the Internet is limited, + * e.g. if the network is behind a portal, or a cellular network is not activated. + */ + RestrictedConnectivity?: boolean; + /** The network's static IP configuration. */ + StaticIPConfig?: IPConfigProperties; + /** IP configuration that was received from the DHCP server before applying static IP configuration. */ + SavedIPConfig?: IPConfigProperties; + /** + * Indicates whether and how the network is configured. + * 'None' conflicts with extension code generation, + * so we must use a string for 'Source' instead of a SourceType enum. + */ + Source?: 'Device' | 'DevicePolicy' | 'User' | 'UserPolicy' | 'None'; + } + interface ManagedProperties extends NetworkProperties<'managed'> { } + interface NetworkStateProperties extends NetworkProperties<'unmanaged', 'partial'> { } + + /** Describes which networks to return. */ + interface Filter { + /** The type of networks to return. */ + networkType: NetworkType; + /** + * If true, only include visible (physically connected or in-range) networks. + * @default false + */ + visible?: boolean; + /** + * If true, only include configured (saved) networks. + * @default false + */ + configured?: boolean; + /** + * Maximum number of networks to return. + * Use 0 for no limit + * @default 1000 if unspecified. + * */ + limit?: integer; + } + + /* The current state of the device. */ + type DeviceState = 'Uninitialized' | 'Disabled' | 'Enabling' | 'Enabled' | 'Prohibited'; + + /** A list of devices and their state. */ + interface DeviceStates { + /** Set if the device is enabled. True if the device is currently scanning. */ + Scanning?: boolean; + /** The SIM lock status if Type = Cellular and SIMPresent = True. */ + SIMLockStatus?: SIMLockStatus; + /** Set to the SIM present state if the device type is Cellular. */ + SIMPresent?: boolean; + /** + * The current state of the device. + * + * **Uninitialized** + * - Device is available but not initialized. + * **Disabled** + * - Device is initialized but not enabled. + * **Enabling** + * - Enabled state has been requested but has not completed. + * **Enabled** + * - Device is enabled. + * **Prohibited** + * - Device is prohibited. + */ + State: DeviceState; + /** The network type associated with the device (Cellular, Ethernet, WiFi, or WiMAX). */ + Type: NetworkType; + } + + interface GlobalPolicy { + /** + * If true, only policy networks may auto connect. + * @default false + */ + AllowOnlyPolicyNetworksToAutoconnect?: boolean; + /** + * If true, only policy networks may be connected to + * and no new networks may be added or configured. + * @default false + */ + AllowOnlyPolicyNetworksToConnect?: boolean; + /** + * List of blacklisted networks. + * Connections to blacklisted networks are prohibited. + * Networks can be whitelisted again by specifying an explicit network configuration. + * @default [] + */ + BlacklistedHexSSIDs?: string[]; + } + + /** + * Gets all the properties of the network with id *networkGuid*. + * Includes all properties of the network (read-only and read/write values). + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called with the network properties when received. + */ + function getProperties(networkGuid: string, callback: (result: NetworkProperties) => void): void; + /** + * Gets the merged properties of the network with id networkGuid from the sources: + * User settings, shared settings, user policy, device policy and the currently active settings. + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called with the managed network properties when received. + */ + function getManagedProperties(networkGuid: string, callback: (result: ManagedProperties) => void): void; + /** + * Gets the cached read-only properties of the network with id *networkGuid*. + * This is meant to be a higher performance function than *getProperties*, + * which requires a round trip to query the networking subsystem. + * The following properties are returned for all networks: + * GUID, Type, Name, WiFi.Security. + * Additional properties are provided for visible networks: + * ConnectionState, ErrorState, WiFi.SignalStrength, + * Cellular.NetworkTechnology, Cellular.ActivationState, Cellular.RoamingState. + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called immediately with the network state properties. + */ + function getState(networkGuid: string, callback: (result: NetworkStateProperties) => void): void; + /** + * Sets the properties of the network with id *networkGuid*. + * This is only valid for configured networks (Source != None). + * Unconfigured visible networks should use **createNetwork** instead. + * **In kiosk sessions, calling this method on a shared network will fail.** + * @param networkGuid The GUID of the network to set properties for. + * @param properties The properties to set. + * @param [callback] Called when the operation has completed. + */ + function setProperties(networkGuid: string, properties: NetworkConfigProperties<'setter'>, callback?: () => void): void; + /** + * Creates a new network configuration from properties. + * If a matching configured network already exists, this will fail. + * Otherwise returns the GUID of the new network. + * @param shared If true, share this network configuration with other users. + * Note: This option is exposed only to Chrome's Web UI. + * When called by apps, false is the only allowed value. + * @param properties The properties to configure the new network with. + * @param [callback] Called with the GUID for the new network configuration once the network has been created. + */ + function createNetwork(shared: false, properties: NetworkConfigProperties<'setter'>, callback?: () => void): void; + /** + * Forgets a network configuration by clearing any configured properties for the network with GUID networkGuid. + * This may also include any other networks with matching identifiers (e.g. WiFi SSID and Security). + * If no such configuration exists, an error will be set and the operation will fail. + * **In kiosk sessions, this method will not be able to forget shared network configurations.** + * @param networkGuid The GUID of the network to forget. + * @param [callback] Called when the operation has completed. + */ + function forgetNetwork(networkGuid: string, callback?: () => void): void; + /** + * Returns a list of network objects with the same properties provided by *getState*. + * A filter is provided to specify the type of networks returned and to limit the number of networks. + * Networks are ordered by the system based on their priority, with connected or connecting networks listed first. + * @param callback Called with a dictionary of networks and their state properties when received. + */ + function getNetworks(filter: Filter, callback: (result: NetworkStateProperties[]) => void): void; + /** + * Returns states of available networking devices. + * @param callback Called with a list of devices and their state. + */ + function getDeviceStates(callback: (result: DeviceStates[]) => void): void; + /** + * Enables any devices matching the specified network type. + * Note, the type might represent multiple network types (e.g. 'Wireless'). + * @param networkType The type of network to enable. + */ + function enableNetworkType(networkType: NetworkType): void; + /** + * Disables any devices matching the specified network type. + * Note, the type might represent multiple network types (e.g. 'Wireless'). + * @param networkType The type of network to disable. + */ + function disableNetworkType(networkType: NetworkType): void; + /** + * Requests that the networking subsystem scan for new networks and update the list returned by *getVisibleNetworks*. + * This is only a request: the network subsystem can choose to ignore it. + * If the list is updated, then the *onNetworkListChanged* event will be fired. + */ + function requestNetworkScan(): void; + /** + * Requests that the networking subsystem scan for new networks and update the list returned by *getVisibleNetworks*. + * This is only a request: the network subsystem can choose to ignore it. + * If the list is updated, then the *onNetworkListChanged* event will be fired. + * @param networkType If provided, requests a scan specific to the type. For Cellular a mobile network scan will be requested if supported. + * @since Chrome 63. + */ + function requestNetworkScan(networkType: NetworkType): void; + /** + * @description Starts a connection to the network with networkGuid. + * @param networkGuid The GUID of the network to connect to. + * @param [callback] Creates a new network configuration from properties. + * If a matching configured network already exists, this will fail. + * Otherwise returns the GUID of the new network. + */ + function startConnect(networkGuid: string, callback?: () => void): void; + /** + * @description Starts a disconnect from the network with networkGuid. + * @param networkGuid The GUID of the network to connect to. + * @param [callback] Called when the disconnect request has been sent. See note for *startConnect*. + */ + function startDisconnect(networkGuid: string, callback?: () => void): void; + /** + * Returns captive portal status for the network matching 'networkGuid'. + * @param networkGuid The GUID of the network to get captive portal status for. + * @param callback A callback function that returns the results of the query for network captive portal status. + */ + function getCaptivePortalStatus(networkGuid: string, callback: (result: CaptivePortalStatus) => void): void; + /** + * Gets the global policy properties. + * These properties are not expected to change during a session. + */ + function getGlobalPolicy(callback: (result: GlobalPolicy) => void): void; + + // + // EVENTS + // + + /** + * Fired when the properties change on any of the networks. + * Sends a list of GUIDs for networks whose properties have changed. + */ + const onNetworksChanged: chrome.events.Event<(changes: string[]) => void>; + /** + * Fired when the list of networks has changed. Sends a complete list of GUIDs for all the current networks. + */ + const onNetworkListChanged: chrome.events.Event<(changes: string[]) => void>; + /** + * Fired when the list of devices has changed or any device state properties have changed. + */ + const onDeviceStateListChanged: chrome.events.Event<() => void>; + /** + * Fired when a portal detection for a network completes. + * Sends the GUID of the network and the corresponding captive portal status. + */ + const onPortalDetectionCompleted: chrome.events.Event<(networkGuid: string, status: CaptivePortalStatus) => void>; } - //////////////////// - // Notifications - // https://developer.chrome.com/extensions/notifications - //////////////////// + /////////////////// + // Notifications // + /////////////////// /** - * Use the chrome.notifications API to create rich notifications using templates and show these notifications to users in the system tray. - * Permissions: 'notifications' + * Use the chrome.notifications API to create rich notifications using + * templates and show these notifications to users in the system tray. + * @requires Permissions: 'notifications' * @since Chrome 28. + * @see[Docs]{@link https://developer.chrome.com/extensions/notifications} */ namespace notifications { interface ButtonOptions { @@ -2970,7 +5491,7 @@ declare namespace chrome { } interface NotificationOptions { - /** Optional. Which type of notification to display. Required for notifications.create method. */ + /** Which type of notification to display. Required for notifications.create method. */ type?: string; /** * Optional. @@ -2978,9 +5499,9 @@ declare namespace chrome { * URLs can be a data URL, a blob URL, or a URL relative to a resource within this extension's .crx file Required for notifications.create method. */ iconUrl?: string; - /** Optional. Title of the notification (e.g. sender name for email). Required for notifications.create method. */ + /** Title of the notification (e.g. sender name for email). Required for notifications.create method. */ title?: string; - /** Optional. Main notification content. Required for notifications.create method. */ + /** Main notification content. Required for notifications.create method. */ message?: string; /** * Optional. @@ -2988,13 +5509,13 @@ declare namespace chrome { * @since Chrome 31. */ contextMessage?: string; - /** Optional. Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ + /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number; - /** Optional. A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ + /** A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ eventTime?: number; - /** Optional. Text and icons for up to two notification action buttons. */ + /** Text and icons for up to two notification action buttons. */ buttons?: ButtonOptions[]; - /** Optional. Items for multi-item notifications. */ + /** Items for multi-item notifications. */ items?: ItemOptions[]; /** * Optional. @@ -3014,7 +5535,7 @@ declare namespace chrome { * @since Chrome 38. */ appIconMaskUrl?: string; - /** Optional. A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */ + /** A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */ imageUrl?: string; /** * Indicates that the notification should remain visible on screen until the user activates or dismisses the notification. @@ -3035,21 +5556,21 @@ declare namespace chrome { interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> { } /** The notification closed, either by the system or by user action. */ - export var onClosed: NotificationClosedEvent; + const onClosed: NotificationClosedEvent; /** The user clicked in a non-button area of the notification. */ - export var onClicked: NotificationClickedEvent; + const onClicked: NotificationClickedEvent; /** The user pressed a button in the notification. */ - export var onButtonClicked: NotificationButtonClickedEvent; + const onButtonClicked: NotificationButtonClickedEvent; /** * The user changes the permission level. * @since Chrome 32. */ - export var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; + const onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; /** * The user clicked on a link for the app's notification settings. * @since Chrome 32. */ - export var onShowSettings: NotificationShowSettingsEvent; + const onShowSettings: NotificationShowSettingsEvent; /** * Creates and displays a notification. @@ -3061,7 +5582,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ - export function create(notificationId: string, options: NotificationOptions, callback?: (notificationId: string) => void): void; + function create(notificationId: string, options: NotificationOptions, callback?: (notificationId: string) => void): void; /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. @@ -3072,7 +5593,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ - export function create(options: NotificationOptions, callback?: (notificationId: string) => void): void; + function create(options: NotificationOptions, callback?: (notificationId: string) => void): void; /** * Updates an existing notification. * @param notificationId The id of the notification to be updated. This is returned by notifications.create method. @@ -3082,7 +5603,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasUpdated) {...}; */ - export function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; + function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; /** * Clears the specified notification. * @param notificationId The id of the notification to be cleared. This is returned by notifications.create method. @@ -3091,7 +5612,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ - export function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; + function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; /** * Retrieves all the notifications. * @since Chrome 29. @@ -3099,7 +5620,7 @@ declare namespace chrome { * The callback parameter should be a function that looks like this: * function(object notifications) {...}; */ - export function getAll(callback: (notifications: Object) => void): void; + function getAll(callback: (notifications: Object) => void): void; /** * Retrieves whether the user has enabled notifications from this app or extension. * @since Chrome 32. @@ -3107,7 +5628,7 @@ declare namespace chrome { * The callback parameter should be a function that looks like this: * function( PermissionLevel level) {...}; */ - export function getPermissionLevel(callback: (level: string) => void): void; + function getPermissionLevel(callback: (level: string) => void): void; } //////////////////// @@ -3155,33 +5676,33 @@ declare namespace chrome { * function(boolean result) {...}; * Parameter result: True if the extension has the specified permissions. */ - export function contains(permissions: Permissions, callback: (result: boolean) => void): void; + function contains(permissions: Permissions, callback: (result: boolean) => void): void; /** * Gets the extension's current set of permissions. * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The extension's active permissions. */ - export function getAll(callback: (permissions: Permissions) => void): void; + function getAll(callback: (permissions: Permissions) => void): void; /** * Requests access to the specified permissions. These permissions must be defined in the optional_permissions field of the manifest. If there are any problems requesting the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * function(boolean granted) {...}; * Parameter granted: True if the user granted the specified permissions. */ - export function request(permissions: Permissions, callback?: (granted: boolean) => void): void; + function request(permissions: Permissions, callback?: (granted: boolean) => void): void; /** * Removes access to the specified permissions. If there are any problems removing the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * function(boolean removed) {...}; * Parameter removed: True if the permissions were removed. */ - export function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; + function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; /** Fired when access to permissions has been removed from the extension. */ - export var onRemoved: PermissionsRemovedEvent; + const onRemoved: PermissionsRemovedEvent; /** Fired when the extension acquires new permissions. */ - export var onAdded: PermissionsAddedEvent; + const onAdded: PermissionsAddedEvent; } //////////////////// @@ -3194,9 +5715,9 @@ declare namespace chrome { */ namespace power { /** Requests that power management be temporarily disabled. |level| describes the degree to which power management should be disabled. If a request previously made by the same app is still active, it will be replaced by the new request. */ - export function requestKeepAwake(level: string): void; + function requestKeepAwake(level: string): void; /** Releases a request previously made via requestKeepAwake(). */ - export function releaseKeepAwake(): void; + function releaseKeepAwake(): void; } //////////////////// @@ -3213,7 +5734,7 @@ declare namespace chrome { id: string; /** Printer's human readable name. */ name: string; - /** Optional. Printer's human readable description. */ + /** Printer's human readable description. */ description?: string; } @@ -3235,26 +5756,18 @@ declare namespace chrome { document: Blob; } - interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> { } - - interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> { } - - interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void> { } - - interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> { } - /** Event fired when print manager requests printers provided by extensions. */ - export var onGetPrintersRequested: PrinterRequestedEvent; + const onGetPrintersRequested: chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void>; /** * Event fired when print manager requests information about a USB device that may be a printer. * Note: An application should not rely on this event being fired more than once per device. If a connected device is supported it should be returned in the onGetPrintersRequested event. * @since Chrome 45. */ - export var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; + const onGetUsbPrinterInfoRequested: chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void>; /** Event fired when print manager requests printer capabilities. */ - export var onGetCapabilityRequested: CapabilityRequestedEvent; + const onGetCapabilityRequested: chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void>; /** Event fired when print manager requests printing. */ - export var onPrintRequested: PrintRequestedEvent; + const onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; } //////////////////// @@ -3266,12 +5779,12 @@ declare namespace chrome { */ namespace runtime { /** This will be defined during an API method callback if there was an error */ - export var lastError: LastError | undefined; + const lastError: LastError | undefined; /** The ID of the extension/app. */ - export var id: string; + const id: string; interface LastError { - /** Optional. Details about the error which occurred. */ + /** Details about the error which occurred. */ message?: string; } @@ -3362,9 +5875,9 @@ declare namespace chrome { */ sender?: MessageSender; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onDisconnect: PortDisconnectEvent; + onDisconnect: chrome.events.Event<(port: Port) => void>; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onMessage: PortMessageEvent; + onMessage: chrome.events.Event<(message: any, port: Port) => void>; name: string; } @@ -3378,22 +5891,6 @@ declare namespace chrome { version: string; } - interface PortDisconnectEvent extends chrome.events.Event<(port: Port) => void> { } - - interface PortMessageEvent extends chrome.events.Event<(message: any, port: Port) => void> { } - - interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } - - interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { } - - interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> { } - - interface RuntimeEvent extends chrome.events.Event<() => void> { } - - interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> { } - - interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> { } - interface ManifestIcons { [size: number]: string; } @@ -3422,6 +5919,63 @@ declare namespace chrome { is_default?: boolean; } + type Permissions = + 'alarms' | + 'audio' | + 'audioCapture' | + 'background' | + 'browser' | + 'certificateProvider' | + 'clipboard' | + 'clipboardRead' | + 'clipboardWrite' | + 'contextMenus' | + 'desktopCapture' | + 'diagnostics' | + 'displaySource' | + 'dns' | + 'documentScan' | + 'enterprise.deviceAttributes' | + 'enterprise.platformKeys' | + 'experimental' | + 'fileBrowserHandler' | + 'fileSystem' | + 'gcm' | + 'geolocation' | + 'hid' | + 'identity' | + 'idle' | + 'mdns' | + 'mediaGalleries' | + 'nativeMessaging' | + 'networking.config' | + 'networking.onc' | + 'notifications' | + 'platformKeys' | + 'pointerLock' | + 'power' | + 'printerProvider' | + 'proxy' | + 'serial' | + 'signedInDevices' | + 'socket' | + 'storage' | + 'syncFileSystem' | + 'system.cpu' | + 'system.display' | + 'system.memory' | + 'system.network' | + 'system.powerSource' | + 'system.storage' | + 'tts' | + 'unlimitedStorage' | + 'usb' | + 'videoCapture' | + 'virtualKeyboard' | + 'vpnProvider' | + 'wallpaper' | + 'webview'; + interface Manifest { /** Required */ app: { @@ -3546,6 +6100,15 @@ declare namespace chrome { pages: string[]; content_security_policy?: string; }; + /** + * The short_name (maximum of 12 characters recommended) is + * a short version of the app's name. It is an optional field + * and if not specified, the name will be used, though it will + * likely be truncated. The short name is typically used where + * there is insufficient space to display the full name, such as: + * - App launcher + * - New Tab page + */ short_name?: string; signature?: any; sockets?: { @@ -3560,7 +6123,7 @@ declare namespace chrome { managed_schema: string }; system_indicator?: any; - update_url?: string; + // update_url?: string; // Listed but deprecated since Chrome 33 - leaving it here so it's not added again url_handlers?: { [name: string]: { matches: string[]; @@ -3590,48 +6153,60 @@ declare namespace chrome { * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. * @since Chrome 26. */ - export function connect(connectInfo?: ConnectInfo): Port; + function connect(connectInfo?: ConnectInfo): Port; /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. * @since Chrome 26. * @param extensionId Optional. * The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for web messaging. */ - export function connect(extensionId: string, connectInfo?: ConnectInfo): Port; + function connect(extensionId: string, connectInfo?: ConnectInfo): Port; /** * Connects to a native application in the host machine. * @since Chrome 28. * @param application The name of the registered application to connect to. */ - export function connectNative(application: string): Port; - /** Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set. */ - export function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; + function connectNative(application: string): Port; + /** - * Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file. + * Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. + * If the background page is an event page, the system will ensure it is loaded before calling the callback. + * If there is no background page, an error is set. + */ + function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; + + /** + * Returns details about the app or extension from the manifest. + * The object returned is a serialization of the full manifest file. * @returns The manifest details. */ - export function getManifest(): Manifest; + function getManifest(): Manifest; + /** * Returns a DirectoryEntry for the package directory. * @since Chrome 29. */ - export function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; + function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; + /** * Returns information about the current platform. * @since Chrome 29. * @param callback Called with results */ - export function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; + function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; + /** * Converts a relative path within an app/extension install directory to a fully-qualified URL. * @param path A path to a resource within an app/extension expressed relative to its install directory. */ - export function getURL(path: string): string; + function getURL(path: string): string; + /** * Reloads the app or extension. * @since Chrome 25. */ - export function reload(): void; + function reload(): void; + /** * Requests an update check for this app/extension. * @since Chrome 25. @@ -3639,26 +6214,30 @@ declare namespace chrome { * Parameter status: Result of the update check. One of: 'throttled', 'no_update', or 'update_available' * Optional parameter details: If an update is available, this contains more information about the available update. */ - export function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + /** * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op. * @since Chrome 32. */ - export function restart(): void; + function restart(): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26. * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(message: any, responseCallback?: (response: any) => void): void; + function sendMessage(message: any, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32. * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26. @@ -3666,7 +6245,8 @@ declare namespace chrome { * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32. @@ -3674,7 +6254,8 @@ declare namespace chrome { * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + /** * Send a single message to a native application. * @since Chrome 28. @@ -3683,7 +6264,8 @@ declare namespace chrome { * @param responseCallback Optional. * Parameter response: The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendNativeMessage(application: string, message: Object, responseCallback?: (response: any) => void): void; + function sendNativeMessage(application: string, message: Object, responseCallback?: (response: any) => void): void; + /** * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters. * @since Chrome 41. @@ -3691,73 +6273,82 @@ declare namespace chrome { * URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation. * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set. */ - export function setUninstallURL(url: string, callback?: () => void): void; + function setUninstallURL(url: string, callback?: () => void): void; + /** * Open your Extension's options page, if possible. * The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload. * If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError. * @since Chrome 42. */ - export function openOptionsPage(callback?: () => void): void; + function openOptionsPage(callback?: () => void): void; + + + interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } + + interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { } + + interface RuntimeEvent extends chrome.events.Event<() => void> { } /** * Fired when a connection is made from either an extension process or a content script. * @since Chrome 26. */ - export var onConnect: ExtensionConnectEvent; + const onConnect: ExtensionConnectEvent; /** * Fired when a connection is made from another extension. * @since Chrome 26. */ - export var onConnectExternal: ExtensionConnectEvent; + const onConnectExternal: ExtensionConnectEvent; /** Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. */ - export var onSuspend: RuntimeEvent; + const onSuspend: RuntimeEvent; /** * Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode. * @since Chrome 23. */ - export var onStartup: RuntimeEvent; + const onStartup: RuntimeEvent; /** Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version. */ - export var onInstalled: RuntimeInstalledEvent; + const onInstalled: chrome.events.Event<(details: InstalledDetails) => void>; /** Sent after onSuspend to indicate that the app won't be unloaded after all. */ - export var onSuspendCanceled: RuntimeEvent; + const onSuspendCanceled: RuntimeEvent; /** * Fired when a message is sent from either an extension process or a content script. * @since Chrome 26. */ - export var onMessage: ExtensionMessageEvent; + const onMessage: ExtensionMessageEvent; /** * Fired when a message is sent from another extension/app. Cannot be used in a content script. * @since Chrome 26. */ - export var onMessageExternal: ExtensionMessageEvent; + const onMessageExternal: ExtensionMessageEvent; /** * Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps. * @since Chrome 29. */ - export var onRestartRequired: RuntimeRestartRequiredEvent; + const onRestartRequired: chrome.events.Event<(reason: string) => void>; /** * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event. * @since Chrome 25. */ - export var onUpdateAvailable: RuntimeUpdateAvailableEvent; + const onUpdateAvailable: chrome.events.Event<(details: UpdateAvailableDetails) => void>; /** * @deprecated since Chrome 33. Please use chrome.runtime.onRestartRequired. * Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required. */ - export var onBrowserUpdateAvailable: RuntimeEvent; + const onBrowserUpdateAvailable: RuntimeEvent; } //////////////////// // Serial //////////////////// /** - * Use the chrome.serial API to read from and write to a device connected to a serial port. + * Use the chrome.socket API to send and receive data over the network using TCP and UDP connections. + * @deprecated Note: Starting with Chrome 33, + * this API is deprecated in favor of the + * sockets.udp, sockets.tcp and sockets.tcpServer APIs. * @since Chrome 23 */ - namespace serial { - /** NOT YET IMPLEMENTED */ - } + const serial: chrome.deprecated; //////////////////// // Socket @@ -3802,21 +6393,21 @@ declare namespace chrome { address: string; } - export function create(type: string, options?: Object, callback?: (createInfo: CreateInfo) => void): void; - export function destroy(socketId: number): void; - export function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; - export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; - export function disconnect(socketId: number): void; - export function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; - export function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; - export function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; - export function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; - export function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; - export function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; - export function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; - export function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; - export function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; - export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; + function create(type: string, options?: Object, callback?: (createInfo: CreateInfo) => void): void; + function destroy(socketId: number): void; + function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; + function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function disconnect(socketId: number): void; + function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; + function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; + function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; + function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; + function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; + function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; + function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; + function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; + function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; + function getNetworkList(callback: (result: NetworkInterface[]) => void): void; } namespace sockets.tcp { @@ -3858,28 +6449,28 @@ declare namespace chrome { peerPort?: number; } - export function create(callback: (createInfo: CreateInfo) => void): void; - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; - export function setKeepAlive(socketId: number, + function setKeepAlive(socketId: number, enable: boolean, callback: (result: number) => void): void; - export function setKeepAlive(socketId: number, + function setKeepAlive(socketId: number, enable: boolean, delay: number, callback: (result: number) => void): void; - export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; - export function connect(socketId: number, + function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + function connect(socketId: number, peerAddress: string, peerPort: number, callback: (result: number) => void): void; - export function disconnect(socketId: number, callback?: () => void): void; - export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; - export function close(socketId: number, callback?: () => void): void; - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function disconnect(socketId: number, callback?: () => void): void; + function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + function close(socketId: number, callback?: () => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; - export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } /** @@ -3960,7 +6551,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create * @param callback Called when the socket has been created. */ - export function create(callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; /** * Creates a TCP server socket. @@ -3969,7 +6560,7 @@ declare namespace chrome { * @param properties The socket properties. * @param callback Called when the socket has been created. */ - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; /** * Updates the socket properties. @@ -3979,7 +6570,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; /** * Enables or disables a listening socket from accepting new connections. @@ -3990,7 +6581,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused * @param callback Callback from the setPaused method. */ - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; /** * Listens for connections on the specified port and address. If the @@ -4007,7 +6598,7 @@ declare namespace chrome { * ensures a reasonable queue length for most applications. * @param callback Called when listen operation completes. */ - export function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; + function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; /** * Listens for connections on the specified port and address. If the @@ -4021,7 +6612,7 @@ declare namespace chrome { * be found by calling getInfo. * @param callback Called when listen operation completes. */ - export function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void; /** * Disconnects the listening socket, i.e. stops accepting new connections @@ -4033,7 +6624,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the disconnect attempt is complete. */ - export function disconnect(socketId: number, callback?: () => void): void; + function disconnect(socketId: number, callback?: () => void): void; /** * Disconnects and destroys the socket. Each socket created should be closed @@ -4045,7 +6636,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the close operation completes. */ - export function close(socketId: number, callback?: () => void): void; + function close(socketId: number, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -4054,7 +6645,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the socket state is available. */ - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -4062,14 +6653,14 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getSockets * @param callback Called when the list of sockets is available. */ - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** * Event raised when a connection has been made to the server socket. * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAccept */ - export var onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; + const onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4079,7 +6670,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError */ - export var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; + const onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; } /** @@ -4129,7 +6720,7 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to receive data. If the buffer is too + * The size of the buffer used to Receive data. If the buffer is too * small to receive the UDP packet, data is lost. The default value is * 4096. */ @@ -4181,7 +6772,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-create * @param createInfo.socketId The ID of the newly created socket. */ - export function create(callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; /** * Creates a UDP socket with the given properties. @@ -4190,7 +6781,7 @@ declare namespace chrome { * @param properties The socket properties. * @param createInfo.socketId The ID of the newly created socket. */ - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; /** * Updates the socket properties. @@ -4200,7 +6791,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; /** * Pauses or unpauses a socket. A paused socket is blocked from firing @@ -4212,7 +6803,7 @@ declare namespace chrome { * @param callback Called when the socket has been successfully paused or * unpaused. */ - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; /** * Binds the local address and port for the socket. For a client socket, it @@ -4231,7 +6822,7 @@ declare namespace chrome { * port. * @param callback Called when the bind operation completes. */ - export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; /** * Sends data on the given socket to the given address and port. The socket @@ -4244,7 +6835,7 @@ declare namespace chrome { * @param port The port of the remote machine. * @param callback Called when the send operation completes. */ - export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; /** * Closes the socket and releases the address/port the socket is bound to. @@ -4256,7 +6847,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the close operation completes. */ - export function close(socketId: number, callback?: () => void): void; + function close(socketId: number, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -4265,7 +6856,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the socket state is available. */ - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -4273,7 +6864,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-getSockets * @param callback Called when the list of sockets is available. */ - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** * Joins the multicast group and starts to receive packets from that group. @@ -4284,7 +6875,7 @@ declare namespace chrome { * @param address The group address to join. Domain names are not supported. * @param callback Called when the joinGroup operation completes. */ - export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; /** * Leaves the multicast group previously joined using joinGroup. This is @@ -4301,7 +6892,7 @@ declare namespace chrome { * supported. * @param callback Called when the leaveGroup operation completes. */ - export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; /** * Sets the time-to-live of multicast packets sent to the multicast group. @@ -4313,7 +6904,7 @@ declare namespace chrome { * @param ttl The time-to-live value. * @param callback Called when the configuration operation completes. */ - export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; /** * Sets whether multicast packets sent from the host to the multicast group @@ -4324,7 +6915,7 @@ declare namespace chrome { * when there is more than one application on the same host joined to the * same multicast group while having different settings on multicast * loopback mode. On Windows, the applications with loopback off will not - * RECEIVE the loopback packets; while on Unix-like systems, the + * receive the loopback packets; while on Unix-like systems, the * applications with loopback off will not SEND the loopback packets to * other applications on the same host. * @see MSDN: http://goo.gl/6vqbj @@ -4336,7 +6927,7 @@ declare namespace chrome { * @param enabled Indicate whether to enable loopback mode. * @param callback Called when the configuration operation completes. */ - export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; /** * Gets the multicast group addresses the socket is currently joined to. @@ -4345,7 +6936,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called with an array of strings of the result. */ - export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; /** * Enables or disables broadcast packets on this socket. @@ -4356,14 +6947,14 @@ declare namespace chrome { * @param enabled true to enable broadcast packets, false to disable them. * @param callback Callback from the setBroadcast method. */ - export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; + function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; /** * Event raised when a UDP packet has been received for the given socket. * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive */ - export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4373,7 +6964,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError */ - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } //////////////////// @@ -4437,9 +7028,9 @@ declare namespace chrome { } interface StorageChange { - /** Optional. The new value of the item, if there is a new value. */ + /** The new value of the item, if there is a new value. */ newValue?: any; - /** Optional. The old value of the item, if there was an old value. */ + /** The old value of the item, if there was an old value. */ oldValue?: any; } @@ -4473,29 +7064,163 @@ declare namespace chrome { interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> { } /** Items in the local storage area are local to each machine. */ - export var local: LocalStorageArea; + const local: LocalStorageArea; /** Items in the sync storage area are synced using Chrome Sync. */ - export var sync: SyncStorageArea; + const sync: SyncStorageArea; /** * Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. * @since Chrome 33. */ - export var managed: StorageArea; + const managed: StorageArea; /** Fired when one or more items change. */ - export var onChanged: StorageChangedEvent; + const onChanged: StorageChangedEvent; } //////////////////// // SyncFileSystem //////////////////// /** - * Use the chrome.syncFileSystem API to save and synchronize data on Google Drive. This API is NOT for accessing arbitrary user docs stored in Google Drive. It provides app-specific syncable storage for offline and caching usage so that the same data can be available across different clients. Read Manage Data for more on using this API. + * Use the chrome.syncFileSystem API to save and synchronize data on Google Drive. + * This API is NOT for accessing arbitrary user docs stored in Google Drive. + * It provides app-specific syncable storage for offline and caching usage so that + * the same data can be available across different clients. Read Manage Data for + * more on using this API. + * + * @requires[Permissions: 'syncFileSystem'] + * @see[Learn more: Manage Data]{@link https://developer.chrome.com/apps/app_storage} * @since Chrome 27 */ namespace syncFileSystem { - /** NOT YET IMPLEMENTED */ + /** + * 'initializing' + * - The sync service is being initialized (e.g. restoring data from the database, checking connectivity and authenticating to the service etc). + * 'running' + * - The sync service is up and running. + * 'authentication_required' + * - The sync service is not synchronizing files because the remote service needs to be authenticated by the user to proceed. + * 'temporary_unavailable' + * - The sync service is not synchronizing files because the remote service is (temporarily) unavailable due to some recoverable errors, e.g. network is offline, the remote service is down or not reachable etc. More details should be given by |description| parameter in OnServiceInfoUpdated (which could contain service-specific details). + * 'disabled' + * - The sync service is disabled and the content will never sync. (E.g. this could happen when the user has no account on the remote service or the sync service has had an unrecoverable error.) + */ + type ServiceStatus = + 'initializing' | + 'running' | + 'authentication_required' | + 'temporary_unavailable' | + 'disabled'; + /** + * 'synced' + * - Not conflicting and has no pending local changes. + * 'pending' + * - Has one or more pending local changes that haven't been synchronized. + * 'conflicting' + * - File conflicts with remote version and must be resolved manually. + */ + type FileStatus = + 'synced' | + 'pending' | + 'conflicting'; + type ConflictResolutionPolicy = + 'last_write_win' | + 'manual' + + type Action = + 'added' | + 'updated' | + 'deleted' + + type Direction = + 'local_to_remote' | + 'remote_to_local'; + + interface FileStatusInfo { + /** One of the Entry's originally given to getFileStatuses. */ + fileEntry: Entry; + /** Status value */ + status: FileStatus; + /** Optional error that is only returned if there was a problem retrieving the FileStatus for the given file. */ + error?: string; + } + interface FileStatusChangedDetail { + /** + * fileEntry for the target file whose status has changed. + * Contains name and path information of synchronized file. + * On file deletion, fileEntry information will still be + * available but file will no longer exist. + */ + fileEntry: Entry; + /** + * Resulting file status after onFileStatusChanged event. + * The status value can be 'synced', 'pending' or 'conflicting'. + */ + status: FileStatus; + /** + * Sync action taken to fire onFileStatusChanged event. + * The action value can be 'added', 'updated' or 'deleted'. + * Only applies if status is 'synced'. + */ + action?: Action; + /** + * Sync direction for the onFileStatusChanged event. + * Sync direction value can be 'local_to_remote' or + * 'remote_to_local'. Only applies if status is 'synced'. + */ + direction?: Direction; + } + /** + * Returns a syncable filesystem backed by Google Drive. + * The returned DOMFileSystem instance can be operated on + * in the same way as the Temporary and Persistant file systems + * @see[More information]{@link http://dev.w3.org/2009/dap/file-system/file-dir-sys.html} + * @description + * Calling this multiple times from the same app will return the same handle to the same file system. + * Note this call can fail. + * For example, if the user is not signed in to Chrome + * or if there is no network operation. To handle these + * errors it is important chrome.runtime.lastError is + * checked in the callback. + * @param callback A callback type for requestFileSystem. + */ + function requestFileSystem(callback: (fileSystem: FileSystem) => void): void; + /** + * Sets the default conflict resolution policy for the 'syncable' file storage + * for the app. By default it is set to 'last_write_win'. When conflict resolution + * policy is set to 'last_write_win' conflicts for existing files are automatically + * resolved next time the file is updated. |callback| can be optionally given to + * know if the request has succeeded or not. + * @param policy Policy + * @param [callback] A generic result callback to indicate success or failure. + */ + function setConflictResolutionPolicy(policy: ConflictResolutionPolicy, callback?: () => void): void; + /** Gets the current conflict resolution policy. */ + function getConflictResolutionPolicy(callback: (policy: ConflictResolutionPolicy) => void): void; + /** + * Returns the current usage and quota in bytes for the 'syncable' file storage for the app. + * @param fileSystem + * @param callback + */ + function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: number, quotaBytes: number }) => void): void; + /** + * Returns the FileStatus for the given fileEntry. + * Note that 'conflicting' state only happens when + * the service's conflict resolution policy is set to 'manual'. + * */ + function getFileStatus(fileEntry: Entry, callback: (status: FileStatus) => void): void; + /** Returns each FileStatus for the given fileEntry array. Typically called with the result from dirReader.readEntries(). */ + function getFileStatuses(fileEntries: Entry[], callback: (status: FileStatusInfo[]) => void): void; + /** + * Returns the current sync backend status. + * @since Chrome 31. + * @param callback + */ + function getServiceStatus(callback: (status: ServiceStatus) => void): void; + /** Fired when an error or other status change has happened in the sync backend (for example, when the sync is temporarily disabled due to network or authentication error). */ + const onServiceStatusChanged: chrome.events.Event<(detail: { state: ServiceStatus, description: string }) => void>; + /** Fired when a file has been updated by the background sync service. */ + const onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } @@ -4541,7 +7266,7 @@ declare namespace chrome { } /** Queries basic CPU information of the system. */ - export function getInfo(callback: (info: CpuInfo) => void): void; + function getInfo(callback: (info: CpuInfo) => void): void; } //////////////////// @@ -4589,7 +7314,7 @@ declare namespace chrome { * @since Chrome 57 */ interface TouchCalibrationPair { - /** The coordinates of the display point. */ + /** The coordinates of the display point. */ displayPoint: Point; /** The coordinates of the touch point corresponding to the display point. */ touchPoint: Point; @@ -4624,6 +7349,8 @@ declare namespace chrome { isSelected: boolean; } + type DisplayPosition = 'top' | 'right' | 'bottom' | 'left'; + /** * @since Chrome 53 */ @@ -4633,13 +7360,13 @@ declare namespace chrome { /** The unique identifier of the parent display. Empty if this is the root. */ parentId: string; /** The layout position of this display relative to the parent. This will be ignored for the root. */ - position: 'top' | 'right' | 'bottom' | 'left'; + position: DisplayPosition; /** The offset of the display along the connected edge. 0 indicates that the topmost or leftmost corners are aligned. */ offset: number; } /** - * @description The pairs of point used to calibrate the display. + * The pairs of point used to calibrate the display. * @export * @interface TouchCalibrationPairs */ @@ -4655,13 +7382,13 @@ declare namespace chrome { } /** - * @description Representation of info data to be used in chrome.system.display.setDisplayProperties() + * Representation of info data to be used in chrome.system.display.setDisplayProperties() * @export * @interface DisplayPropertiesInfo */ interface DisplayPropertiesInfo { /** - * @description Chrome OS only. If set to true, changes the display mode to unified desktop (see enableUnifiedDesktop for details). If set to false, unified desktop mode will be disabled. This is only valid for the primary display. If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. + * Chrome OS only. If set to true, changes the display mode to unified desktop (see enableUnifiedDesktop for details). If set to false, unified desktop mode will be disabled. This is only valid for the primary display. If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. * @since Chrome 59 * */ isUnified?: boolean; @@ -4688,20 +7415,20 @@ declare namespace chrome { /** * @since Chrome 52 - * @description If set, updates the display mode to the mode matching this value. + * If set, updates the display mode to the mode matching this value. */ displayMode?: DisplayMode; } /** - * @description Options affecting how the information is returned. + * Options affecting how the information is returned. * @since Chrome 59 * @export * @interface DisplayInfoFlags */ interface DisplayInfoFlags { /** - * @description If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode (see enableUnifiedDesktop). Defaults to false. + * If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode (see enableUnifiedDesktop). Defaults to false. * @type {boolean} * @memberof DisplayInfoFlags */ @@ -4753,7 +7480,7 @@ declare namespace chrome { } /** - * @description Fired when anything changes to the display configuration. + * Fired when anything changes to the display configuration. * @export * @interface DisplayChangedEvent * @extends {chrome.events.Event<() => void>} @@ -4761,123 +7488,123 @@ declare namespace chrome { interface DisplayChangedEvent extends chrome.events.Event<() => void> { } /** - * @description Requests the information for all attached display devices. + * Requests the information for all attached display devices. * @export * @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results. */ - export function getInfo(callback: (info: DisplayInfo[]) => void): void; + function getInfo(callback: (info: DisplayInfo[]) => void): void; /** - * @description Requests the information for all attached display devices. + * Requests the information for all attached display devices. * @export * @since Chrome 59 * @param {DisplayInfoFlags} [flags] Options affecting how the information is returned. * @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results. */ - export function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void; + function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void; /** - * @description Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 53 * @export * @param {(layouts: DisplayLayout[]) => void} callback The callback to invoke with the results. */ - export function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; + function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; /** - * @description Updates the properties for the display specified by |id|, according to the information provided in |info|. On failure, runtime.lastError will be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Updates the properties for the display specified by |id|, according to the information provided in |info|. On failure, runtime.lastError will be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @export * @param {string} id The display's unique identifier. * @param {DisplayPropertiesInfo} info The information about display properties that should be changed. A property will be changed only if a new value for it is specified in |info|. * @param {() => void} [callback] Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ - export function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void; + function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void; /** - * @description Set the layout for all displays. Any display not included will use the default layout. If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. After layout is resolved, an onDisplayChanged event will be triggered. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Set the layout for all displays. Any display not included will use the default layout. If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. After layout is resolved, an onDisplayChanged event will be triggered. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 53 * @export * @param {DisplayLayout[]} layouts The layout information, required for all displays except the primary display. * @param {() => void} callback Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ - export function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void; + function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void; /** - * @description Enables/disables the unified desktop feature. Note that this simply enables the feature, but will not change the actual desktop mode. (That is, if the desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Enables/disables the unified desktop feature. Note that this simply enables the feature, but will not change the actual desktop mode. (That is, if the desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 46 * @export * @param {boolean} enabled True if unified desktop should be enabled. */ - export function enableUnifiedDesktop(enabled: boolean): void; + function enableUnifiedDesktop(enabled: boolean): void; /** - * @description Starts overscan calibration for a display. This will show an overlay on the screen indicating the current overscan insets. If overscan calibration for display |id| is in progress this will reset calibration. + * Starts overscan calibration for a display. This will show an overlay on the screen indicating the current overscan insets. If overscan calibration for display |id| is in progress this will reset calibration. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationStart(id: string): void; + function overscanCalibrationStart(id: string): void; /** - * @description Adjusts the current overscan insets for a display. Typically this should etiher move the display along an axis (e.g. left+right have the same value) or scale it along an axis (e.g. top+bottom have opposite values). Each Adjust call is cumulative with previous calls since Start. + * Adjusts the current overscan insets for a display. Typically this should etiher move the display along an axis (e.g. left+right have the same value) or scale it along an axis (e.g. top+bottom have opposite values). Each Adjust call is cumulative with previous calls since Start. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. * @param {Insets} delta The amount to change the overscan insets. */ - export function overscanCalibrationAdjust(id: string, delta: Insets): void; + function overscanCalibrationAdjust(id: string, delta: Insets): void; /** - * @description Resets the overscan insets for a display to the last saved value (i.e before Start was called). + * Resets the overscan insets for a display to the last saved value (i.e before Start was called). * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationReset(id: string): void; + function overscanCalibrationReset(id: string): void; /** - * @description Complete overscan adjustments for a display by saving the current values and hiding the overlay. + * Complete overscan adjustments for a display by saving the current values and hiding the overlay. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationComplete(id: string): void; + function overscanCalibrationComplete(id: string): void; /** - * @description Displays the native touch calibration UX for the display with |id| as display id. This will show an overlay on the screen with required instructions on how to proceed. The callback will be invoked in case of successful calibraion only. If the calibration fails, this will throw an error. + * Displays the native touch calibration UX for the display with |id| as display id. This will show an overlay on the screen with required instructions on how to proceed. The callback will be invoked in case of successful calibraion only. If the calibration fails, this will throw an error. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. * @param {(success) => void} callback Optional callback to inform the caller that the touch calibration has ended. The argument of the callback informs if the calibration was a success or not. */ - export function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; + function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; /** - * @description Starts custom touch calibration for a display. This should be called when using a custom UX for collecting calibration data. If another touch calibration is already in progress this will throw an error. + * Starts custom touch calibration for a display. This should be called when using a custom UX for collecting calibration data. If another touch calibration is already in progress this will throw an error. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. */ - export function startCustomTouchCalibration(id: string): void; + function startCustomTouchCalibration(id: string): void; /** - * @description Sets the touch calibration pairs for a display. These |pairs| would be used to calibrate the touch screen for display with |id| called in startCustomTouchCalibration(). Always call |startCustomTouchCalibration| before calling this method. If another touch calibration is already in progress this will throw an error. + * Sets the touch calibration pairs for a display. These |pairs| would be used to calibrate the touch screen for display with |id| called in startCustomTouchCalibration(). Always call |startCustomTouchCalibration| before calling this method. If another touch calibration is already in progress this will throw an error. * @since Chrome 57 * @export * @param {TouchCalibrationPairs} pairs The pairs of point used to calibrate the display. * @param {Bounds} bounds Bounds of the display when the touch calibration was performed. |bounds.left| and |bounds.top| values are ignored. */ - export function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void; + function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void; /** - * @description Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display. + * Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. */ - export function clearTouchCalibration(id: string): void; + function clearTouchCalibration(id: string): void; /** - * @description Fired when anything changes to the display configuration. + * Fired when anything changes to the display configuration. * @export */ - export var onDisplayChanged: DisplayChangedEvent; + const onDisplayChanged: DisplayChangedEvent; } //////////////////// @@ -4897,7 +7624,7 @@ declare namespace chrome { } /** Get physical memory information. */ - export function getInfo(callback: (info: MemoryInfo) => void): void; + function getInfo(callback: (info: MemoryInfo) => void): void; } //////////////////// @@ -4910,7 +7637,7 @@ declare namespace chrome { prefixLength: number; } - export function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; + function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } //////////////////// @@ -4950,23 +7677,23 @@ declare namespace chrome { interface SystemStorageDetachedEvent extends chrome.events.Event<(id: string) => void> { } /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ - export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; + function getInfo(callback: (info: StorageUnitInfo[]) => void): void; /** * Ejects a removable storage device. * @param callback * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. */ - export function ejectDevice(id: string, callback: (result: string) => void): void; + function ejectDevice(id: string, callback: (result: string) => void): void; /** * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. * @since Dev channel only. */ - export function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; + function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; /** Fired when a new removable storage is attached to the system. */ - export var onAttached: SystemStorageAttachedEvent; + const onAttached: SystemStorageAttachedEvent; /** Fired when a removable storage is detached from the system. */ - export var onDetached: SystemStorageDetachedEvent; + const onDetached: SystemStorageDetachedEvent; } //////////////////// @@ -4980,9 +7707,9 @@ declare namespace chrome { namespace tts { /** An event from the TTS engine to communicate the status of an utterance. */ interface TtsEvent { - /** Optional. The index of the current character in the utterance. */ + /** The index of the current character in the utterance. */ charIndex?: number; - /** Optional. The error description, if the event type is 'error'. */ + /** The error description, if the event type is 'error'. */ errorMessage?: string; /** * The type can be 'start' as soon as speech has started, 'word' when a word boundary is reached, 'sentence' when a sentence boundary is reached, 'marker' when an SSML mark element is reached, 'end' when the end of the utterance is reached, 'interrupted' when the utterance is stopped or interrupted before reaching the end, 'cancelled' when it's removed from the queue before ever being synthesized, or 'error' when any other error occurs. When pausing speech, a 'pause' event is fired if a particular utterance is paused in the middle, and 'resume' if an utterance resumes speech. Note that pause and resume events may not fire if speech is paused in-between utterances. @@ -4993,14 +7720,14 @@ declare namespace chrome { /** A description of a voice available for speech synthesis. */ interface TtsVoice { - /** Optional. The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ + /** The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; /** - * Optional. This voice's gender. + * This voice's gender. * One of: 'male', or 'female' */ gender?: string; - /** Optional. The name of the voice. */ + /** The name of the voice. */ voiceName?: string; /** The ID of the extension providing this voice. */ extensionsId?: string; @@ -5014,7 +7741,7 @@ declare namespace chrome { } interface SpeakOptions { - /** Optional. Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ + /** Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ volume?: number; /** * Optional. @@ -5027,7 +7754,7 @@ declare namespace chrome { */ rate?: number; /** - * Optional. This function is called with events that occur in the process of speaking the utterance. + * This function is called with events that occur in the process of speaking the utterance. * @param event The update event from the text-to-speech engine indicating the status of this utterance. */ onEvent?: (event: TtsEvent) => void; @@ -5036,52 +7763,52 @@ declare namespace chrome { * Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 corresponds to a voice's default pitch. */ pitch?: number; - /** Optional. The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ + /** The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; - /** Optional. The name of the voice to use for synthesis. If empty, uses any available voice. */ + /** The name of the voice to use for synthesis. If empty, uses any available voice. */ voiceName?: string; - /** Optional. The extension ID of the speech engine to use, if known. */ + /** The extension ID of the speech engine to use, if known. */ extensionId?: string; /** - * Optional. Gender of voice for synthesized speech. + * Gender of voice for synthesized speech. * One of: 'male', or 'female' */ gender?: string; - /** Optional. The TTS event types the voice must support. */ + /** The TTS event types the voice must support. */ requiredEventTypes?: string[]; - /** Optional. The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ + /** The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ desiredEventTypes?: string[]; } /** Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the system speech engine is speaking, even if the speech wasn't initiated by Chrome. */ - export function isSpeaking(callback?: (speaking: boolean) => void): void; + function isSpeaking(callback?: (speaking: boolean) => void): void; /** Stops any current speech and flushes the queue of any pending utterances. In addition, if speech was paused, it will now be un-paused for the next call to speak. */ - export function stop(): void; + function stop(): void; /** Gets an array of all available voices. */ - export function getVoices(callback?: (voices: TtsVoice[]) => void): void; + function getVoices(callback?: (voices: TtsVoice[]) => void): void; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. + * @param callback Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ - export function speak(utterance: string, callback?: Function): void; + function speak(utterance: string, callback?: Function): void; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param options Optional. The speech options. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. + * @param options The speech options. + * @param callback Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ - export function speak(utterance: string, options: SpeakOptions, callback?: Function): void; + function speak(utterance: string, options: SpeakOptions, callback?: Function): void; /** * Pauses speech synthesis, potentially in the middle of an utterance. A call to resume or stop will un-pause speech. * @since Chrome 29. */ - export function pause(): void; + function pause(): void; /** * If speech was paused, resumes speaking where it left off. * @since Chrome 29. */ - export function resume(): void; + function resume(): void; } //////////////////// @@ -5122,14 +7849,14 @@ declare namespace chrome { } interface ChromeSettingGetDetails { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ + /** Whether to return the value that applies to the incognito session (default false). */ incognito?: boolean; } /** * @param details Details of the currently effective value. */ - export type DetailsCallback = (details: ChromeSettingGetResultDetails) => void; + type DetailsCallback = (details: ChromeSettingGetResultDetails) => void; interface ChromeSettingGetResultDetails { /** @@ -5157,7 +7884,7 @@ declare namespace chrome { /** * Sets the value of a setting. * @param details Which setting to change. - * @param callback Optional. Called at the completion of the set operation. + * @param callback Called at the completion of the set operation. */ set(details: ChromeSettingSetDetails, callback?: Function): void; /** @@ -5168,7 +7895,7 @@ declare namespace chrome { /** * Clears the setting, restoring any default value. * @param details Which setting to clear. - * @param callback Optional. Called at the completion of the clear operation. + * @param callback Called at the completion of the clear operation. */ clear(details: ChromeSettingClearDetails, callback?: Function): void; /** Fired after the setting changes. */ @@ -5197,13 +7924,17 @@ declare namespace chrome { productId: number } + type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; + type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; + type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback'; + interface EndpointDescriptor { address: number, - type: 'control' | 'interrupt' | 'isochronous' | 'bulk', + type: EndpointType, direction: Direction, maximumPacketSize: number, - synchronization?: 'asynchronous' | 'adaptive' | 'synchronous', - usage?: 'data' | 'feedback' | 'explicitFeedback', + synchronization?: EndpointSyncType, + usage?: EndpointUsage, pollingInterval?: number, extra_data: ArrayBuffer } @@ -5251,10 +7982,14 @@ declare namespace chrome { interfaceProtocol?: number } + type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; + + type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; + interface TransferInfo { direction: Direction; - recipient: 'device' | 'interface' | 'endpoint' | 'other'; - requestType: 'standard' | 'class' | 'vendor' | 'reserved'; + recipient: TransferRecipient; + requestType: TransferRequestType; request: number; value: number; index: number; @@ -5265,27 +8000,27 @@ declare namespace chrome { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> { } - export var onDeviceAdded: DeviceEvent; - export var onDeviceRemoved: DeviceEvent; + const onDeviceAdded: DeviceEvent; + const onDeviceRemoved: DeviceEvent; - export function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; - export function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; - export function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void; - export function requestAccess(device: Device, interfaceId: number, callback: (success: boolean) => void): void; - export function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void; - export function findDevices(options: { vendorId: number, productId: number, interfaceId?: number }, callback: (handles: ConnectionHandle[]) => void): void; - export function closeDevice(handle: ConnectionHandle, callback?: () => void): void; - export function setConfiguration(handle: ConnectionHandle, configurationValue: number, callback: () => void): void; - export function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void; - export function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void; - export function claimInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; - export function releaseInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; - export function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: number, alternateSetting: number, callback: () => void): void; - export function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void; - export function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; - export function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; - export function isochronousTransfer(handle: ConnectionHandle, transferInfo: { transferInfo: GenericTransferInfo, packets: number, packetLength: number }, callback: (info: TransferResultInfo) => void): void; - export function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void; + function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void; + function requestAccess(device: Device, interfaceId: number, callback: (success: boolean) => void): void; + function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void; + function findDevices(options: { vendorId: number, productId: number, interfaceId?: number }, callback: (handles: ConnectionHandle[]) => void): void; + function closeDevice(handle: ConnectionHandle, callback?: () => void): void; + function setConfiguration(handle: ConnectionHandle, configurationValue: number, callback: () => void): void; + function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void; + function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void; + function claimInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; + function releaseInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; + function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: number, alternateSetting: number, callback: () => void): void; + function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void; + function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + function isochronousTransfer(handle: ConnectionHandle, transferInfo: { transferInfo: GenericTransferInfo, packets: number, packetLength: number }, callback: (info: TransferResultInfo) => void): void; + function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void; } @@ -5302,9 +8037,9 @@ declare namespace chrome { interface VpnSessionParameters { /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ address: string; - /** Optional. Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ + /** Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ broadcastAddress?: string; - /** Optional. MTU setting for the VPN interface. (default: 1500 bytes) */ + /** MTU setting for the VPN interface. (default: 1500 bytes) */ mtu?: string; /** * Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. This can be used to bypass traffic to and from the VPN server. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. @@ -5314,7 +8049,7 @@ declare namespace chrome { * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry '0.0.0.0/0' to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. */ inclusionList: string[]; - /** Optional. A list of search domains. (default: no search domain) */ + /** A list of search domains. (default: no search domain) */ domainSearch?: string[]; /** A list of IPs for the DNS servers. */ dnsServer: string[]; @@ -5336,135 +8071,123 @@ declare namespace chrome { * @param callback Called when the configuration is created or if there is an error. * Parameter id: A unique ID for the created configuration, empty string on failure. */ - export function createConfig(name: string, callback: (id: string) => void): void; + function createConfig(name: string, callback: (id: string) => void): void; /** * Destroys a VPN configuration created by the extension. * @param id ID of the VPN configuration to destroy. - * @param callback Optional. Called when the configuration is destroyed or if there is an error. + * @param callback Called when the configuration is destroyed or if there is an error. */ - export function destroyConfig(id: string, callback?: Function): void; + function destroyConfig(id: string, callback?: Function): void; /** * Sets the parameters for the VPN session. This should be called immediately after 'connected' is received from the platform. This will succeed only when the VPN session is owned by the extension. * @param parameters The parameters for the VPN session. * @param callback Called when the parameters are set or if there is an error. */ - export function setParameters(parameters: VpnSessionParameters, callback: Function): void; + function setParameters(parameters: VpnSessionParameters, callback: Function): void; /** * Sends an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension. * @param data The IP packet to be sent to the platform. - * @param callback Optional. Called when the packet is sent or if there is an error. + * @param callback Called when the packet is sent or if there is an error. */ - export function sendPacket(data: ArrayBuffer, callback?: Function): void; + function sendPacket(data: ArrayBuffer, callback?: Function): void; /** * Notifies the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension. * @param state The VPN session state of the VPN client. * connected: VPN connection was successful. * failure: VPN connection failed. - * @param callback Optional. Called when the notification is complete or if there is an error. + * @param callback Called when the notification is complete or if there is an error. */ - export function notifyConnectionStateChanged(state: string, callback?: Function): void; + function notifyConnectionStateChanged(state: string, callback?: Function): void; /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - export var onPlatformMessage: VpnPlatformMessageEvent; + const onPlatformMessage: VpnPlatformMessageEvent; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - export var onPacketReceived: VpnPacketReceptionEvent; + const onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ - export var onConfigRemoved: VpnConfigRemovalEvent; + const onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ - export var onConfigCreated: VpnConfigCreationEvent; + const onConfigCreated: VpnConfigCreationEvent; /** Triggered when there is a UI event for the extension. UI events are signals from the platform that indicate to the app that a UI dialog needs to be shown to the user. */ - export var onUIEvent: VpnUiEvent; + const onUIEvent: VpnUiEvent; } - //////////////////// - // Wallpaper - //////////////////// + /////////////// + // Wallpaper // + /////////////// /** * Use the chrome.wallpaper API to change the ChromeOS wallpaper. - * Permissions: 'wallpaper' - * Important: This API works only on Chrome OS. + * @requires Permissions: 'wallpaper' + * @requires Important: This API works only on Chrome OS. * @since Chrome 43. */ namespace wallpaper { + type WallpaperLayout = + 'STRETCH' | + 'CENTER' | + 'CENTER_CROPPED'; interface WallpaperDetails { - /** Optional. The jpeg or png encoded wallpaper image. */ + /** The jpeg or png encoded wallpaper image. */ data?: any; - /** Optional. The URL of the wallpaper to be set. */ + /** The URL of the wallpaper to be set. */ url?: string; - /** - * The supported wallpaper layouts. - * One of: 'STRETCH', 'CENTER', or 'CENTER_CROPPED' - */ - layout: string; + /** The supported wallpaper layouts. */ + layout: WallpaperLayout; /** The file name of the saved wallpaper. */ filename: string; - /** Optional. True if a 128x60 thumbnail should be generated. */ + /** True if a 128x60 thumbnail should be generated. */ thumbnail?: boolean; } /** * Sets wallpaper to the image at url or wallpaperData with the specified layout - * @param callback - * Optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. + * @param callback Contains the optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. */ - export function setWallpaper(details: WallpaperDetails, callback: (thumbnail: any) => void): void; + function setWallpaper(details: WallpaperDetails, callback: (thumbnail?: string) => void): void; } - /////////////////// - // Webview Tag - /////////////////// + ///////////////// + // Webview Tag // + ///////////////// /** - * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. Your app can control the appearance of the webview and interact with the web content, initiate navigations in an embedded web page, react to error events that happen within it, and more (see Usage). + * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. + * Your app can control the appearance of the *webview* and interact with the web content, initiate navigations in + * an embedded web page, react to error events that happen within it. */ namespace webview { - /** Options that determine what data should be cleared by `clearData`. */ + /** Options that determine what data should be cleared by *clearData`* */ interface ClearDataOptions { - /** Clear data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data). */ + /** + * Clear data accumulated on or after this date, + * represented in milliseconds since the epoch + * (accessible via the getTime method of the JavaScript *Date* object). + * If absent, defaults to *0* (which would remove all browsing data). + **/ since?: number; } interface WindowEvent extends chrome.events.Event<() => void> { } interface ConsoleEvent extends Event { - /** - * @description The severity level of the log message. Ranges from 0 to 4. - * @type {number} - * @memberof ConsoleEvent - */ + /** The severity level of the log message. Ranges from 0 to 4. */ level: number; - /** - * @description The logged message contents. - * @type {string} - * @memberof ConsoleEvent - */ + /** The logged message contents.*/ message: string; - /** - * @description The line number of the message source. - * @type {number} - * @memberof ConsoleEvent - */ + /** The line number of the message source.*/ line: number; - /** - * @description A string identifying the resource which logged the message. - * @type {string} - * @memberof ConsoleEvent - */ + /** A string identifying the resource which logged the message. */ sourceId: string; } + type ExitEventReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; interface ExitEvent extends Event { - /** - * @description Chrome's internal ID of the process that exited. - * @type {number} - * @memberof ExitEvent - */ + /** Chrome's internal ID of the process that exited. */ processID: number; - /** - * @description String indicating the reason for the exit. - * @type {string} - * @memberof ExitEvent - */ - reason: 'normal' | 'abnormal' | 'crash' | 'kill'; + /** String indicating the reason for the exit. */ + reason: ExitEventReason; } /** Description of a declarative rule for handling events. */ @@ -5473,47 +8196,44 @@ declare namespace chrome { priority?: number; /** List of conditions that can trigger the actions. */ conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ + /** Optional identifier that allows referencing this rule. */ id?: string; /** List of actions that are triggered if one of the condtions is fulfilled. */ actions: any[]; /** - * @description Tags can be used to annotate rules and perform operations on sets of rules.¨ + * Tags can be used to annotate rules and perform operations on sets of rules.¨ * @since Chrome 28 - * @type {string[]} - * @memberof Rule */ tags?: string[]; } /** - * @description Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @export - * @interface InjectDetails + * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ interface InjectDetails { /** - * @description JavaScript or CSS code to inject.

Warning:
Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. - * @type {string} - * @memberof InjectDetails + * JavaScript or CSS code to inject. + * + * **Warning** + * Be careful using the *code* parameter. + * Incorrect use of it may open your app to + * cross site scripting attacks. + * @see[More information]{@link https://en.wikipedia.org/wiki/Cross-site_scripting} */ code?: string, /** - * @description JavaScript or CSS file to inject. - * @type {string} - * @memberof InjectDetails + * JavaScript or CSS file to inject. */ file?: string } /** - * @description WebView element from html + * WebView element from html */ - interface HTMLWebViewElement extends Element { - /** - * This sets the guest content's window.name object. - */ + interface HTMLWebViewElement extends HTMLElement { + /** This sets the guest content's window.name object.**/ name: string; + /** * Returns the visible URL. Mirrors the logic in the browser's omnibox: either returning a pending new navigation if initiated by the embedder page, or the last committed navigation. Writing to this attribute initiates top-level navigation. * Assigning src its own value will reload the current page. @@ -5521,28 +8241,45 @@ declare namespace chrome { * The src attribute can also accept data URLs, such as 'data:text/plain,Hello, world!'. */ src: string; + /** - * Storage partition ID used by the webview tag. If the storage partition ID starts with persist: (partition='persist:googlepluswidgets'), the webview will use a persistent storage partition available to all guests in the app with the same storage partition ID. If the ID is unset or if there is no 'persist': prefix, the webview will use an in-memory storage partition. This value can only be modified before the first navigation, since the storage partition of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. By assigning the same partition ID, multiple webviews can share the same storage partition. + * Storage partition ID used by the webview tag. + * If the storage partition ID starts with persist: (partition='persist:googlepluswidgets'), + * the webview will use a persistent storage partition available to all guests in the app with the same storage partition ID. + * If the ID is unset or if there is no 'persist': prefix, the webview will use an in-memory storage partition. + * his value can only be modified before the first navigation, since the storage partition of an active renderer process cannot change. + * Subsequent attempts to modify the value will fail with a DOM exception. + * By assigning the same partition ID, multiple webviews can share the same storage partition. */ partition?: string; + /** - * If present, portions of the embedder could be visible through the webview, where the contents are transparent. Without allowtransparency enabled, no part of the embedder will be shown through the webview, even if elements exist that are specified as transparent. + * If present, portions of the embedder could be visible through the webview, + * where the contents are transparent. Without allowtransparency enabled, + * no part of the embedder will be shown through the webview, + * even if elements exist that are specified as transparent. * This does not affect transparency within the contents of the webview itself. */ allowtransparency?: boolean; + /** * If 'on', the webview container will automatically resize within the bounds specified by the attributes minwidth, minheight, maxwidth, and maxheight. * These constraints do not impact the webview UNLESS autosize is enabled. * When autosize is enabled, the webview container size cannot be less than the minimum values or greater than the maximum. */ autosize?: 'on'; + /** * Object reference which can be used to post messages into the guest page. */ contentWindow: ContentWindow; + /** Interface which provides access to webRequest events on the guest page. */ request: WebRequestEventInterface; - /** Similar to chrome's ContextMenus API, but applies to webview instead of browser. Use the webview.contextMenus API to add items to webview's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. */ + + /** Similar to chrome's ContextMenus API, but applies to webview instead of browser. + * Use the webview.contextMenus API to add items to webview's context menu. + * You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. */ contextMenus: webview.ContextMenus; /** * Fired when the guest window attempts to close itself. @@ -5553,7 +8290,7 @@ declare namespace chrome { * Fired when the guest window logs a console message. * The following example code forwards all log messages to the embedder's console without regard for log level or other properties. */ - addEventListener(type: 'consolemessage', listener: (this: HTMLWebViewElement, ev: IConsoleMessage) => void, useCapture?: boolean): void; + addEventListener(type: 'consolemessage', listener: (this: HTMLWebViewElement, ev: ConsoleMessage) => void, useCapture?: boolean): void; /** * Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads. * The following example code modifies the default font size of the guest's body element after the page loads: @@ -5568,33 +8305,33 @@ declare namespace chrome { * Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.) * The default behavior is to cancel the dialog. */ - addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: IDialog) => void, useCapture?: boolean): void; + addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: Dialog) => void, useCapture?: boolean): void; /** * Fired when the process rendering the guest web content has exited. */ - addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: IExit) => void, useCapture?: boolean): void; + addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: Exit) => void, useCapture?: boolean): void; /** * Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. */ - addEventListener(type: 'findupdate', listener: (this: HTMLWebViewElement, ev: IFindupdate) => void, useCapture?: boolean): void; + addEventListener(type: 'findupdate', listener: (this: HTMLWebViewElement, ev: FindUpdate) => void, useCapture?: boolean): void; /** * Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented. * Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted. * Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'. */ - addEventListener(type: 'loadabort', listener: (this: HTMLWebViewElement, ev: ILoadabort) => void, useCapture?: boolean): void; + addEventListener(type: 'loadabort', listener: (this: HTMLWebViewElement, ev: LoadAbort) => void, useCapture?: boolean): void; /** * Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. */ - addEventListener(type: 'loadcommit', listener: (this: HTMLWebViewElement, ev: ILoadcommit) => void, useCapture?: boolean): void; + addEventListener(type: 'loadcommit', listener: (this: HTMLWebViewElement, ev: LoadCommit) => void, useCapture?: boolean): void; /** * Fired when a top-level load request has redirected to a different URL. */ - addEventListener(type: 'loadredirect', listener: (this: HTMLWebViewElement, ev: ILoadredirect) => void, useCapture?: boolean): void; + addEventListener(type: 'loadredirect', listener: (this: HTMLWebViewElement, ev: LoadRedirect) => void, useCapture?: boolean): void; /** * Fired when a load has begun. */ - addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: ILoadstart) => void, useCapture?: boolean): void; + addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: LoadStart) => void, useCapture?: boolean): void; /** * Fired when all frame-level loads in a guest page (including all its subframes) have completed. * This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. @@ -5608,12 +8345,12 @@ declare namespace chrome { * The following example code will create and navigate a new webview in the embedder for each requested new window: * @example * webview.addEventListener('newwindow', function(e) { - * var newWebview = document.createElement('webview'); + * const newWebview = document.createElement('webview'); * document.body.appendChild(newWebview); * e.window.attach(newWebview); * }); */ - addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: INewwindow) => void, useCapture?: boolean): void; + addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: NewWindow) => void, useCapture?: boolean): void; /** * Fired when the guest page needs to request special permission from the embedder. * The following example code will grant the guest page access to the webkitGetUserMedia API. @@ -5625,40 +8362,40 @@ declare namespace chrome { * } * }); */ - addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: IPermissionrequest) => void, useCapture?: boolean): void; + addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: PermissionRequest) => void, useCapture?: boolean): void; /** Fired when the process rendering the guest web content has become responsive again after being unresponsive. */ - addEventListener(type: 'response', listener: (this: HTMLWebViewElement, ev: IResponsive) => void, useCapture?: boolean): void; + addEventListener(type: 'response', listener: (this: HTMLWebViewElement, ev: ProcessResponsive) => void, useCapture?: boolean): void; /** Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. */ - addEventListener(type: 'sizechanged', listener: (this: HTMLWebViewElement, ev: ISizechanged) => void, useCapture?: boolean): void; + addEventListener(type: 'sizechanged', listener: (this: HTMLWebViewElement, ev: SizeChanged) => void, useCapture?: boolean): void; /** Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. */ - addEventListener(type: 'unresponsive', listener: (this: HTMLWebViewElement, ev: IUnresponsive) => void, useCapture?: boolean): void; + addEventListener(type: 'unresponsive', listener: (this: HTMLWebViewElement, ev: ProcessUnresponsive) => void, useCapture?: boolean): void; /** Fired when the page's zoom changes. */ - addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: IZoomchange) => void, useCapture?: boolean): void; + addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: ZoomChange) => void, useCapture?: boolean): void; /** - * @description Queries audio state. - */ + * Queries audio state. + **/ getAudioState(callback: (audible: boolean) => void): void; /** - * @description Sets audio mute state of the webview. - * @param {boolean} mute Mute audio value + * Sets audio mute state of the webview. + * @param mute Mute audio value */ setAudioMuted(mute: boolean): void; /** - * @description Queries whether audio is muted. + * Queries whether audio is muted. */ isAudioMuted(callback: (muted: boolean) => void): void; /** - * @description Captures the visible region of the webview. - * @param {(dataUrl: string) => void} callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. + * Captures the visible region of the webview. + * @param callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleRegion(callback: (dataUrl: string) => void): void; /** - * @description Captures the visible region of the webview. - * @param {*} options - * @param {(dataUrl: string) => void} callback + * Captures the visible region of the webview. + * @param options + * @param callback */ captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; @@ -5713,1059 +8450,975 @@ declare namespace chrome { addContentScripts(contentScriptList: ContentScriptDetails[]): void; /** - * @description Navigates backward one history entry if possible. Equivalent to go(-1). - * @param {(success: boolean) => void} [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. + * Navigates backward one history entry if possible. Equivalent to go(-1). + * @param [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. */ back(callback?: (success: boolean) => void): void; /** - * @description Indicates whether or not it is possible to navigate backward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + * Indicates whether or not it is possible to navigate backward through history. + * The state of this function is cached, and updated before each loadcommit, + * so the best place to call it is on loadcommit. */ canGoBack(): void; /** - * @description Indicates whether or not it is possible to navigate forward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + * Indicates whether or not it is possible to navigate forward through history. + * The state of this function is cached, and updated before each loadcommit, + * so the best place to call it is on loadcommit. */ canGoForward(): void; /** - * @description

Clears browsing data for the webview partition.

- * @param options Options determining which data to clear. - * @param types The types of data to be cleared. + * Clears browsing data for the webview partition. + * @param options Options determining which data to clear. + * @param types The types of data to be cleared. * @param callback */ clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; /** - * @description

Injects JavaScript code into the guest page.

The following sample code uses script injection to set the guest page's background color to red:

webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' });
- * @param details Details of the script to run. + * Injects JavaScript code into the guest page. + * The following sample code uses script injection + * to set the guest page's background color to red: + * @example webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' }); + * @param details Details of the script to run. * @param callback */ executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; /** - * @description Initiates a find-in-page request. - * @param {string} searchText The string to find in the page. - * @param options Options for the find request. + * Initiates a find-in-page request. + * @param {string} searchText The string to find in the page. + * @param options Options for the find request. * @param callback */ find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; /** - * @description Navigates forward one history entry if possible. Equivalent to go(1). + * Navigates forward one history entry if possible. Equivalent to go(1). * @param callback */ forward(callback?: (success: boolean) => void): void; /** - * @description Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. + * Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. */ getProcessId(): void; /** - * @description Returns the user agent string used by the webview for guest page requests. + * Returns the user agent string used by the webview for guest page requests. */ getUserAgent(): void; /** - * @description Gets the current zoom factor. + * Gets the current zoom factor. * @param callback */ getZoom(callback: (zoomFactor: number) => void): void; /** - * @description Gets the current zoom mode. + * Gets the current zoom mode. * @param callback */ getZoomMode(callback: (ZoomMode: any) => void): void; /** - * @description Navigates to a history entry using a history index relative to the current navigation. If the requested navigation is impossible, this method has no effect. - * @param {number} relativeIndex Relative history index to which the webview should be navigated. For example, a value of 2 will navigate forward 2 history entries if possible; a value of -3 will navigate backward 3 entries. + * Navigates to a history entry using a history index relative to the current navigation. + * If the requested navigation is impossible, this method has no effect. + * @param relativeIndex Relative history index to which the webview should be navigated. + * For example, a value of 2 will navigate forward 2 history entries if possible; + * a value of -3 will navigate backward 3 entries. * @param callback */ go(relativeIndex: number, callback?: (success: boolean) => void): void; /** - * @description Injects CSS into the guest page. - * @param details Details of the CSS to insert. + * Injects CSS into the guest page. + * @param details Details of the CSS to insert. * @param callback */ insertCSS(details: InjectDetails, callback?: () => void): void; - /** - * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). - */ + /** Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. */ isUserAgentOverridden(): void; - /** - * @description Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. - */ + /** Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. */ print(): void; - /** - * @description Reloads the current top-level page. - */ + /** Reloads the current top-level page. */ reload(): void; /** - * @description Removes content scripts from a webview. - * @description The following example removes 'myRule' which was added before. - * @example webview.removeContentScripts(['myRule']); - * @description You can remove all the rules by calling: - * @example webview.removeContentScripts(); - * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. + * Removes content scripts from a webview. + * The following example removes 'myRule' which was added before. + * @example webview.removeContentScripts(['myRule']); + * @description You can remove all the rules by calling: + * @example webview.removeContentScripts(); + * @todo TODO LIST FIX + * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. */ removeContentScripts(scriptNameList?: any[]): void; /** - * @description Override the user agent string used by the webview for guest page requests. - * @param {string} userAgent The user agent string to use. + * Override the user agent string used by the webview for guest page requests. + * @param userAgent The user agent string to use. */ setUserAgentOverride(userAgent: string): void; /** - * @description Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see $(ref:webviewTag.ZoomMode)). - * @param {number} zoomFactor The new zoom factor. - * @param callback + * Changes the zoom factor of the page. + * The scope and persistence of this change + * are determined by the webview's current zoom mode. + * @param zoomFactor The new zoom factor. + * @param [callback] */ setZoom(zoomFactor: number, callback?: () => void): void; /** - * @description Sets the zoom mode of the webview. - * @param ZoomMode Defines how zooming is handled in the webview. - * @param callback + * Sets the zoom mode of the webview. + * @param ZoomMode Defines how zooming is handled in the webview. + * @param [callback] */ setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; - /** - * @description Stops loading the current webview navigation if in progress. - */ + /** Stops loading the current webview navigation if in progress. */ stop(): void; /** - * @description Ends the current find session (clearing all highlighting) and cancels all find requests in progress. - * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. + * @todo TODO Fix action param + * Ends the current find session (clearing all highlighting) + * and cancels all find requests in progress. + * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. */ stopFinding(action?: string): void; /** - * @description Loads a data URL with a specified base URL used for relative links. Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. - * @param {string} dataUrl The data URL to load. - * @param {string} baseUrl The base URL that will be used for relative links. - * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). + * Loads a data URL with a specified base URL used for relative links. + * Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. + * @param {string} dataUrl The data URL to load. + * @param {string} baseUrl The base URL that will be used for relative links. + * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). */ loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; /** - * @description Forcibly kills the guest web page's renderer process. This may affect multiple webview tags in the current app if they share the same process, but it will not affect webview tags in other apps. + * Forcibly kills the guest web page's renderer process. + * This may affect multiple webview tags in the current app if they share the same process, + * but it will not affect webview tags in other apps. */ terminate(): void; /** - * @description Fired when the guest window attempts to close itself.

The following example code navigates the webview to about:blank when the guest attempts to close itself.

webview.addEventListener('close', function() {
-              webview.src = 'about:blank';
-            });
+ * Fired when the guest window attempts to close itself. + * The following example code navigates the webview to + * about:blank when the guest attempts to close itself. + * @example + * webview.addEventListener('close', function() { + * webview.src = 'about:blank'; + * }); */ - close(event: chrome.events.Event): void; /** - * @description Fired when the guest window logs a console message.

The following example code forwards all log messages to the embedder's console without regard for log level or other properties.

webview.addEventListener('consolemessage', function(e) {
-              console.log('Guest page logged a message: ', e.message);
-            });
- * @param callback + * Fired when the guest window logs a console message. + * The following example code forwards all log messages + * to the embedder's console without regard for log level + * or other properties. + * @example + * webview.addEventListener('consolemessage', function(e) { + * console.log('Guest page logged a message: ', e.message); + * }); */ - - consolemessage: chrome.events.Event; + consolemessage: chrome.events.Event; /** - * @description Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads.

The following example code modifies the default font size of the guest's body element after the page loads:

webview.addEventListener('contentload', function() {
-              webview.executeScript({ code: 'document.body.style.fontSize = '42px'' });
-            });
+ * Fired when the guest window fires a load event, i.e., when a new document is loaded. + * This does *not* include page navigation within the current document or asynchronous + * resource loads. The following example code modifies the default font size of the + * guest's body element after the page loads: + * @example + * webview.addEventListener('contentload', function() { + * webview.executeScript({ code: 'document.body.style.fontSize = '42px'' }); + * }); */ - contentload: (event: chrome.events.Event) => void; /** - * @description Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

+ * Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

* @param callback */ - dialog: chrome.events.Event; + dialog: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has exited.

The following example code will show a farewell message whenever the guest page crashes:

webview.addEventListener('exit', function(e) {
-              if (e.reason === 'crash') {
-                webview.src = 'data:text/plain,Goodbye, world!';
-              }
-            });
+ * Fired when the process rendering the guest web content has exited. + * The following example code will show a farewell message whenever + * the guest page crashes: + * @example + * webview.addEventListener('exit', function(e) { + * if (e.reason === 'crash') { + * webview.src = 'data:text/plain,Goodbye, world!'; + * } + * }); * @param callback */ - exit: chrome.events.Event; + exit: chrome.events.Event; /** - * @description Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. + * Fired when new find results are available for an active find request. + * This might happen multiple times for a single find request as matches are found. + */ + + findupdate: chrome.events.Event; + + /** + * Fired when a top-level load has aborted without committing. + * An error message will be printed to the console unless the event is default-prevented. + * @requires Note: When a resource load is aborted, + * a loadabort event will eventually be followed by a loadstop event, + * even if all committed loads since the last loadstop event (if any) + * were aborted. + * @requires Note: When the load of either an about URL + * or a JavaScript URL is aborted, loadabort will be fired + * and then the webview will be navigated to 'about:blank'. + */ + + loadabort: chrome.events.Event; + + /** + * Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. * @param callback */ - findupdate: chrome.events.Event; + loadcommit: chrome.events.Event; /** - * @description Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented.

Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted.

Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'.

+ * Fired when a top-level load request has redirected to a different URL. * @param callback */ - loadabort: chrome.events.Event; + loadredirect: chrome.events.Event; /** - * @description Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. + * Fired when a load has begun. * @param callback */ - loadcommit: chrome.events.Event; + loadstart: chrome.events.Event; /** - * @description Fired when a top-level load request has redirected to a different URL. - * @param callback + * Fired when all frame-level loads in a guest page (including all its subframes) + * have completed. This includes navigation within the current document as well + * as subframe document-level loads, but does not(!) include asynchronousresource + * loads. This event fires every time the number of document-level loads transitions + * from one (or more) to zero. For example, if a page that has already finished loading + * (i.e., loadstop already fired once) creates a new iframe which loads a page, + * then a second loadstop will fire when the iframe page load completes. This pattern + * is commonly observed on pages that load ads. + * @requires Note: When a committed load is aborted, + * a loadstop event will eventually follow a loadabort event, + * even if all committed loads since the last loadstop event (if any) were aborted. */ - - loadredirect: chrome.events.Event; - - /** - * @description Fired when a load has begun. - * @param callback - */ - - loadstart: chrome.events.Event; - - /** - * @description Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.

Note: When a committed load is aborted, a loadstop event will eventually follow a loadabort event, even if all committed loads since the last loadstop event (if any) were aborted.

- */ - loadstop(event: chrome.events.Event): void; /** - * @description Fired when the guest page attempts to open a new browser window.

The following example code will create and navigate a new webview in the embedder for each requested new window:

webview.addEventListener('newwindow', function(e) {
-              var newWebview = document.createElement('webview');
-              document.body.appendChild(newWebview);
-              e.window.attach(newWebview);
-            });
- * @param callback + * Fired when the guest page attempts to open a new browser window. + * The following example code will create and navigate a new webview + * in the embedder for each requested new window: + * @example + * webview.addEventListener('newwindow', function(e) { + * const newWebview = document.createElement('webview'); + * document.body.appendChild(newWebview); + * e.window.attach(newWebview); + * }); */ - newwindow: chrome.events.Event; + newwindow: chrome.events.Event; /** - * @description Fired when the guest page needs to request special permission from the embedder.

The following example code will grant the guest page access to the webkitGetUserMedia API. Note that an app using this example code must itself specify audioCapture and/or videoCapture manifest permissions:

webview.addEventListener('permissionrequest', function(e) {
-              if (e.permission === 'media') {
-                e.request.allow();
-              }
-            });
- * @param callback + * Fired when the guest page needs to request special permission from the embedder. + * The following example code will grant the guest page access to the webkitGetUserMedia API. + * Note that an app using this example code must itself specify audioCapture and / or + * videoCapture manifest permissions: + * @example + * webview.addEventListener('permissionrequest', function(e) { + * if (e.permission === 'media') { + * e.request.allow(); + * } + * }); */ - permissionrequest: chrome.events.Event; + permissionrequest: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has become responsive again after being unresponsive.

The following example code will fade the webview element in or out as it becomes responsive or unresponsive:

webview.style.webkitTransition = 'opacity 250ms';
-            webview.addEventListener('unresponsive', function() {
-              webview.style.opacity = '0.5';
-            });
-            webview.addEventListener('responsive', function() {
-              webview.style.opacity = '1';
-            });
- * @param callback + * Fired when the process rendering the guest web content has become + * responsive again after being unresponsive. + * + * The following example code will fade the webview element + * in or out as it becomes responsive or unresponsive: + * + * @example + * webview.style.webkitTransition = 'opacity 250ms'; + * webview.addEventListener('unresponsive', function() { + * webview.style.opacity = '0.5'; + * }); + * webview.addEventListener('responsive', function() { + * webview.style.opacity = '1'; + * }); */ - - responsive: chrome.events.Event; - + responsive: chrome.events.Event; /** - * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. - * @param callback + * Fired when the embedded web content has been resized via autosize. + * @requires Note: Only fires if autosize is enabled. */ - - sizechanged: chrome.events.Event; - + sizechanged: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. - * @param callback + * Fired when the process rendering the guest web content has become unresponsive. + * This event will be generated once with a matching responsive event if the guest begins to respond again. */ - - unresponsive: chrome.events.Event; - + unresponsive: chrome.events.Event; /** - * @description Fired when the page's zoom changes. - * @param callback + * Fired when the page's zoom changes. */ - - zoomchange: chrome.events.Event; + zoomchange: chrome.events.Event; } - /**Options that determine what data should be cleared by clearData. */ + /** Options that determine what data should be cleared by clearData. */ interface ClearDataOptions { - /** - * @description Clear data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data). + * Clear data accumulated on or after this date, + * represented in milliseconds since the epoch + * (accessible via the getTime method of the JavaScript Date object). + * If absent, defaults to 0 (which would remove all browsing data). + * @default 0 */ - since?: number; + since?: integer; } - /**A set of data types. Missing properties are interpreted as false. */ + /** A set of data types. Missing properties are interpreted as false. */ interface ClearDataTypeSet { - + /** Websites' appcaches. */ + appcache?: boolean; /** - * @description Websites' appcaches. + * The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. + * @since Available since Chrome 43. */ - appcache?: boolean - - /** - * @description Since Chrome 43. The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. - */ - cache?: boolean - - /** - * @description The partition's cookies. - */ - cookies?: boolean - - /** - * @description The partition's session cookies. - */ - sessionCookies?: boolean - - /** - * @description The partition's persistent cookies. - */ - persistentCookies?: boolean - - /** - * @description Websites' filesystems. - */ - fileSystems?: boolean - - /** - * @description Websites' IndexedDB data. - */ - indexedDB?: boolean - - /** - * @description Websites' local storage data. - */ - localStorage?: boolean - - /** - * @description Websites' WebSQL data. - */ - webSQL?: boolean + cache?: boolean; + /** The partition's cookies. */ + cookies?: boolean; + /** The partition's session cookies. */ + sessionCookies?: boolean; + /** The partition's persistent cookies. */ + persistentCookies?: boolean; + /** Websites' filesystems. */ + fileSystems?: boolean; + /** Websites' IndexedDB data. */ + indexedDB?: boolean; + /** Websites' local storage data. */ + localStorage?: boolean; + /** Websites' WebSQL data. */ + webSQL?: boolean; } /** - * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts. - * Enum values: - * 'all' - * 'page' - * 'frame' - * 'selection' - * 'link' - * 'editable' - * 'image' - * 'video' - * 'audio' */ - export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio'; - /**Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ + * The different contexts a menu can appear in. + * Specifying 'all' is equivalent to the combination of all other contexts. + **/ + type ContextType = + 'all' | + 'page' | + 'frame' | + 'selection' | + 'link' | + 'editable' | + 'image' | + 'video' | + 'audio'; + /** + * Details of the script or CSS to inject. + * Either the code or the file property must be set, + * but both may not be set at the same time. + **/ interface InjectDetails { - /** - * @description JavaScript or CSS code to inject. Warning: Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. + * JavaScript or CSS code to inject. + * Warning: Be careful using the code parameter. + * Incorrect use of it may open your app to xss attacks. */ - code?: string + code?: string; - /** - * @description JavaScript or CSS file to inject. - */ + /** JavaScript or CSS file to inject. */ file?: string } - /**The type of injection item: code or a set of files. */ + /** The type of injection item: code or a set of files. */ interface InjectionItems { - - /** - * @description JavaScript code or CSS to be injected into matching pages. - */ + /** JavaScript code or CSS to be injected into matching pages. */ code?: string - /** - * @description The list of JavaScript or CSS files to be injected into matching pages. These are injected in the order they appear in this array. + * The list of JavaScript or CSS files to be injected into matching pages. + * These are injected in the order they appear in this array. */ files?: any[] } - /**Details of the content script to inject. Refer to the content scripts documentation for more details. */ + /** Details of the content script to inject. **/ interface ContentScriptDetails { - - /** - * @description The name of the content script to inject. - */ + /** The name of the content script to inject. */ name: string - /** - * @description Specifies which pages this content script will be injected into. - */ + /** Specifies which pages this content script will be injected into. */ matches: any[] - /** - * @description Excludes pages that this content script would otherwise be injected into. - */ + /** Excludes pages that this content script would otherwise be injected into. */ exclude_matches?: any[] /** - * @description Whether to insert the content script on about:blank and about:srcdoc. Content scripts will only be injected on pages when their inherit URL is matched by one of the declared patterns in the matches field. The inherit URL is the URL of the document that created the frame or window. Content scripts cannot be inserted in sandboxed frames. + * Whether to insert the content script on about:blank and about:srcdoc. + * Content scripts will only be injected on pages when their inherit URL + * is matched by one of the declared patterns in the matches field. + * The inherit URL is the URL of the document that created the frame or window. + * Content scripts cannot be inserted in sandboxed frames. */ - match_about_blank?: boolean + match_about_blank?: boolean; /** - * @description The CSS code or a list of CSS files to be injected into matching pages. These are injected in the order they appear, before any DOM is constructed or displayed for the page. + * The CSS code or a list of CSS files to be injected into matching pages. + * These are injected in the order they appear, + * before any DOM is constructed or displayed for the page. */ - css?: InjectionItems + css?: InjectionItems; /** - * @description The JavaScript code or a list of JavaScript files to be injected into matching pages. These are injected in the order they appear. + * The JavaScript code or a list of JavaScript files to be injected into matching pages. + * These are injected in the order they appear. */ - js?: InjectionItems + js?: InjectionItems; /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. + * The soonest that the JavaScript or CSS will be injected into the tab. + * Defaults to 'document_idle'. */ run_at?: chrome.extensionTypes.RunAt; /** - * @description If all_frames is true, this implies that the JavaScript or CSS should be injected into all frames of current page. By default, all_frames is false and the JavaScript or CSS is only injected into the top frame. + * If all_frames is true, this implies that the JavaScript or CSS should be injected into all frames of current page. + * By default, all_frames is false and the JavaScript or CSS is only injected into the top frame. + * @default false */ all_frames?: boolean; /** - * @description Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword. + * Applied after matches to include only those URLs that also match this glob. + * Intended to emulate the @include Greasemonkey keyword. */ include_globs?: string[]; /** - * @description Applied after matches to exclude URLs that match this glob. Intended to emulate the @exclude Greasemonkey keyword. + * Applied after matches to exclude URLs that match this glob. + * Intended to emulate the @exclude Greasemonkey keyword. */ exclude_globs?: string[]; } - /**@todo Add documentation */ + /** @todo TODO Add documentation */ interface ContextMenuCreateProperties { /** - * @description The type of menu item. Defaults to 'normal' if not specified. + * The type of menu item. Defaults to 'normal' if not specified. */ - type?: chrome.contextMenus.ItemType + type?: chrome.contextMenus.ItemType; /** - * @description The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. + * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. */ - id?: string + id?: string; /** - * @description The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. + * The text to be displayed in the item; this is -required- unless type is 'separator'. + * When the context is 'selection', you can use %s within the string to show the selected text. + * For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects + * the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ - title?: string + title?: string; /** - * @description The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. + * The initial state of a checkbox or radio item: + * true for selected and false for unselected. + * Only one radio item can be selected at a time in a given group of radio items. */ checked?: boolean /** - * @description List of contexts this menu item will appear in. Defaults to ['page'] if not specified. + * List of contexts this menu item will appear in. + * Defaults to ['page'] if not specified. */ - contexts?: any[] + contexts?: any[]; /** - * @description A function that will be called back when the menu item is clicked. - * @param callback + * A function that will be called back when the menu item is clicked. */ onclick?: (info: any) => void /** - * @description The ID of a parent menu item; this makes the item a child of a previously added item. + * The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: number | string + parentId?: number | string; /** - * @description Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. + * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. */ - documentUrlPatterns?: any[] + documentUrlPatterns?: any[]; /** - * @description Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. + * Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: any[] + targetUrlPatterns?: any[]; /** - * @description Whether this context menu item is enabled or disabled. Defaults to true. + * Whether this context menu item is enabled or disabled. Defaults to true. */ - enabled?: boolean + enabled?: boolean; } /**@todo Add documentation */ interface ContextMenuUpdateProperties { - - /** - * @description The type of menu item. - */ + /** The type of menu item. */ type?: chrome.webview.ContextType; - /** - * @description The text to be displayed in the item - */ - title?: string + /** The text to be displayed in the item */ + title?: string; /** - * @description The state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. + * The state of a checkbox or radio item: true for selected and false for unselected. + * Only one radio item can be selected at a time in a given group of radio items. */ - checked?: boolean + checked?: boolean; /** - * @description List of contexts this menu item will appear in. + * List of contexts this menu item will appear in. */ - contexts?: any[] + contexts?: any[]; /** - * @description A function that will be called back when the menu item is clicked. + * A function that will be called back when the menu item is clicked. * @param callback */ - onclick?: (info: any) => void + onclick?: (info: any) => void; /** - * @description The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants. + * The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants. */ - parentId?: number | string + parentId?: number | string; /** - * @description Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. + * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. + * (This applies to frames as well.) */ - documentUrlPatterns?: any[] + documentUrlPatterns?: any[]; /** - * @description Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. + * Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: any[] + targetUrlPatterns?: any[]; /** - * @description Whether this context menu item is enabled or disabled. + * Whether this context menu item is enabled or disabled. */ - enabled?: boolean + enabled?: boolean; } interface ContextMenus { - /** - * @description Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). - * @param {object} createProperties The properties used to create the item - * @param callback + * Creates a new context menu item. Note that if an error occurs during creation, + * you may not find out until the creation callback fires + * (the details will be in chrome.runtime.lastError). + * @param createProperties The properties used to create the item + * @param [callback] */ create(createProperties: object, callback?: () => void): void; /** - * @description Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param {object} updateProperties The properties to update. Accepts the same values as the create function. - * @param callback + * Updates a previously created context menu item. + * @param id The ID of the item to update. + * @param updateProperties The properties to update. Accepts the same values as the create function. + * @param [callback] */ - update(id: number | string, updateProperties: object, callback?: () => void): void; + update(id: integer | string, updateProperties: object, callback?: () => void): void; /** - * @description Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param [callback] */ - remove(menuItemId: number | string, callback?: () => void): void; + remove(menuItemId: integer | string, callback?: () => void): void; /** - * @description Removes all context menu items added to this webview. - * @param callback + * Removes all context menu items added to this webview. + * @param [callback] */ removeAll(callback?: () => void): void; - /** - * @description Fired before showing a context menu on this webview. Can be used to disable this context menu by calling event.preventDefault(). + * Fired before showing a context menu on this webview. + * Can be used to disable this context menu by calling event.preventDefault(). */ - onShow: chrome.events.Event; - + onShow: chrome.events.Event; } - interface IOnShowEvent { - /** - * @description Call this to prevent showing the context menu. - * @memberof IOnShowEvent - */ + interface OnShowEvent { + /** Call this to prevent showing the context menu. */ preventDefault: () => void; } interface ContentWindow { - /** - * @description

Posts a message to the embedded web content as long as the embedded content is displaying a page from the target origin. This method is available once the page has completed loading. Listen for the contentload event and then call the method.

The guest will be able to send replies to the embedder by posting message to event.source on the message event it receives.

This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a message event listener to its own frame.

- * @param message Message object to send to the guest. - * @param {string} targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched. + * Posts a message to the embedded web content as long as the embedded + * content is displaying a page from the target origin. This method is + * available once the page has completed loading. Listen for the + * contentload event and then call the method. + * + * The guest will be able to send replies to the embedder by posting message + * to event.source on the message event it receives. + * + * This API is identical to the HTML5 postMessage API for communication + * between web pages. The embedder may listen for replies by adding + * a message event listener to its own frame. + * + * @param message Message object to send to the guest. + * @param targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched. */ postMessage(message: any, targetOrigin: string): void; - } interface DialogController { - /** - * @description Accept the dialog. Equivalent to clicking OK in an alert, confirm, or prompt dialog. - * @param {string} response The response string to provide to the guest when accepting a prompt dialog. + * Accept the dialog. Equivalent to clicking OK in an alert, confirm, or prompt dialog. + * @param response The response string to provide to the guest when accepting a prompt dialog. */ ok(response?: string): void; - - /** - * @description Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. - */ + /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ cancel(): void; - } - /**Contains all of the results of the find request. */ + /** Contains all of the results of the find request. */ interface FindCallbackResults { - - /** - * @description The number of times searchText was matched on the page. - */ - numberOfMatches: number - - /** - * @description The ordinal number of the current match. - */ - activeMatchOrdinal: number - - /** - * @description Describes a rectangle around the active match in screen coordinates. - */ - selectionRect: SelectionRect - - /** - * @description Indicates whether this find request was canceled. - */ - canceled: boolean + /** The number of times searchText was matched on the page. */ + numberOfMatches: number; + /** The ordinal number of the current match. */ + activeMatchOrdinal: number; + /** Describes a rectangle around the active match in screen coordinates. */ + selectionRect: SelectionRect; + /** Indicates whether this find request was canceled. */ + canceled: boolean; } - /**Options for the find request. */ interface FindOptions { - /** - * @description Flag to find matches in reverse order. The default value is false. + * Flag to find matches in reverse order. + * @default false */ - backward?: boolean - + backward?: boolean; /** - * @description Flag to match with case-sensitivity. The default value is false. + * Flag to match with case-sensitivity. + * @default false */ - matchCase?: boolean + matchCase?: boolean; } interface NewWindow { - /** - * @description Attach the requested target page to an existing webview element. - * @param {object} webview The webview element to which the target page should be attached. + * Attach the requested target page to an existing webview element. + * @param webview The webview element to which the target page should be attached. */ - attach(webview: object): void; - + attach(webview: HTMLWebViewElement): void; /** - * @description Cancel the new window request. + * Cancel the new window request. */ discard(): void; - } - interface MediaPermissionRequest { - - /** - * @description Allow the permission request. - */ + interface PermissionRequestHandler { + /** Allow the permission request. */ allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ + /** Deny the permission request. This is the default behavior if allow is not called. */ deny(): void; - - } - interface GeolocationPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface PointerLockPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface DownloadPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface FileSystemPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - - } - interface FullscreenPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - - } - interface LoadPluginPermissionRequest { - - /** - * @description Allow the permission request. This is the default behavior if deny is not called.. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - } /** - * Fescribes a rectangle in screen coordinates. + * Describes a rectangle in screen coordinates. * The containment semantics are array-like; that is, the coordinate (left, top) is considered to be contained by the rectangle, * but the coordinate (left + width, top) is not. **/ interface SelectionRect { - - /** - * @description Distance from the left edge of the screen to the left edge of the rectangle. - */ - left: number - - /** - * @description Distance from the top edge of the screen to the top edge of the rectangle. - */ - top: number - - /** - * @description Width of the rectangle. - */ - width: number - - /** - * @description Height of the rectangle. - */ - height: number + /** Distance from the left edge of the screen to the left edge of the rectangle. */ + left: number; + /** Distance from the top edge of the screen to the top edge of the rectangle. */ + top: number; + /** Width of the rectangle. */ + width: number; + /** Height of the rectangle. */ + height: number; } /** - * @description Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts.

To illustrate how usage differs from the extensions webRequest API, consider the following example code which blocks any guest requests for URLs which match *://www.evil.com/*:

webview.request.onBeforeRequest.addListener(
-         * @example function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
-         * @description Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
-         * @see http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest
-         * @description Note that conditions and actions for declarative webview webRequests should be instantiated from their chrome.webViewRequest.* counterparts. The following example code declaratively blocks all requests to 'example.com' on the webview myWebview:
-         * @example var rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
+         * Interface which provides access to webRequest events on the guest page.
+         * @see[chrome.webRequest]{@link http://developer.chrome.com/extensions/webRequest}
+         * extensions API for details on webRequest life cycle and related concepts.
+         *
+         * To illustrate how usage differs from the extensions webRequest API,
+         * consider the following example code which blocks any guest requests
+         * for URLs which match *://www.evil.com/*:
+         * @example
+         * webview.request.onBeforeRequest.addListener(
+         *   function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
+         * @description
+         * Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
+         * @see[Docs]{@link http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest}
+         * @description
+         * Note that conditions and actions for declarative webview webRequests should be instantiated
+         * from their chrome.webViewRequest.* counterparts. The following example code declaratively
+         * blocks all requests to 'example.com' on the webview myWebview:
+         * @example const rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
          **/
         interface WebRequestEventInterface {
+            /** @todo TODO */
         }
         /**
         * Defines the how zooming is handled in the webview.
         * Enum values:
         * 'per-origin'
-        * * Zoom changes will persist in the zoomed page's origin, i.e. all other webviews in the same partition that are navigated to that same origin will be zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they will all be zoomed to the same zoom factor.
+        *   > Zoom changes will persist in the zoomed page's origin,
+        *     i.e. all other webviews in the same partition that are
+        *     navigated to that same origin will be zoomed as well.
+        *     Moreover, per-origin zoom changes are saved with the origin,
+        *     meaning that when navigating to other pages in the same origin,
+        *     they will all be zoomed to the same zoom factor.
         * 'per-view'
-        * * Zoom changes only take effect in this webview, and zoom changes in other webviews will not affect the zooming of this webview. Also, per-view zoom changes are reset on navigation; navigating a webview will always load pages with their per-origin zoom factors (within the scope of the partition).
+        *   > Zoom changes only take effect in this webview,
+        *     and zoom changes in other webviews will not affect
+        *     the zooming of this webview. Also, per-view zoom
+        *     changes are reset on navigation; navigating a webview
+        *     will always load pages with their per-origin zoom factors
+        *     (within the scope of the partition).
         * 'disabled'
-        * * Disables all zooming in the webview. The content will revert to the default zoom level, and all attempted zoom changes will be ignored. */
-        export type ZoomMode = 'per-origin' | 'per-view' | 'disabled';
-
-        export enum ConsoleMessageLevel {
-            LOG_VERBOSE = -1,
-            LOG_INFO = 0,
-            LOG_WARNING = 1,
-            LOG_ERROR = 2
-        }
-        interface IConsoleMessage {
-
+        *   > Disables all zooming in the webview.
+        *     The content will revert to the default zoom level,
+        *     and all attempted zoom changes will be ignored.
+        **/
+        type ZoomMode =
+            'per-origin' |
+            'per-view' |
+            'disabled';
+        type ConsoleMessageLevel = -1 | 0 | 1 | 2;
+        type LoadAbortReason =
+            'ERR_ABORTED' |
+            'ERR_INVALID_URL' |
+            'ERR_DISALLOWED_URL_SCHEME' |
+            'ERR_BLOCKED_BY_CLIENT' |
+            'ERR_ADDRESS_UNREACHABLE' |
+            'ERR_EMPTY_RESPONSE' |
+            'ERR_FILE_NOT_FOUND' |
+            'ERR_UNKNOWN_URL_SCHEME';
+        interface ConsoleMessage {
             /**
-            * @description The severity level of the log message. Ranges from -1 to 2. LOG_VERBOSE (console.debug) = -1, LOG_INFO (console.log, console.info) = 0, LOG_WARNING (console.warn) = 1, LOG_ERROR (console.error) = 2.
+             * The severity level of the log message.
+             * Ranges from -1 to 2.
+             * LOG_VERBOSE (console.debug) = -1
+             * LOG_INFO (console.log, console.info) = 0
+             * LOG_WARNING (console.warn) = 1
+             * LOG_ERROR (console.error) = 2
              */
             level: ConsoleMessageLevel;
-
-            /**
-            * @description The logged message contents.
-             */
-            message: string
-
-            /**
-            * @description The line number of the message source.
-             */
-            line: number
-
-            /**
-            * @description A string identifying the resource which logged the message.
-             */
-            sourceId: string
+            /** The logged message contents. */
+            message: string;
+            /** The line number of the message source. */
+            line: number;
+            /** A string identifying the resource which logged the message. */
+            sourceId: string;
         }
-        interface IDialog {
+        type DialogMessageType =
+            'alert' |
+            'confirm' |
+            'prompt';
 
+        interface Dialog {
             /**
-            * @description The type of modal dialog requested by the guest.
+             * The type of modal dialog requested by the guest.
              */
-            messageType: 'alert' | 'confirm' | 'prompt'
-
+            messageType: DialogMessageType;
             /**
-            * @description The text the guest attempted to display in the modal dialog.
+             * The text the guest attempted to display in the modal dialog.
              */
-            messageText: string
-
+            messageText: string;
             /**
-            * @description An interface that can be used to respond to the guest's modal request.
+             * An interface that can be used to respond to the guest's modal request.
              */
-            dialog: DialogController
+            dialog: DialogController;
         }
-        interface IExit {
-
-            /**
-            * @description Chrome's internal ID of the process that exited.
-             */
-            processID: number
-
-            /**
-            * @description String indicating the reason for the exit.
-             */
-            reason: 'normal' | 'abnormal' | 'crash' | 'kill'
+        type ExitReason =
+            'normal' |
+            'abnormal' |
+            'crash' |
+            'kill';
+        interface Exit {
+            /** Chrome's internal ID of the process that exited. */
+            processID: number;
+            /** String indicating the reason for the exit. */
+            reason: ExitReason;
         }
-        interface IFindupdate {
-
+        interface FindUpdate {
             /**
-            * @description The string that is being searched for in the page.
+             * The string that is being searched for in the page.
              */
-            searchText: string
-
+            searchText: string;
             /**
-            * @description The number of matches found for searchText on the page so far.
+             * The number of matches found for searchText on the page so far.
              */
-            numberOfMatches: number
-
+            numberOfMatches: number;
             /**
-            * @description The ordinal number of the current active match, if it has been found. This will be 0 until then.
+             * The ordinal number of the current active match,
+             * if it has been found. This will be 0 until then.
              */
-            activeMatchOrdinal: number
-
+            activeMatchOrdinal: number;
             /**
-            * @description Describes a rectangle around the active match, if it has been found, in screen coordinates.
+             * Describes a rectangle around the active match,
+             * if it has been found, in screen coordinates.
              */
-            selectionRect: SelectionRect
-
+            selectionRect: SelectionRect;
             /**
-            * @description Indicates whether the find request was canceled.
+             * Indicates whether the find request was canceled.
              */
-            canceled: boolean
-
+            canceled: boolean;
             /**
-            * @description Indicates that all find requests have completed and that no more findupdate events will be fired until more find requests are made.
+             * Indicates that all find requests have completed
+             * and that no more findupdate events will be fired
+             * until more find requests are made.
              */
-            finalUpdate: string
+            finalUpdate: string;
         }
-        interface ILoadabort {
-
+        interface LoadAbort {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load was top-level or in a subframe. */
+            isTopLevel: boolean;
             /**
-            * @description Requested URL.
+             * Unique integer ID for the type of abort.
+             * Note that this ID is `not` guaranteed to
+             * remain backwards compatible between releases.
+             * You must not act based upon this specific integer.
              */
-            url: string
-
+            code: integer;
             /**
-            * @description Whether the load was top-level or in a subframe.
+             * String indicating what type of abort occurred.
+             * This string is `not` guaranteed to remain
+             * backwards compatible between releases.
+             * You must not parse and act based upon its content.
+             * It is also possible that, in some cases,
+             * an error not listed here could be reported.
              */
-            isTopLevel: boolean
-
-            /**
-            * @description Unique integer ID for the type of abort. Note that this ID is not guaranteed to remain backwards compatible between releases. You must not act based upon this specific integer.
-             */
-            code: number
-
-            /**
-            * @description String indicating what type of abort occurred. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. It is also possible that, in some cases, an error not listed here could be reported.
-             */
-            reason: 'ERR_ABORTED' | 'ERR_INVALID_URL' | 'ERR_DISALLOWED_URL_SCHEME' | 'ERR_BLOCKED_BY_CLIENT' | 'ERR_ADDRESS_UNREACHABLE' | 'ERR_EMPTY_RESPONSE' | 'ERR_FILE_NOT_FOUND' | 'ERR_UNKNOWN_URL_SCHEME'
+            reason: LoadAbortReason;
         }
-        interface ILoadcommit {
-
-            /**
-            * @description The URL that committed.
-             */
-            url: string
-
-            /**
-            * @description Whether the load is top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadCommit {
+            /** The URL that committed. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**ILoadredirect (Auto generated interface) */
-        interface ILoadredirect {
-
-            /**
-            * @description The requested URL before the redirect.
-             */
-            oldUrl: string
-
-            /**
-            * @description The new URL after the redirect.
-             */
-            newUrl: string
-
-            /**
-            * @description Whether or not the redirect happened at top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadRedirect {
+            /** The requested URL before the redirect. */
+            oldUrl: string;
+            /** The new URL after the redirect. */
+            newUrl: string;
+            /** Whether or not the redirect happened at top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**ILoadstart (Auto generated interface) */
-        interface ILoadstart {
-
-            /**
-            * @description Requested URL.
-             */
-            url: string
-
-            /**
-            * @description Whether the load is top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadStart {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**INewwindow (Auto generated interface) */
-        interface INewwindow {
-
+        type WindowOpenDisposition =
+            'ignore' |
+            'save_to_disk' |
+            'current_tab' |
+            'new_background_tab' |
+            'new_foreground_tab' |
+            'new_window' |
+            'new_popup';
+        interface NewWindow {
             /**
-            * @description An interface that can be used to either attach the requested target page to an existing webview element or explicitly discard the request.
-             */
-            window: NewWindow
+             * An interface that can be used to either attach the requested
+             * target page to an existing webview element or explicitly
+             * discard the request.
+             **/
+            window: NewWindow;
 
-            /**
-            * @description The target URL requested for the new window.
-             */
-            targetUrl: string
+            /** The target URL requested for the new window. */
+            targetUrl: string;
 
-            /**
-            * @description The initial width requested for the new window.
-             */
-            initialWidth: number
+            /** The initial width requested for the new window. */
+            initialWidth: number;
 
-            /**
-            * @description The initial height requested for the new window.
-             */
-            initialHeight: number
+            /** The initial height requested for the new window. */
+            initialHeight: number;
 
-            /**
-            * @description The requested name of the new window.
-             */
-            name: string
+            /** The requested name of the new window. */
+            name: string;
 
-            /**
-            * @description The requested disposition of the new window.
-             */
-            windowOpenDisposition: 'ignore' | 'save_to_disk' | 'current_tab' | 'new_background_tab' | 'new_foreground_tab' | 'new_window' | 'new_popup'
+            /** The requested disposition of the new window. */
+            windowOpenDisposition: WindowOpenDisposition;
         }
-        interface IPermissionrequest {
-
-            /**
-            * @description The type of permission being requested.
-             */
-            permission: 'media' | 'geolocation' | 'pointerLock' | 'download' | 'loadplugin' | 'filesystem' | 'fullscreen'
-
-            /**
-            * @description An object which holds details of the requested permission. Depending on the type of permission requested, this may be a $(ref:webviewTag.MediaPermissionRequest), $(ref:webviewTag.GeolocationPermissionRequest), $(ref:webviewTag.PointerLockPermissionRequest), $(ref:webviewTag.DownloadPermissionRequest), $(ref:webviewTag.LoadPluginPermissionRequest), or $(ref:webviewTag.FullscreenPermissionRequest).
-             */
-            request: GeolocationPermissionRequest | PointerLockPermissionRequest | DownloadPermissionRequest | LoadPluginPermissionRequest | FullscreenPermissionRequest;
+        type RequestedPermission =
+            'media' |
+            'geolocation' |
+            'pointerLock' |
+            'download' |
+            'loadplugin' |
+            'filesystem' |
+            'fullscreen';
+        interface PermissionRequest {
+            /** The type of permission being requested. */
+            permission: RequestedPermission;
+            /** An object which holds details of the requested permission.*/
+            request: PermissionRequestHandler;
         }
-
-        /**IResponsive (Auto generated interface) */
-        interface IResponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that became responsive.
-             */
-            processID: number
+        interface ProcessResponsive {
+            /** Chrome's internal ID of the process that became responsive. */
+            processID: number;
         }
-        /**ISizechanged (Auto generated interface) */
-        interface ISizechanged {
-
-            /**
-            * @description Old width of embedded web content.
-             */
-            oldWidth: number
-
-            /**
-            * @description Old height of embedded web content.
-             */
-            oldHeight: number
-
-            /**
-            * @description New width of embedded web content.
-             */
-            newWidth: number
-
-            /**
-            * @description New height of embedded web content.
-             */
-            newHeight: number
+        interface SizeChanged {
+            /** Old width of embedded web content. */
+            oldWidth: number;
+            /** Old height of embedded web content. */
+            oldHeight: number;
+            /** New width of embedded web content. */
+            newWidth: number;
+            /** New height of embedded web content. */
+            newHeight: number;
         }
-        /**IUnresponsive (Auto generated interface) */
-        interface IUnresponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that has become unresponsive.
-             */
-            processID: number
+        interface ProcessUnresponsive {
+            /** Chrome's internal ID of the process that has become unresponsive. */
+            processID: number;
         }
-        /**IZoomchange (Auto generated interface) */
-        interface IZoomchange {
-
-            /**
-            * @description The page's previous zoom factor.
-             */
-            oldZoomFactor: number
-
-            /**
-            * @description The new zoom factor that the page was zoomed to.
-             */
-            newZoomFactor: number
+        interface ZoomChange {
+            /** The page's previous zoom factor. */
+            oldZoomFactor: number;
+            /** The new zoom factor that the page was zoomed to. */
+            newZoomFactor: number;
         }
-
     }
 
+    /////////////
+    // METHODS //
+    /////////////
+
+    /**
+     * Different page speed and load metrics
+     */
+    function csi(): {
+        onloadT: number;
+        pageT: number;
+        startE: number;
+        tran: number;
+    }
+
+    /**
+     * @deprecated Deprecated in Chrome 64.
+     * chrome.loadTimes() is a non-standard API that exposes loading metrics
+     * and network information to developers in order to help them better
+     * understand their site's performance in the real world.
+     * @see[Use this instead]{@link https://www.w3.org/TR/navigation-timing-2/}
+     * @see[Deprecation article]{@link https://developers.google.com/web/updates/2017/12/chrome-loadtimes-deprecated}
+     */
+    function loadTimes(): chrome.deprecatedButUsable;
 }
 
 /////////////////////
diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts
index c0dc6402a6..3babb0b80e 100644
--- a/types/chrome-apps/test/index.ts
+++ b/types/chrome-apps/test/index.ts
@@ -1,8 +1,8 @@
 import runtime = chrome.app.runtime;
-import cwindow = chrome.app.window;
+const cwindow = chrome.app.window;
 
-const createOptions: cwindow.CreateWindowOptions = {
-    id: "My Window",
+const createOptions: chrome.app.CreateWindowOptions = {
+    id: 'My Window',
     bounds: {
         left: 0,
         top: 0,
@@ -14,7 +14,7 @@ const createOptions: cwindow.CreateWindowOptions = {
 
 //Create new window on app launch
 chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchData) {
-    chrome.app.window.create('app/url', createOptions, function (created_window: cwindow.AppWindow) {
+    chrome.app.window.create('app/url', createOptions, function (created_window: chrome.app.AppWindow) {
         return;
     });
 });
@@ -22,9 +22,9 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa
 chrome.app.runtime.onRestarted.addListener(function () { return; });
 
 // retrieving windows
-var currentWindow: cwindow.AppWindow = chrome.app.window.current();
-var otherWindow: cwindow.AppWindow = chrome.app.window.get('some-string');
-var allWindows: cwindow.AppWindow[] = chrome.app.window.getAll();
+var currentWindow: chrome.app.AppWindow = chrome.app.window.current();
+var otherWindow: chrome.app.AppWindow = chrome.app.window.get('some-string');
+var allWindows: chrome.app.AppWindow[] = chrome.app.window.getAll();
 
 // listening to window events
 currentWindow.onBoundsChanged.addListener(function () { return; });
@@ -42,11 +42,11 @@ var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(
 
 function test_fileSystem(): void {
     var accepts: chrome.fileSystem.AcceptOptions[] = [
-        { mimeTypes: ["text/*"], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
+        { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
     ];
     var chooseOption: chrome.fileSystem.ChooseEntryOptions = {
-        type: "openFile",
-        suggestedName: "foo.txt",
+        type: 'openFile',
+        suggestedName: 'foo.txt',
         accepts: accepts,
         acceptsAllTypes: false,
         acceptsMultiple: false
@@ -98,7 +98,7 @@ function test_socketsTcp(): void {
     chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { });
 
     // connect
-    chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { });
+    chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { });
 
     // disconnect
     chrome.sockets.tcp.disconnect(socketId);
@@ -132,7 +132,7 @@ function testSocketsTcpTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test",
+        name: 'test',
         bufferSize: 1024
     };
 
@@ -146,11 +146,11 @@ function testSocketsTcpTypes(): void {
         connected: false
     };
 
-    socketInfo.name = "test";
+    socketInfo.name = 'test';
     socketInfo.bufferSize = 1024;
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
-    socketInfo.peerAddress = "192.168.0.3";
+    socketInfo.peerAddress = '192.168.0.3';
     socketInfo.peerPort = 1000;
 }
 
@@ -178,10 +178,10 @@ function test_socketsUdp(): void {
     chrome.sockets.udp.setPaused(socketId, true, () => { });
 
     // bind
-    chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { });
+    chrome.sockets.udp.bind(socketId, '0.0.0.0', 8080, (result: number) => { });
 
     // send
-    chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { });
+    chrome.sockets.udp.send(socketId, buffer, '172.21.0.1', 10080, (info: chrome.sockets.udp.SendInfo) => { });
 
     // close
     chrome.sockets.udp.close(socketId);
@@ -194,10 +194,10 @@ function test_socketsUdp(): void {
     chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { });
 
     // joinGroup
-    chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { });
+    chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { });
 
     // leaveGroup
-    chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { });
+    chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { });
 
     // setMulticastTimeToLive
     chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { });
@@ -223,7 +223,7 @@ function testSocketsUdpTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test",
+        name: 'test',
         bufferSize: 1024
     };
 
@@ -236,9 +236,9 @@ function testSocketsUdpTypes(): void {
         paused: true
     };
 
-    socketInfo.name = "test";
+    socketInfo.name = 'test';
     socketInfo.bufferSize = 1024;
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
 }
 
@@ -266,8 +266,8 @@ function test_socketsTcpServer(): void {
     chrome.sockets.tcpServer.setPaused(socketId, true, () => { });
 
     // listen
-    chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { });
-    chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { });
+    chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, (result: number) => { });
+    chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, 128, (result: number) => { });
 
     // disconnect
     chrome.sockets.tcp.disconnect(socketId);
@@ -298,7 +298,7 @@ function testSocketsTcpServerTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test"
+        name: 'test'
     };
 
     // SocketInfo
@@ -310,8 +310,8 @@ function testSocketsTcpServerTypes(): void {
         paused: true
     };
 
-    socketInfo.name = "test";
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.name = 'test';
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
 }
 
@@ -340,7 +340,7 @@ wve.addEventListener('close', () => {
     return;
 });
 wve.addEventListener('consolemessage', (ev) => {
-    if (ev.level === chrome.webview.ConsoleMessageLevel.LOG_ERROR) {
+    if (ev.level === 2) {
         const msg = ev.message;
     }
 });
@@ -360,4 +360,177 @@ wve.addEventListener('loadredirect', (ev) => {
     return ev.newUrl || ev.oldUrl;
 });
 
-chrome.bluetoothLowEnergy.connect('1111111', () => { });
+chrome.bluetooth.getAdapterState((adapter) => {
+    console.log('Adapter ' + adapter.address + ': ' + adapter.name);
+});
+
+chrome.bluetooth.getDevices((devices) => {
+    for (const device of devices) {
+        console.log(device.address);
+    }
+});
+
+chrome.bluetooth.onDeviceAdded.addListener((device) => {
+    let uuid = '0000180d-0000-1000-8000-00805f9b34fb';
+    if (!device.uuids || device.uuids.indexOf(uuid) < 0)
+        return;
+
+    // The device has a service with the desired UUID.
+    chrome.bluetoothLowEnergy.connect(device.address, () => {
+        if (chrome.runtime.lastError) {
+            console.log('Failed to connect: ' + chrome.runtime.lastError.message);
+            return;
+        }
+        // Connected! Do stuff...
+    });
+});
+
+const uuid = '1105';
+
+chrome.bluetooth.getDevices((devices) => {
+    chrome.bluetoothSocket.create((createInfo) => {
+        chrome.bluetoothSocket.connect(createInfo.socketId,
+            devices[0].address, uuid, () => {
+                if (chrome.runtime.lastError) {
+                    console.log('Connection failed: ' + chrome.runtime.lastError.message);
+                } else {
+                    chrome.bluetoothSocket.send(createInfo.socketId, new ArrayBuffer(4096), (bytes_sent) => {
+                        if (chrome.runtime.lastError) {
+                            console.log('Send failed: ' + chrome.runtime.lastError.message);
+                        } else {
+                            console.log('Sent ' + bytes_sent + ' bytes')
+                        }
+                    });
+                }
+            });
+        chrome.bluetoothSocket.onReceive.addListener((receiveInfo) => {
+            if (receiveInfo.socketId != createInfo.socketId)
+                return;
+            // receiveInfo.data is an ArrayBuffer.
+        });
+    });
+});
+
+chrome.hid.getDevices({
+    filters: [
+        { vendorId: 5 }
+    ]
+}, (devices) => {
+    const productId = devices[0].productId;
+    chrome.hid.getUserSelectedDevices((selectedDevices) => {
+        const hmm = selectedDevices.productId == productId ? selectedDevices.vendorId : selectedDevices.maxFeatureReportSize;
+    });
+});
+
+chrome.syncFileSystem.getConflictResolutionPolicy((policy) => {
+    if (policy === 'manual') {
+        chrome.syncFileSystem.requestFileSystem((fs) => {
+            if (fs.root.isFile) {
+                throw new Error('It was a file!');
+            }
+        });
+    }
+})
+chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT;
+
+chrome.i18n.getMessage('click_here', ['string1', 'string2']);
+
+const TLSFormatExample = {
+    NetworkConfigurations: 
+        {
+            GUID: '{00f79111-51e0-e6e0-76b3b55450d80a1b}',
+            Name: 'MyTTLSNetwork',
+            Type: 'WiFi',
+            WiFi: {
+                AutoConnect: false,
+                EAP: {
+                    ClientCertPattern: {
+                        EnrollmentURI: [
+                            'http://fetch-my-certificate.com'
+                        ],
+                        IssuerCARef: [
+                            '{6ed8dce9-64c8-d568-d225d7e467e37828}'
+                        ]
+                    },
+                    'ClientCertType': 'Pattern',
+                    'Outer': 'EAP-TLS',
+                    'ServerCARef': '{6ed8dce9-64c8-d568-d225d7e467e37828}',
+                    'UseSystemCAs': true
+                },
+                'HiddenSSID': false,
+                'SSID': 'MyTTLSNetwork',
+                'Security': 'WPA-EAP'
+            }
+        }
+}
+
+let serviceId: any = null;
+
+const runApp = () => {
+    var options = {
+        'id': 'Bluetooth Sample App',
+        'bounds': {
+            'width': 1024,
+            'height': 768
+        }
+    };
+
+    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+        if (request.serviceId) {
+            serviceId = request.serviceId;
+            console.log('Received registered service Id: ' + serviceId);
+        }
+    });
+
+    chrome.app.window.create('test.html', options, (theWindow) => {
+        theWindow.onClosed.addListener(() => {
+            if (serviceId) {
+                console.log('Unregistering service: ' + serviceId);
+                chrome.bluetoothLowEnergy.unregisterService(serviceId, (status) => {
+                    console.log('Unregister service status = ' + status);
+                });
+            }
+        });
+    });
+}
+
+chrome.app.runtime.onLaunched.addListener(runApp);
+chrome.app.runtime.onRestarted.addListener(runApp);
+
+// networking.onc
+
+chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => {
+    console.log('Length of Network list: ' + networkList.length);
+    for (let networkObj of networkList) {
+        console.log('GUID: ' + networkObj.GUID);
+        console.log('Connectable: ' + networkObj.Connectable);
+        if (networkObj.WiFi) {
+            // WiFi active :)
+            console.log('Wifi BSID: ' + networkObj.WiFi.BSSID);
+        }
+        chrome.networking.onc.setProperties(networkObj.GUID || '', {
+            WiFi: {
+                Passphrase: 'Can be set :) but not get?'
+            }
+        })
+        // Test that we can't get passphrase
+        chrome.networking.onc.getProperties(networkObj.GUID || '', (props) => {
+            const WiFiResult = props.WiFi;
+        });
+    }
+});
+
+//// AUDIO
+
+chrome.audio.getDevices({}, (audioDeviceInfoList) => {
+    for (let audioObj of audioDeviceInfoList) {
+        console.log('ID: ' + audioObj.id);
+        console.log('Audio Stream Type: ' + audioObj.streamType);
+        console.log('Audio Device Name: ' + audioObj.deviceName);
+    }
+});
+
+
+chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { });
+chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { });
+

From 271b8f20c0f31280f8a600d4889f1856e7c84fe6 Mon Sep 17 00:00:00 2001
From: Jonny Fairfull 
Date: Fri, 3 Aug 2018 19:05:49 +0100
Subject: [PATCH 181/275] fix: update autoplay types to boolean or string.
 (#27838)

---
 types/video.js/index.d.ts | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts
index 8535cf4f16..8ac320d190 100644
--- a/types/video.js/index.d.ts
+++ b/types/video.js/index.d.ts
@@ -3760,9 +3760,9 @@ declare namespace videojs {
 		 *
 		 * @return The current value of autoplay when getting
 		 */
-		autoplay(value?: boolean): void;
+		autoplay(value?: boolean | string): void;
 
-		autoplay(): boolean;
+		autoplay(): boolean | string;
 
 		/**
 		 * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will
@@ -4559,7 +4559,7 @@ declare namespace videojs {
 
 	interface PlayerOptions extends ComponentOptions {
 		aspectRatio?: string;
-		autoplay?: boolean;
+		autoplay?: boolean | string;
 		controlBar?: ControlBarOptions | false;
 		textTrackSettings?: TextTrackSettingsOptions;
 		controls?: boolean;

From 4e450a27b6d9f5827114efcd8e775ae883c5cab8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rados=C5=82aw=20Miernik?= 
Date: Fri, 3 Aug 2018 20:10:12 +0200
Subject: [PATCH 182/275] Fixed typo. (#27843)

---
 .../{meteor-univserse-i18n => meteor-universe-i18n}/index.d.ts  | 0
 .../meteor-universe-i18n-tests.ts}                              | 0
 .../tsconfig.json                                               | 2 +-
 .../{meteor-univserse-i18n => meteor-universe-i18n}/tslint.json | 0
 4 files changed, 1 insertion(+), 1 deletion(-)
 rename types/{meteor-univserse-i18n => meteor-universe-i18n}/index.d.ts (100%)
 rename types/{meteor-univserse-i18n/meteor-univserse-i18n-tests.ts => meteor-universe-i18n/meteor-universe-i18n-tests.ts} (100%)
 rename types/{meteor-univserse-i18n => meteor-universe-i18n}/tsconfig.json (91%)
 rename types/{meteor-univserse-i18n => meteor-universe-i18n}/tslint.json (100%)

diff --git a/types/meteor-univserse-i18n/index.d.ts b/types/meteor-universe-i18n/index.d.ts
similarity index 100%
rename from types/meteor-univserse-i18n/index.d.ts
rename to types/meteor-universe-i18n/index.d.ts
diff --git a/types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts b/types/meteor-universe-i18n/meteor-universe-i18n-tests.ts
similarity index 100%
rename from types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts
rename to types/meteor-universe-i18n/meteor-universe-i18n-tests.ts
diff --git a/types/meteor-univserse-i18n/tsconfig.json b/types/meteor-universe-i18n/tsconfig.json
similarity index 91%
rename from types/meteor-univserse-i18n/tsconfig.json
rename to types/meteor-universe-i18n/tsconfig.json
index 7beab3bd30..3b4c98a86d 100644
--- a/types/meteor-univserse-i18n/tsconfig.json
+++ b/types/meteor-universe-i18n/tsconfig.json
@@ -18,6 +18,6 @@
     },
     "files": [
         "index.d.ts",
-        "meteor-univserse-i18n-tests.ts"
+        "meteor-universe-i18n-tests.ts"
     ]
 }
diff --git a/types/meteor-univserse-i18n/tslint.json b/types/meteor-universe-i18n/tslint.json
similarity index 100%
rename from types/meteor-univserse-i18n/tslint.json
rename to types/meteor-universe-i18n/tslint.json

From 7d077bf41894f995c58bc9a7c3bdfcb8065b38ac Mon Sep 17 00:00:00 2001
From: Claas Ahlrichs 
Date: Fri, 3 Aug 2018 20:49:22 +0200
Subject: [PATCH 183/275] Feature/react select v2 update (#27837)

* updated parameter names in function signatures

* addressed return type of "CSS functions"

* simplified StylesConfig and SelectComponentsConfig

* updated type of base parameter in styleFn

* removed invalid property from HTML select element
---
 types/react-select/lib/Creatable.d.ts         |  4 +--
 types/react-select/lib/Select.d.ts            |  6 ++--
 .../react-select/lib/components/Control.d.ts  |  2 +-
 types/react-select/lib/components/Group.d.ts  |  4 +--
 types/react-select/lib/components/Input.d.ts  |  4 +--
 types/react-select/lib/components/Menu.d.ts   | 10 +++---
 .../lib/components/MultiValue.d.ts            |  6 ++--
 types/react-select/lib/components/Option.d.ts |  2 +-
 .../lib/components/Placeholder.d.ts           |  2 +-
 .../lib/components/SingleValue.d.ts           |  2 +-
 .../lib/components/containers.d.ts            |  6 ++--
 types/react-select/lib/components/index.d.ts  | 28 +--------------
 .../lib/components/indicators.d.ts            |  6 ++--
 types/react-select/lib/styles.d.ts            | 34 +++----------------
 .../test/examples/Experimental.tsx            |  6 ++--
 .../react-select/test/examples/MenuPortal.tsx |  1 -
 types/react-select/test/examples/Popout.tsx   |  4 +--
 17 files changed, 38 insertions(+), 89 deletions(-)

diff --git a/types/react-select/lib/Creatable.d.ts b/types/react-select/lib/Creatable.d.ts
index c194441a8b..ac67bf039c 100644
--- a/types/react-select/lib/Creatable.d.ts
+++ b/types/react-select/lib/Creatable.d.ts
@@ -14,10 +14,10 @@ export interface CreatableProps {
   formatCreateLabel?: (inputValue: string) => Node;
   /* Determines whether the "create new ..." option should be displayed based on
      the current input value, select value and options array. */
-  isValidNewOption?: (a: string, b: ValueType, c: OptionsType) => boolean;
+  isValidNewOption?: (inputValue: string, value: ValueType, options: OptionsType) => boolean;
   /* Returns the data for the new option when it is created. Used to display the
      value, and is passed to `onChange`. */
-  getNewOptionData?: (a: string, b: Node) => OptionType;
+  getNewOptionData?: (inputValue: string, optionLabel: Node) => OptionType;
   /* If provided, this will be called with the input value when a new option is
      created, and `onChange` will **not** be called. Use this when you need more
      control over what happens when new options are created. */
diff --git a/types/react-select/lib/Select.d.ts b/types/react-select/lib/Select.d.ts
index 0298ea0288..3e89a139ac 100644
--- a/types/react-select/lib/Select.d.ts
+++ b/types/react-select/lib/Select.d.ts
@@ -107,7 +107,7 @@ export interface Props {
   /* Formats group labels in the menu as React components */
   formatGroupLabel?: typeof formatGroupLabel;
   /* Formats option labels in the menu and control as React components */
-  formatOptionLabel?: (a: OptionType, b: FormatOptionLabelMeta) => Node;
+  formatOptionLabel?: (option: OptionType, labelMeta: FormatOptionLabelMeta) => Node;
   /* Resolves option data to a string to be displayed as the label by components */
   getOptionLabel?: typeof getOptionLabel;
   /* Resolves option data to a string to compare options and specify value attributes */
@@ -129,9 +129,9 @@ export interface Props {
   /* Is the select in a state of loading (async) */
   isLoading?: boolean;
   /* Override the built-in logic to detect whether an option is disabled */
-  isOptionDisabled?: (a: OptionType, b: OptionsType) => boolean | false;
+  isOptionDisabled?: (option: OptionType, options: OptionsType) => boolean | false;
   /* Override the built-in logic to detect whether an option is selected */
-  isOptionSelected?: (a: OptionType, b: OptionsType) => boolean;
+  isOptionSelected?: (option: OptionType, options: OptionsType) => boolean;
   /* Support multiple selected options */
   isMulti?: boolean;
   /* Is the select direction right-to-left */
diff --git a/types/react-select/lib/components/Control.d.ts b/types/react-select/lib/components/Control.d.ts
index 019f75bee9..c48dee76d4 100644
--- a/types/react-select/lib/components/Control.d.ts
+++ b/types/react-select/lib/components/Control.d.ts
@@ -22,7 +22,7 @@ export type ControlProps = CommonProps &
     },
   };
 
-export function css(state: State): any; // TODO css type
+export function css(state: State): React.CSSProperties;
 
 declare const Control: ComponentType>;
 
diff --git a/types/react-select/lib/components/Group.d.ts b/types/react-select/lib/components/Group.d.ts
index d37964c0b4..9e05263224 100644
--- a/types/react-select/lib/components/Group.d.ts
+++ b/types/react-select/lib/components/Group.d.ts
@@ -13,11 +13,11 @@ interface ComponentProps {
 }
 export type GroupProps = CommonProps & ComponentProps;
 
-export function groupCSS(): any; // TODO css type
+export function groupCSS(): React.CSSProperties;
 
 export const Group: ComponentType>;
 
-export function groupHeadingCSS(): any; // TODO css type
+export function groupHeadingCSS(): React.CSSProperties;
 
 export const GroupHeading: ComponentType;
 
diff --git a/types/react-select/lib/components/Input.d.ts b/types/react-select/lib/components/Input.d.ts
index 16f07491d2..9f79ffb1e0 100644
--- a/types/react-select/lib/components/Input.d.ts
+++ b/types/react-select/lib/components/Input.d.ts
@@ -15,8 +15,8 @@ export type InputProps = PropsWithStyles & {
   className?: string,
 };
 
-export function inputCSS(props: InputProps): any; // TODO css type;
-export function inputStyle(isHidden: boolean): any; // TODO css type
+export function inputCSS(props: InputProps): React.CSSProperties;
+export function inputStyle(isHidden: boolean): React.CSSProperties;
 
 export const Input: ComponentType;
 
diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts
index 85b5ef0fae..d91288cdeb 100644
--- a/types/react-select/lib/components/Menu.d.ts
+++ b/types/react-select/lib/components/Menu.d.ts
@@ -64,7 +64,7 @@ export type MenuProps = CommonProps & {
   menuShouldScrollIntoView: boolean,
 };
 
-export function menuCSS(state: MenuState): any; // TODO css type
+export function menuCSS(state: MenuState): React.CSSProperties;
 
 export class Menu extends Component, MenuState> {
   static contextTypes: {
@@ -96,15 +96,15 @@ export interface MenuListProps {
 export type MenuListComponentProps = CommonProps &
   MenuListProps &
   MenuListState;
-export function menuListCSS(state: MenuState): any; // TODO css type
+export function menuListCSS(state: MenuState): React.CSSProperties;
 export const MenuList: ComponentType>;
 
 // ==============================
 // Menu Notices
 // ==============================
 
-export function noOptionsMessageCSS(): any; // TODO css type
-export function loadingMessageCSS(): any; // TODO css type
+export function noOptionsMessageCSS(): React.CSSProperties;
+export function loadingMessageCSS(): React.CSSProperties;
 
 export type NoticeProps = CommonProps & {
   /** The children to be rendered. */
@@ -143,7 +143,7 @@ interface PortalStyleArgs {
   rect: RectType;
 }
 
-export function menuPortalCSS(args: PortalStyleArgs): any; // TODO css type
+export function menuPortalCSS(args: PortalStyleArgs): React.CSSProperties;
 
 export class MenuPortal extends Component, MenuPortalState> {
   static childContextTypes: {
diff --git a/types/react-select/lib/components/MultiValue.d.ts b/types/react-select/lib/components/MultiValue.d.ts
index 495b4fc96f..ac304bd42a 100644
--- a/types/react-select/lib/components/MultiValue.d.ts
+++ b/types/react-select/lib/components/MultiValue.d.ts
@@ -18,9 +18,9 @@ export type MultiValueProps = CommonProps &{
   },
 };
 
-export function multiValueCSS(): any; // TODO css type
-export function multiValueLabelCSS(props: MultiValueProps): any; // TODO css type
-export function multiValueRemoveCSS(props: MultiValueProps): any; // TODO css type
+export function multiValueCSS(): React.CSSProperties;
+export function multiValueLabelCSS(props: MultiValueProps): React.CSSProperties;
+export function multiValueRemoveCSS(props: MultiValueProps): React.CSSProperties;
 
 export interface MultiValueGenericProps {
   children: Node;
diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts
index 743083fff8..81ab38e401 100644
--- a/types/react-select/lib/components/Option.d.ts
+++ b/types/react-select/lib/components/Option.d.ts
@@ -34,7 +34,7 @@ export type OptionProps = PropsWithStyles &
     type: 'option',
   };
 
-export function optionCSS(state: State): any; // TODO css type
+export function optionCSS(state: State): React.CSSProperties;
 
 export const Option: ComponentType>;
 
diff --git a/types/react-select/lib/components/Placeholder.d.ts b/types/react-select/lib/components/Placeholder.d.ts
index f674f74cc2..6f674d70a8 100644
--- a/types/react-select/lib/components/Placeholder.d.ts
+++ b/types/react-select/lib/components/Placeholder.d.ts
@@ -10,7 +10,7 @@ export type PlaceholderProps = CommonProps & {
   innerProps: { [key: string]: any },
 };
 
-export function placeholderCSS(): any; // TODO css type
+export function placeholderCSS(): React.CSSProperties;
 
 export const Placeholder: ComponentType>;
 
diff --git a/types/react-select/lib/components/SingleValue.d.ts b/types/react-select/lib/components/SingleValue.d.ts
index c5f922d84c..c727b2242e 100644
--- a/types/react-select/lib/components/SingleValue.d.ts
+++ b/types/react-select/lib/components/SingleValue.d.ts
@@ -16,7 +16,7 @@ interface ValueProps {
 }
 export type SingleValueProps = CommonProps & ValueProps & State;
 
-export function css(props: SingleValueProps): any; // TODO css type
+export function css(props: SingleValueProps): React.CSSProperties;
 
 export const SingleValue: ComponentType>;
 
diff --git a/types/react-select/lib/components/containers.d.ts b/types/react-select/lib/components/containers.d.ts
index 373a552062..e75de6d756 100644
--- a/types/react-select/lib/components/containers.d.ts
+++ b/types/react-select/lib/components/containers.d.ts
@@ -20,7 +20,7 @@ export type ContainerProps = CommonProps &
     /** Inner props to be passed down to the container. */
     innerProps: { onKeyDown: KeyboardEventHandler },
   };
-export function containerCSS(state: ContainerState): any; // TODO css type;
+export function containerCSS(state: ContainerState): React.CSSProperties;
 export const SelectContainer: ComponentType>;
 
 // ==============================
@@ -35,7 +35,7 @@ export type ValueContainerProps = CommonProps & {
   /** The children to be rendered. */
   children: Node,
 };
-export function valueContainerCSS(): any; // TODO css type;
+export function valueContainerCSS(): React.CSSProperties;
 export class ValueContainer extends Component> {}
 
 // ==============================
@@ -53,5 +53,5 @@ export type IndicatorContainerProps = CommonProps &
     children: Node,
   };
 
-export function indicatorsContainerCSS(): any; // TODO css type;
+export function indicatorsContainerCSS(): React.CSSProperties;
 export const IndicatorsContainer: ComponentType>;
diff --git a/types/react-select/lib/components/index.d.ts b/types/react-select/lib/components/index.d.ts
index 7d493a562a..d9d505b119 100644
--- a/types/react-select/lib/components/index.d.ts
+++ b/types/react-select/lib/components/index.d.ts
@@ -79,33 +79,7 @@ export interface SelectComponents {
   ValueContainer: ComponentType>;
 }
 
-export interface SelectComponentsConfig {
-  ClearIndicator?: IndicatorComponentType | null;
-  Control?: ComponentType>;
-  DropdownIndicator?: IndicatorComponentType | null;
-  DownChevron?: ComponentType;
-  CrossIcon?: ComponentType;
-  Group?: ComponentType>;
-  GroupHeading?: ComponentType;
-  IndicatorsContainer?: ComponentType>;
-  IndicatorSeparator?: IndicatorComponentType | null;
-  Input?: ComponentType;
-  LoadingIndicator?: ComponentType> | null;
-  Menu?: ComponentType>;
-  MenuList?: ComponentType>;
-  MenuPortal?: ComponentType>;
-  LoadingMessage?: ComponentType>;
-  NoOptionsMessage?: ComponentType>;
-  MultiValue?: ComponentType>;
-  MultiValueContainer?: ComponentType;
-  MultiValueLabel?: ComponentType;
-  MultiValueRemove?: ComponentType;
-  Option?: ComponentType>;
-  Placeholder?: ComponentType>;
-  SelectContainer?: ComponentType>;
-  SingleValue?: ComponentType>;
-  ValueContainer?: ComponentType>;
-}
+export type SelectComponentsConfig = Partial>;
 
 export namespace components {
   const ClearIndicator: IndicatorComponentType | null;
diff --git a/types/react-select/lib/components/indicators.d.ts b/types/react-select/lib/components/indicators.d.ts
index d27cc518da..15df6d3748 100644
--- a/types/react-select/lib/components/indicators.d.ts
+++ b/types/react-select/lib/components/indicators.d.ts
@@ -25,7 +25,7 @@ export type IndicatorProps = CommonProps & {
   isRtl: boolean,
 };
 
-export type baseCSS = (props: IndicatorProps) => any; // TODO css type
+export type baseCSS = (props: IndicatorProps) => React.CSSProperties;
 
 export const dropdownIndicatorCSS: baseCSS;
 export const DropdownIndicator: ComponentType>;
@@ -39,7 +39,7 @@ export const ClearIndicator: ComponentType>;
 
 export interface SeparatorState { isDisabled: boolean; }
 
-export function indicatorSeparatorCSS(state: SeparatorState): any; // TODO css type
+export function indicatorSeparatorCSS(state: SeparatorState): React.CSSProperties;
 
 export const IndicatorSeparator: ComponentType>;
 
@@ -50,7 +50,7 @@ export const IndicatorSeparator: ComponentType>;
 export function loadingIndicatorCSS(state: {
   isFocused: boolean,
   size: number,
-}): any; // TODO css type
+}): React.CSSProperties;
 
 export type LoadingIconProps = {
   /** Props that will be passed on to the children. */
diff --git a/types/react-select/lib/styles.d.ts b/types/react-select/lib/styles.d.ts
index 9c5178fed1..e9c63d07b8 100644
--- a/types/react-select/lib/styles.d.ts
+++ b/types/react-select/lib/styles.d.ts
@@ -27,6 +27,7 @@ import {
   multiValueLabelCSS,
   multiValueRemoveCSS,
 } from './components/MultiValue';
+import { CSSProperties } from 'react';
 
 export interface Props { [key: string]: any; }
 
@@ -35,7 +36,7 @@ export interface Props { [key: string]: any; }
  * @param state -- the component's current state e.g. `isFocused`
  * @returns
  */
-export type styleFn = (base: any, state: any) => any;
+export type styleFn = (base: CSSProperties, state: any) => CSSProperties;
 
 export interface Styles {
   clearIndicator?: styleFn;
@@ -63,37 +64,12 @@ export interface Styles {
   singleValue?: styleFn;
   valueContainer: styleFn;
 }
-export interface StylesConfig {
-  clearIndicator?: styleFn;
-  container?: styleFn;
-  control?: styleFn;
-  dropdownIndicator?: styleFn;
-  group?: styleFn;
-  groupHeading?: styleFn;
-  indicatorsContainer?: styleFn;
-  indicatorSeparator?: styleFn;
-  input?: styleFn;
-  loadingIndicator?: styleFn;
-  // TODO loadingMessageCSS?: styleFn;
-  loadingMessage?: styleFn;
-  menu?: styleFn;
-  menuList?: styleFn;
-  menuPortal?: styleFn;
-  multiValue?: styleFn;
-  multiValueLabel?: styleFn;
-  multiValueRemove?: styleFn;
-  // TODO noOptionsMessageCSS?: styleFn;
-  noOptionsMessage?: styleFn;
-  option?: styleFn;
-  placeholder?: styleFn;
-  singleValue?: styleFn;
-  valueContainer?: styleFn;
-}
-export type GetStyles = (a: string, b: Props) => any;
+export type StylesConfig = Partial;
+export type GetStyles = (a: string, b: Props) => CSSProperties;
 
 export const defaultStyles: Styles;
 
 // Merge Utility
 // Allows consumers to extend a base Select with additional styles
 
-export function mergeStyles(source: any, target: any): any;
+export function mergeStyles(source: any, target: any): CSSProperties;
diff --git a/types/react-select/test/examples/Experimental.tsx b/types/react-select/test/examples/Experimental.tsx
index c2b8e42f95..c0bbf3c6ad 100644
--- a/types/react-select/test/examples/Experimental.tsx
+++ b/types/react-select/test/examples/Experimental.tsx
@@ -111,14 +111,14 @@ const Group = (props: any) => {
       >
         {label}
       
-      
// TODO css type +
{days.map((day, i) => ( - // TODO css type + {day} ))}
-
{children}
// TODO css type +
{children}
); }; diff --git a/types/react-select/test/examples/MenuPortal.tsx b/types/react-select/test/examples/MenuPortal.tsx index 32590acfb1..b7360e6fff 100644 --- a/types/react-select/test/examples/MenuPortal.tsx +++ b/types/react-select/test/examples/MenuPortal.tsx @@ -52,7 +52,6 @@ export default class MenuPortal extends React.Component { />