From 98d94b19b12c12b0d2f92f8ac0acf3e654d3fbd7 Mon Sep 17 00:00:00 2001 From: johnjbarton Date: Fri, 3 Aug 2018 10:45:02 -0700 Subject: [PATCH 01/34] 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 02/34] 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 03/34] 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 04/34] 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 05/34] [@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 06/34] 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 07/34] 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 08/34] 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 09/34] @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 10/34] 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 11/34] 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 12/34] @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 13/34] 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 14/34] 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 15/34] 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 16/34] 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 { />