From 452111db33f579b239e44f525cc8865fcef8b683 Mon Sep 17 00:00:00 2001 From: Duong Tran Date: Thu, 14 Jun 2018 15:00:44 +1000 Subject: [PATCH 001/289] improve static router props context --- types/react-router/index.d.ts | 8 +++++++- .../examples-from-react-router-website/StaticRouter.tsx | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 5ae92ababc..2b1e2f97c1 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -17,6 +17,7 @@ // Youen Toupin // Rahul Raina // Maksim Sharipov +// Duong Tran // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -86,10 +87,15 @@ export interface RouterProps { } export class Router extends React.Component { } +export interface StaticRouterContext { + url?: string; + action?: 'PUSH' | 'REPLACE'; + location?: object; +} export interface StaticRouterProps { basename?: string; location?: string | object; - context?: object; + context?: StaticRouterContext; } export class StaticRouter extends React.Component { } diff --git a/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx b/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx index c9763bdda5..3dce9a5def 100644 --- a/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx +++ b/types/react-router/test/examples-from-react-router-website/StaticRouter.tsx @@ -1,7 +1,8 @@ import * as React from 'react'; import { StaticRouter, Route } from 'react-router-dom'; +import { StaticRouterContext } from 'react-router'; -interface StaticContext { +interface StaticContext extends StaticRouterContext { statusCode?: number; } From b3176dde99cecca3ac348ef65ecd0313a0c5e9ac Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 13:18:53 +0200 Subject: [PATCH 002/289] Bugfixes: Webview is an HTMLElement and also frame must be of type chrome to set options --- types/chrome-apps/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index a1713aa6f9..f1a03f2b44 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -448,7 +448,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. @@ -2719,7 +2719,7 @@ declare namespace chrome { // 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: http://www.w3.org/TR/discovery-api/ * @since Chrome 31 */ namespace mdns { @@ -4589,7 +4589,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; @@ -5509,7 +5509,7 @@ declare namespace chrome { /** * @description WebView element from html */ - interface HTMLWebViewElement extends Element { + interface HTMLWebViewElement extends HTMLElement { /** * This sets the guest content's window.name object. */ From 67f94a57b22d50eacda9ae7a54f86359519bc836 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 13:18:53 +0200 Subject: [PATCH 003/289] Bugfixes: Webview is an HTMLElement and also frame must be of type chrome to set options --- types/chrome-apps/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index a1713aa6f9..f1a03f2b44 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -448,7 +448,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. @@ -2719,7 +2719,7 @@ declare namespace chrome { // 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: http://www.w3.org/TR/discovery-api/ * @since Chrome 31 */ namespace mdns { @@ -4589,7 +4589,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; @@ -5509,7 +5509,7 @@ declare namespace chrome { /** * @description WebView element from html */ - interface HTMLWebViewElement extends Element { + interface HTMLWebViewElement extends HTMLElement { /** * This sets the guest content's window.name object. */ From 348c3ab5aea40ba249fb805dc58c5d7c98d195e5 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 14:17:14 +0200 Subject: [PATCH 004/289] Bluetooth Socket: typings complete --- types/chrome-apps/index.d.ts | 323 ++++++++++++++++++++++++++++++++++- 1 file changed, 322 insertions(+), 1 deletion(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index f1a03f2b44..337fba3e06 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,3 +1,4 @@ +import { onAcceptError } from './index.d'; // 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 @@ -1367,6 +1368,7 @@ declare namespace chrome { */ 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 @@ -1374,7 +1376,326 @@ declare namespace chrome { * Important: This API works only on OS X, Windows and Chrome OS. */ namespace bluetoothSocket { - /* NOT IMPLEMENTED YET */ + 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; + /** (integer) The size of the buffer used to receive data. The default value is 4096. */ + bufferSize?: number; + } + interface ListenOptions { + /** + * (integer) + * 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?: number; + /** + * (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?: number; + /** + * Length of the socket's listen queue. + * The default value depends on the operating system's host subsystem. + * */ + backlog?: number; + } + interface SocketInfo { + /** + * (integer) + * The socket identifier. + * */ + socketId: number; + /** + * 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; + /** + * (integer) + * The size of the buffer used to receive data. + * If no buffer size has been specified explictly, + * the value is not provided. + */ + bufferSize?: number; + /** + * 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 { + /** + * (integer) + * 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: number; + } + interface OnAcceptInfoData { + /** The server socket identifier. (integer) */ + socketId: number; + /** + * (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: number; + } + enum OnAcceptErrorCode { + "system_error", + "not_listening" + } + interface OnAcceptErrorEventData { + /** The server socket identifier. (integer) */ + socketId: number; + /** 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. (integer) */ + socketId: number; + /** The data received, with a maxium size of bufferSize. */ + data: ArrayBuffer; + } + enum OnReceiveErrorCode { + "disconnected", + "system_error", + "not_connected" + } + interface OnReceiveErrorEventData { + /** The server socket identifier. (integer) */ + socketId: number; + /** 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; + /** + * 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; + /** + * Updates the socket properties. + * @param socketId The socket identifier. (integer) + * @param properties The properties to update. + * @param [callback] Called when the properties are updated. + */ + function update(socketId: number, properties: SocketProperties, callback?: () => {}): 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. (integer) + * @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: number, paused: boolean, callback?: () => {}): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. (integer) + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingRfcomm(socketId: number, uuid: string, callback: () => {}): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. (integer) + * @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: number, uuid: string, options: ListenOptions, callback: () => {}): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. (integer) + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingL2cap(socketId: number, uuid: string, callback: () => {}): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. (integer) + * @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: number, uuid: string, options: ListenOptions, callback: () => {}): 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. (integer) + * @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: number, address: string, uuid: string, callback: () => {}): void; + /** + * Disconnects the socket. The socket identifier remains valid. + * @param socketId The socket identifier. (integer) + * @param [callback] Called when the disconnect attempt is complete. + */ + function disconnect(socketId: number, callback?: () => {}): 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. (integer) + * @param callback Called when the `close` operation completes + */ + function close(socketId: number, callback: () => {}): void; + /** + * Sends data on the given Bluetooth socket. + * @param socketId The socket identifier. (integer) + * @param data The data to send. + * @param [callback] Called with the number of bytes sent. + */ + function send(socketId: number, data: ArrayBuffer, callback?: (bytesSent: number) => {}): void; + /** + * Retrieves the state of the given socket. + * @param socketId The socket identifier. (integer) + * @param callback Called when the socket state is available. + * Callback returning object containing the socket information. + */ + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => {}): 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; + /** + * Event raised when a connection has been established + * for a given socket. + */ + var 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. + */ + var onAcceptError: OnAcceptErrorEvent; + /** + * Event raised when data has been received for a given socket. + */ + var 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. + */ + var onReceiveError: OnReceiveErrorEvent; } //////////////////// From 5e8a55ded5c7cfb722b6d6ee47f1523a59391903 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 14:33:45 +0200 Subject: [PATCH 005/289] Bluetooth tests --- types/chrome-apps/index.d.ts | 140 ++++++++++++++++---------------- types/chrome-apps/test/index.ts | 53 +++++++++++- 2 files changed, 124 insertions(+), 69 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 337fba3e06..45f3bb294a 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,4 +1,3 @@ -import { onAcceptError } from './index.d'; // 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 @@ -813,14 +812,14 @@ declare namespace chrome { /** * @description 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; /** * @description 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; /** Fired when sound level changes for an active audio device. */ @@ -892,7 +891,7 @@ declare namespace chrome { */ uuids?: string[]; /** - * The received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. + * The Recieved signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. * @since Chrome 44 */ inquiryRssi: number; @@ -920,12 +919,17 @@ declare namespace chrome { export 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; + /** + * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. + * @param callback Called when the search is completed. + */ + export 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; + export 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. @@ -1370,7 +1374,7 @@ declare namespace chrome { } /** - * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. + * Use the chrome.bluetoothSocket API to send and Recieve 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. @@ -1387,7 +1391,7 @@ declare namespace chrome { persistent?: boolean; /** An application-defined string associated with the socket. */ name?: string; - /** (integer) The size of the buffer used to receive data. The default value is 4096. */ + /** (integer) The size of the buffer used to Recieve data. The default value is 4096. */ bufferSize?: number; } interface ListenOptions { @@ -1432,7 +1436,7 @@ declare namespace chrome { name?: string; /** * (integer) - * The size of the buffer used to receive data. + * The size of the buffer used to Recieve data. * If no buffer size has been specified explictly, * the value is not provided. */ @@ -1511,18 +1515,18 @@ declare namespace chrome { */ error: OnAcceptErrorCode; } - interface OnReceiveEventData { + interface OnRecieveEventData { /** The socket identifier. (integer) */ socketId: number; - /** The data received, with a maxium size of bufferSize. */ + /** The data Recieved, with a maxium size of bufferSize. */ data: ArrayBuffer; } - enum OnReceiveErrorCode { + enum OnRecieveErrorCode { "disconnected", "system_error", "not_connected" } - interface OnReceiveErrorEventData { + interface OnRecieveErrorEventData { /** The server socket identifier. (integer) */ socketId: number; /** The error message */ @@ -1541,26 +1545,26 @@ declare namespace chrome { } 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> { } + interface OnRecieveEvent extends chrome.events.Event<(info: OnRecieveEventData) => void> { } + interface OnRecieveErrorEvent extends chrome.events.Event<(info: OnRecieveErrorEventData) => void> { } /** * Creates a Bluetooth socket. * @param callback Called when the socket has been created * */ - function create(callback: (createInfo: CreateInfo) => {}): void; + 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; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; /** * Updates the socket properties. * @param socketId The socket identifier. (integer) * @param properties The properties to update. * @param [callback] Called when the properties are updated. */ - function update(socketId: number, properties: SocketProperties, callback?: () => {}): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; /** * Enables or disables a connected socket from * receiving messages from its peer, or a listening @@ -1568,9 +1572,9 @@ declare namespace chrome { * 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, + * no onRecieveevent is raised. When a socket is connected + * and un-paused, onRecieve events are raised again when + * messages are Recieved. 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. @@ -1584,7 +1588,7 @@ declare namespace chrome { * See setPaused. The default value is "false". * @param [callback] Callback from the setPaused method. */ - function setPaused(socketId: number, paused: boolean, callback?: () => {}): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; /** * Listen for connections using the RFCOMM protocol. * @@ -1592,7 +1596,7 @@ declare namespace chrome { * @param uuid Service UUID to listen on. * @param callback Called when listen operation completes. */ - function listenUsingRfcomm(socketId: number, uuid: string, callback: () => {}): void; + function listenUsingRfcomm(socketId: number, uuid: string, callback: () => void): void; /** * Listen for connections using the RFCOMM protocol. * @@ -1601,7 +1605,7 @@ declare namespace chrome { * @param options Optional additional options for the service. * @param callback Called when listen operation completes. */ - function listenUsingRfcomm(socketId: number, uuid: string, options: ListenOptions, callback: () => {}): void; + function listenUsingRfcomm(socketId: number, uuid: string, options: ListenOptions, callback: () => void): void; /** * Listen for connections using the L2CAP protocol. * @@ -1609,7 +1613,7 @@ declare namespace chrome { * @param uuid Service UUID to listen on. * @param callback Called when listen operation completes. */ - function listenUsingL2cap(socketId: number, uuid: string, callback: () => {}): void; + function listenUsingL2cap(socketId: number, uuid: string, callback: () => void): void; /** * Listen for connections using the L2CAP protocol. * @@ -1618,14 +1622,14 @@ declare namespace chrome { * @param options Optional additional options for the service. * @param callback Called when listen operation completes. */ - function listenUsingL2cap(socketId: number, uuid: string, options: ListenOptions, callback: () => {}): void; + function listenUsingL2cap(socketId: number, 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 + * onRecieve events are raised when data is Recieved * 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 + * runtime is receiving packets, a onRecieveError + * event is raised, at which point no more onRecieve * event will be raised for this socket until the * setPaused(false) method is called. * @@ -1634,13 +1638,13 @@ declare namespace chrome { * @param uuid The UUID of the service to connect to. * @param callback Called when the connect attempt is complete. */ - function connect(socketId: number, address: string, uuid: string, callback: () => {}): void; + function connect(socketId: number, address: string, uuid: string, callback: () => void): void; /** * Disconnects the socket. The socket identifier remains valid. * @param socketId The socket identifier. (integer) * @param [callback] Called when the disconnect attempt is complete. */ - function disconnect(socketId: number, callback?: () => {}): void; + function disconnect(socketId: number, callback?: () => void): void; /** * Disconnects and destroys the socket. * Each socket created should be closed after use. @@ -1651,27 +1655,27 @@ declare namespace chrome { * @param socketId The socket identifier. (integer) * @param callback Called when the `close` operation completes */ - function close(socketId: number, callback: () => {}): void; + function close(socketId: number, callback: () => void): void; /** * Sends data on the given Bluetooth socket. * @param socketId The socket identifier. (integer) * @param data The data to send. * @param [callback] Called with the number of bytes sent. */ - function send(socketId: number, data: ArrayBuffer, callback?: (bytesSent: number) => {}): void; + function send(socketId: number, data: ArrayBuffer, callback?: (bytesSent: number) => void): void; /** * Retrieves the state of the given socket. * @param socketId The socket identifier. (integer) * @param callback Called when the socket state is available. * Callback returning object containing the socket information. */ - function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => {}): void; + function getInfo(socketId: number, 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; + function getSockets(callback: (sockets: SocketInfo[]) => void): void; /** * Event raised when a connection has been established * for a given socket. @@ -1686,16 +1690,16 @@ declare namespace chrome { */ var onAcceptError: OnAcceptErrorEvent; /** - * Event raised when data has been received for a given socket. + * Event raised when data has been Recieved for a given socket. */ - var onReceive: OnReceiveEvent; + var onRecieve: OnRecieveEvent; /** * 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 + * the socket is set to paused and no more onRecieve events are * raised for this socket. */ - var onReceiveError: OnReceiveErrorEvent; + var onRecieveError: OnRecieveErrorEvent; } //////////////////// @@ -2635,7 +2639,7 @@ declare namespace chrome { export 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. + * @param callback Callback to Recieve the result of getAll function. * The callback parameter should be a function that looks like this: * function(array of FileSystemInfo fileSystems) {...}; */ @@ -2643,7 +2647,7 @@ declare namespace chrome { /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. - * @param callback Callback to receive the result of get function. + * @param callback Callback to Recieve the result of get function. * The callback parameter should be a function that looks like this: * function(FileSystemInfo fileSystem) {...}; */ @@ -2715,7 +2719,7 @@ declare namespace chrome { // Google Cloud Messaging //////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and receive messages through the Google Cloud Messaging Service. + * Use chrome.gcm to enable apps and extensions to send and Recieve messages through the Google Cloud Messaging Service. * Availability: Since Chrome 35. * Permissions: 'gcm' */ @@ -2801,7 +2805,7 @@ declare namespace chrome { */ export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; - /** Fired when a message is received through GCM. */ + /** Fired when a message is Recieved through GCM. */ export var onMessage: MessageReceptionEvent; /** 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; @@ -4150,12 +4154,12 @@ declare namespace chrome { bytesSent?: number; } - interface ReceiveEventArgs { + interface RecieveEventArgs { socketId: number; data: ArrayBuffer; } - interface ReceiveErrorEventArgs { + interface RecieveErrorEventArgs { socketId: number; resultCode: number; } @@ -4199,8 +4203,8 @@ declare namespace chrome { export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; export 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>; + export var onRecieve: chrome.events.Event<(args: RecieveEventArgs) => void>; + export var onRecieveError: chrome.events.Event<(args: RecieveErrorEventArgs) => void>; } /** @@ -4404,7 +4408,7 @@ declare namespace chrome { } /** - * Use the chrome.sockets.udp API to send and receive data over the network + * Use the chrome.sockets.udp API to send and Recieve data over the network * using UDP connections. This API supersedes the UDP functionality previously * found in the 'socket' API. * @@ -4421,14 +4425,14 @@ declare namespace chrome { bytesSent?: number; } - interface ReceiveEventArgs { + interface RecieveEventArgs { socketId: number; data: ArrayBuffer; remoteAddress: string; remotePort: number; } - interface ReceiveErrorEventArgs { + interface RecieveErrorEventArgs { socketId: number; resultCode: number; } @@ -4450,8 +4454,8 @@ declare namespace chrome { name?: string; /** - * 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 + * The size of the buffer used to Recieve data. If the buffer is too + * small to Recieve the UDP packet, data is lost. The default value is * 4096. */ bufferSize?: number; @@ -4474,13 +4478,13 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to receive data. If no buffer size ha + * The size of the buffer used to Recieve data. If no buffer size ha * been specified explictly, the value is not provided. */ bufferSize?: number; /** - * Flag indicating whether the socket is blocked from firing onReceive + * Flag indicating whether the socket is blocked from firing onRecieve * events. */ paused: boolean; @@ -4525,7 +4529,7 @@ declare namespace chrome { /** * Pauses or unpauses a socket. A paused socket is blocked from firing - * onReceive events. + * onRecieve events. * * @see https://developer.chrome.com/apps/sockets_udp#method-setPaused * @param socketId The socket ID. @@ -4539,7 +4543,7 @@ declare namespace chrome { * Binds the local address and port for the socket. For a client socket, it * is recommended to use port 0 to let the platform pick a free port. * - * Once the bind operation completes successfully, onReceive events are + * Once the bind operation completes successfully, onRecieve events are * raised when UDP packets arrive on the address/port specified -- unless * the socket is paused. * @@ -4597,7 +4601,7 @@ declare namespace chrome { export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** - * Joins the multicast group and starts to receive packets from that group. + * Joins the multicast group and starts to Recieve packets from that group. * The socket must be bound to a local port before calling this method. * * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup @@ -4645,7 +4649,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 + * Recieve 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 @@ -4680,21 +4684,21 @@ declare namespace chrome { export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; /** - * Event raised when a UDP packet has been received for the given socket. + * Event raised when a UDP packet has been Recieved for the given socket. * - * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive + * @see https://developer.chrome.com/apps/sockets_udp#event-onRecieve */ - export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + export var onRecieve: chrome.events.Event<(args: RecieveEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting * for data on the socket address and port. Once this event is raised, the - * socket is paused and no more onReceive events will be raised for this + * socket is paused and no more onRecieve events will be raised for this * socket until the socket is resumed. * - * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError + * @see https://developer.chrome.com/apps/sockets_udp#event-onRecieveError */ - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + export var onRecieveError: chrome.events.Event<(args: RecieveErrorEventArgs) => void>; } //////////////////// @@ -5665,7 +5669,7 @@ declare namespace chrome { */ export 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. + * Sets the parameters for the VPN session. This should be called immediately after 'connected' is Recieved 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. */ @@ -5685,10 +5689,10 @@ declare namespace chrome { */ export function notifyConnectionStateChanged(state: string, callback?: Function): void; - /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ + /** Triggered when a message is Recieved from the platform for a VPN configuration owned by the extension. */ export var onPlatformMessage: VpnPlatformMessageEvent; - /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - export var onPacketReceived: VpnPacketReceptionEvent; + /** Triggered when an IP packet is Recieved via the tunnel for the VPN session owned by the extension. */ + export var onPacketRecieved: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ export var onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ @@ -6622,7 +6626,7 @@ declare namespace chrome { 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.

+ * @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 Recieves.

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. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index c0dc6402a6..3a36322dc8 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -360,4 +360,55 @@ 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), function (bytes_sent) { + if (chrome.runtime.lastError) { + console.log("Send failed: " + chrome.runtime.lastError.message); + } else { + console.log("Sent " + bytes_sent + " bytes") + } + }); + } + }); + chrome.bluetoothSocket.onRecieve.addListener((receiveInfo) => { + if (receiveInfo.socketId != createInfo.socketId) + return; + // receiveInfo.data is an ArrayBuffer. + }); + }); +}); + + From f96df8e80a33b242fb786357b120d778e3910ceb Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 14:59:58 +0200 Subject: [PATCH 006/289] Fix typo --- types/chrome-apps/test/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 3a36322dc8..4bf47f0655 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -403,7 +403,7 @@ chrome.bluetooth.getDevices((devices) => { }); } }); - chrome.bluetoothSocket.onRecieve.addListener((receiveInfo) => { + chrome.bluetoothSocket.onReceive.addListener((receiveInfo) => { if (receiveInfo.socketId != createInfo.socketId) return; // receiveInfo.data is an ArrayBuffer. From 8bcbee8944a0c067fc49ff261f45b998d1144197 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 15:02:01 +0200 Subject: [PATCH 007/289] Typo fix --- types/chrome-apps/index.d.ts | 100 +++++++++++++++++------------------ 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 45f3bb294a..601eab047e 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -891,7 +891,7 @@ declare namespace chrome { */ uuids?: string[]; /** - * The Recieved signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. + * The Received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. * @since Chrome 44 */ inquiryRssi: number; @@ -1374,7 +1374,7 @@ declare namespace chrome { } /** - * Use the chrome.bluetoothSocket API to send and Recieve data to Bluetooth devices using RFCOMM and L2CAP connections. + * 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. @@ -1391,7 +1391,7 @@ declare namespace chrome { persistent?: boolean; /** An application-defined string associated with the socket. */ name?: string; - /** (integer) The size of the buffer used to Recieve data. The default value is 4096. */ + /** (integer) The size of the buffer used to Receive data. The default value is 4096. */ bufferSize?: number; } interface ListenOptions { @@ -1436,7 +1436,7 @@ declare namespace chrome { name?: string; /** * (integer) - * The size of the buffer used to Recieve data. + * The size of the buffer used to Receive data. * If no buffer size has been specified explictly, * the value is not provided. */ @@ -1515,18 +1515,18 @@ declare namespace chrome { */ error: OnAcceptErrorCode; } - interface OnRecieveEventData { + interface OnReceiveEventData { /** The socket identifier. (integer) */ socketId: number; - /** The data Recieved, with a maxium size of bufferSize. */ + /** The data Received, with a maxium size of bufferSize. */ data: ArrayBuffer; } - enum OnRecieveErrorCode { + enum OnReceiveErrorCode { "disconnected", "system_error", "not_connected" } - interface OnRecieveErrorEventData { + interface OnReceiveErrorEventData { /** The server socket identifier. (integer) */ socketId: number; /** The error message */ @@ -1545,8 +1545,8 @@ declare namespace chrome { } interface OnAcceptEvent extends chrome.events.Event<(info: OnAcceptInfoData) => void> { } interface OnAcceptErrorEvent extends chrome.events.Event<(info: OnAcceptErrorEventData) => void> { } - interface OnRecieveEvent extends chrome.events.Event<(info: OnRecieveEventData) => void> { } - interface OnRecieveErrorEvent extends chrome.events.Event<(info: OnRecieveErrorEventData) => 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 @@ -1572,9 +1572,9 @@ declare namespace chrome { * 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 onRecieveevent is raised. When a socket is connected - * and un-paused, onRecieve events are raised again when - * messages are Recieved. When a listening 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. @@ -1626,10 +1626,10 @@ declare namespace chrome { /** * Connects the socket to a remote Bluetooth device. * When the connect operation completes successfully, - * onRecieve events are raised when data is Recieved + * onReceive events are raised when data is Received * from the peer. If a network error occur while the - * runtime is receiving packets, a onRecieveError - * event is raised, at which point no more onRecieve + * 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. * @@ -1690,16 +1690,16 @@ declare namespace chrome { */ var onAcceptError: OnAcceptErrorEvent; /** - * Event raised when data has been Recieved for a given socket. + * Event raised when data has been Received for a given socket. */ - var onRecieve: OnRecieveEvent; + var 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 onRecieve events are + * the socket is set to paused and no more onReceive events are * raised for this socket. */ - var onRecieveError: OnRecieveErrorEvent; + var onReceiveError: OnReceiveErrorEvent; } //////////////////// @@ -2639,7 +2639,7 @@ declare namespace chrome { export function unmount(options: UnmountOptions, callback?: () => void): void; /** * Returns all file systems mounted by the extension. - * @param callback Callback to Recieve the result of getAll function. + * @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) {...}; */ @@ -2647,7 +2647,7 @@ declare namespace chrome { /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. - * @param callback Callback to Recieve the result of get function. + * @param callback Callback to Receive the result of get function. * The callback parameter should be a function that looks like this: * function(FileSystemInfo fileSystem) {...}; */ @@ -2719,7 +2719,7 @@ declare namespace chrome { // Google Cloud Messaging //////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and Recieve messages through the Google Cloud Messaging Service. + * 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' */ @@ -2805,7 +2805,7 @@ declare namespace chrome { */ export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; - /** Fired when a message is Recieved through GCM. */ + /** Fired when a message is Received through GCM. */ export var onMessage: MessageReceptionEvent; /** 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; @@ -4154,12 +4154,12 @@ declare namespace chrome { bytesSent?: number; } - interface RecieveEventArgs { + interface ReceiveEventArgs { socketId: number; data: ArrayBuffer; } - interface RecieveErrorEventArgs { + interface ReceiveErrorEventArgs { socketId: number; resultCode: number; } @@ -4203,8 +4203,8 @@ declare namespace chrome { export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; - export var onRecieve: chrome.events.Event<(args: RecieveEventArgs) => void>; - export var onRecieveError: chrome.events.Event<(args: RecieveErrorEventArgs) => void>; + export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } /** @@ -4408,7 +4408,7 @@ declare namespace chrome { } /** - * Use the chrome.sockets.udp API to send and Recieve data over the network + * Use the chrome.sockets.udp API to send and Receive data over the network * using UDP connections. This API supersedes the UDP functionality previously * found in the 'socket' API. * @@ -4425,14 +4425,14 @@ declare namespace chrome { bytesSent?: number; } - interface RecieveEventArgs { + interface ReceiveEventArgs { socketId: number; data: ArrayBuffer; remoteAddress: string; remotePort: number; } - interface RecieveErrorEventArgs { + interface ReceiveErrorEventArgs { socketId: number; resultCode: number; } @@ -4454,8 +4454,8 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to Recieve data. If the buffer is too - * small to Recieve the UDP packet, data is lost. The default value is + * 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. */ bufferSize?: number; @@ -4478,13 +4478,13 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to Recieve data. If no buffer size ha + * The size of the buffer used to Receive data. If no buffer size ha * been specified explictly, the value is not provided. */ bufferSize?: number; /** - * Flag indicating whether the socket is blocked from firing onRecieve + * Flag indicating whether the socket is blocked from firing onReceive * events. */ paused: boolean; @@ -4529,7 +4529,7 @@ declare namespace chrome { /** * Pauses or unpauses a socket. A paused socket is blocked from firing - * onRecieve events. + * onReceive events. * * @see https://developer.chrome.com/apps/sockets_udp#method-setPaused * @param socketId The socket ID. @@ -4543,7 +4543,7 @@ declare namespace chrome { * Binds the local address and port for the socket. For a client socket, it * is recommended to use port 0 to let the platform pick a free port. * - * Once the bind operation completes successfully, onRecieve events are + * Once the bind operation completes successfully, onReceive events are * raised when UDP packets arrive on the address/port specified -- unless * the socket is paused. * @@ -4601,7 +4601,7 @@ declare namespace chrome { export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** - * Joins the multicast group and starts to Recieve packets from that group. + * Joins the multicast group and starts to Receive packets from that group. * The socket must be bound to a local port before calling this method. * * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup @@ -4649,7 +4649,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 - * Recieve 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 @@ -4684,21 +4684,21 @@ declare namespace chrome { export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; /** - * Event raised when a UDP packet has been Recieved for the given socket. + * Event raised when a UDP packet has been Received for the given socket. * - * @see https://developer.chrome.com/apps/sockets_udp#event-onRecieve + * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive */ - export var onRecieve: chrome.events.Event<(args: RecieveEventArgs) => void>; + export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting * for data on the socket address and port. Once this event is raised, the - * socket is paused and no more onRecieve events will be raised for this + * socket is paused and no more onReceive events will be raised for this * socket until the socket is resumed. * - * @see https://developer.chrome.com/apps/sockets_udp#event-onRecieveError + * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError */ - export var onRecieveError: chrome.events.Event<(args: RecieveErrorEventArgs) => void>; + export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } //////////////////// @@ -5669,7 +5669,7 @@ declare namespace chrome { */ export function destroyConfig(id: string, callback?: Function): void; /** - * Sets the parameters for the VPN session. This should be called immediately after 'connected' is Recieved from the platform. This will succeed only when the VPN session is owned by the extension. + * 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. */ @@ -5689,10 +5689,10 @@ declare namespace chrome { */ export function notifyConnectionStateChanged(state: string, callback?: Function): void; - /** Triggered when a message is Recieved from the platform for a VPN configuration owned by the extension. */ + /** Triggered when a message is Received from the platform for a VPN configuration owned by the extension. */ export var onPlatformMessage: VpnPlatformMessageEvent; - /** Triggered when an IP packet is Recieved via the tunnel for the VPN session owned by the extension. */ - export var onPacketRecieved: VpnPacketReceptionEvent; + /** Triggered when an IP packet is Received via the tunnel for the VPN session owned by the extension. */ + export var onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ export var onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ @@ -6626,7 +6626,7 @@ declare namespace chrome { 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 Recieves.

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.

+ * @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. */ From bf589d73452f6766fc81534127f7ccc5c2c9fe18 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 15:25:25 +0200 Subject: [PATCH 008/289] HID typings, but missing documentation --- types/chrome-apps/index.d.ts | 91 ++++++++++++++++++++++++++---------- 1 file changed, 66 insertions(+), 25 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 601eab047e..52adabdb9c 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -891,7 +891,7 @@ declare namespace chrome { */ uuids?: string[]; /** - * The Received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. + * The received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. * @since Chrome 44 */ inquiryRssi: number; @@ -1374,7 +1374,7 @@ declare namespace chrome { } /** - * Use the chrome.bluetoothSocket API to send and Receive data to Bluetooth devices using RFCOMM and L2CAP connections. + * 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. @@ -1391,7 +1391,7 @@ declare namespace chrome { persistent?: boolean; /** An application-defined string associated with the socket. */ name?: string; - /** (integer) The size of the buffer used to Receive data. The default value is 4096. */ + /** (integer) The size of the buffer used to receive data. The default value is 4096. */ bufferSize?: number; } interface ListenOptions { @@ -1436,7 +1436,7 @@ declare namespace chrome { name?: string; /** * (integer) - * The size of the buffer used to Receive data. + * The size of the buffer used to receive data. * If no buffer size has been specified explictly, * the value is not provided. */ @@ -1518,7 +1518,7 @@ declare namespace chrome { interface OnReceiveEventData { /** The socket identifier. (integer) */ socketId: number; - /** The data Received, with a maxium size of bufferSize. */ + /** The data received, with a maxium size of bufferSize. */ data: ArrayBuffer; } enum OnReceiveErrorCode { @@ -1574,7 +1574,7 @@ declare namespace chrome { * 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, + * 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. @@ -1626,7 +1626,7 @@ declare namespace chrome { /** * Connects the socket to a remote Bluetooth device. * When the connect operation completes successfully, - * onReceive events are raised when data is Received + * 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 @@ -1690,7 +1690,7 @@ declare namespace chrome { */ var onAcceptError: OnAcceptErrorEvent; /** - * Event raised when data has been Received for a given socket. + * Event raised when data has been received for a given socket. */ var onReceive: OnReceiveEvent; /** @@ -2639,7 +2639,7 @@ declare namespace chrome { export 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. + * @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) {...}; */ @@ -2647,7 +2647,7 @@ declare namespace chrome { /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. - * @param callback Callback to Receive the result of get function. + * @param callback Callback to receive the result of get function. * The callback parameter should be a function that looks like this: * function(FileSystemInfo fileSystem) {...}; */ @@ -2719,7 +2719,7 @@ declare namespace chrome { // Google Cloud Messaging //////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and Receive messages through the Google Cloud Messaging Service. + * 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' */ @@ -2805,7 +2805,7 @@ declare namespace chrome { */ export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; - /** Fired when a message is Received through GCM. */ + /** Fired when a message is received through GCM. */ export var onMessage: MessageReceptionEvent; /** 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; @@ -2817,11 +2817,52 @@ declare namespace chrome { // 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. + * + * Permissions: "hid" + * @since Available since Chrome 38 */ namespace hid { - /** NOT YET IMPLEMENTED */ + interface Collection { + usagePage: number; + usage: number; + reportIds: number[]; + } + interface HidDeviceInfo { + deviceId: number; + vendorId: number; + productId: number; + /** @since Chrome 46 */ + productName: string; + serialNumber: string; + collections: Collection[]; + maxInputReportSize: number; + maxOutputReportSize: number; + maxFeatureReportSize: number; + reportDescriptor: ArrayBuffer; + } + interface DeviceFilter { + vendorId?: number; + productId?: number; + usagePage?: number; + usage?: number; + } + function getDevices(options: { filters?: DeviceFilter[] }, callback: (devices: HidDeviceInfo[]) => void): void; + function getUserSelectedDevices(callback: (devices: HidDeviceInfo) => void): void; + function getUserSelectedDevices(options: { multiple: boolean, filters?: DeviceFilter[] }, callback: (devices: HidDeviceInfo) => void): void; + function connect(deviceId: number, callback: (connection: { connectionId: number }) => void): void; + function disconnect(connectionId: number, callback?: () => void): void; + function receive(connectionId: number, callback: (reportId: number, data: ArrayBuffer) => void): void; + function send(connectionId: number, reportId: number, data: ArrayBuffer, callback: () => void): void; + function receiveFeatureReport(connectionId: number, reportId: number, callback: (data: ArrayBuffer) => void): void; + function sendFeatureReport(connectionId: number, reportId: number, data: ArrayBuffer, callback: () => void): void; + var onDeviceAdded: chrome.events.Event<(device: HidDeviceInfo) => void>; + var onDeviceRemoved: chrome.events.Event<(deviceId: number) => void>; } //////////////////// @@ -4408,7 +4449,7 @@ declare namespace chrome { } /** - * Use the chrome.sockets.udp API to send and Receive data over the network + * Use the chrome.sockets.udp API to send and receive data over the network * using UDP connections. This API supersedes the UDP functionality previously * found in the 'socket' API. * @@ -4455,7 +4496,7 @@ declare namespace chrome { /** * 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 + * small to receive the UDP packet, data is lost. The default value is * 4096. */ bufferSize?: number; @@ -4478,7 +4519,7 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to Receive data. If no buffer size ha + * The size of the buffer used to receive data. If no buffer size ha * been specified explictly, the value is not provided. */ bufferSize?: number; @@ -4601,7 +4642,7 @@ declare namespace chrome { export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** - * Joins the multicast group and starts to Receive packets from that group. + * Joins the multicast group and starts to receive packets from that group. * The socket must be bound to a local port before calling this method. * * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup @@ -4649,7 +4690,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 @@ -4684,7 +4725,7 @@ declare namespace chrome { export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; /** - * Event raised when a UDP packet has been Received for the given socket. + * Event raised when a UDP packet has been received for the given socket. * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive */ @@ -5669,7 +5710,7 @@ declare namespace chrome { */ export 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. + * 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. */ @@ -5689,9 +5730,9 @@ declare namespace chrome { */ export function notifyConnectionStateChanged(state: string, callback?: Function): void; - /** Triggered when a message is Received from the platform for a VPN configuration owned by the extension. */ + /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ export var onPlatformMessage: VpnPlatformMessageEvent; - /** Triggered when an IP packet is Received via the tunnel for the VPN session owned by the extension. */ + /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ export var onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ export var onConfigRemoved: VpnConfigRemovalEvent; @@ -6626,7 +6667,7 @@ declare namespace chrome { 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.

+ * @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. */ From 5b92a4a7dc8f487f51c784e745fcc6f865881873 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 15:54:30 +0200 Subject: [PATCH 009/289] Documentation and testing added --- types/chrome-apps/index.d.ts | 158 +++++++++++++++++++++++++++++++- types/chrome-apps/test/index.ts | 11 +++ 2 files changed, 166 insertions(+), 3 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 52adabdb9c..94684df440 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -12,6 +12,17 @@ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// declare namespace chrome { + ////////////// + // 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; + + //////////////////// // Accessibility Features //////////////////// @@ -2829,39 +2840,180 @@ declare namespace chrome { */ namespace hid { interface Collection { + /** HID usage page identifier. */ usagePage: number; + /** Page-defined usage identifier. */ usage: number; + /** Report IDs which belong to the collection and to its children. */ reportIds: number[]; } interface HidDeviceInfo { + /** Opaque device ID. */ deviceId: number; + /** Vendor ID. */ vendorId: number; + /** Product ID. */ productId: number; - /** @since Chrome 46 */ + /** + * 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: number; + /** Top-level collection's maximum output report size. */ maxOutputReportSize: number; + /** Top-level collection's maximum feature report size. */ maxFeatureReportSize: number; + /** + * Raw device report descriptor (not available on Windows). + * @since Chrome 42 + * */ reportDescriptor: ArrayBuffer; } interface DeviceFilter { + /** Device vendor ID. */ vendorId?: number; + /** Device product ID, only checked only if the vendor ID matches. */ productId?: number; + /** HID usage page identifier. */ usagePage?: number; + /** HID usage identifier, checked only if the HID usage page matches. */ usage?: number; } - function getDevices(options: { filters?: DeviceFilter[] }, callback: (devices: HidDeviceInfo[]) => void): void; + 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; - function getUserSelectedDevices(options: { multiple: boolean, filters?: DeviceFilter[] }, 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} + * @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 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: number, 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. (integer) + * * data - The report data, the report ID prefix (if present) is removed. + */ function receive(connectionId: number, callback: (reportId: number, 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. (integer) + * @param reportId The connectionId returned by connect. (integer) + * @param data The report data. + * @param callback + */ function send(connectionId: number, reportId: number, data: ArrayBuffer, callback: () => void): void; + /** + * Request a feature report from the device. + * @param connectionId The connectionId returned by connect. (integer) + * @param reportId The report ID, or 0 if none. (integer) + * @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: number, reportId: number, 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. (integer) + * @param reportId The report ID to use, or 0 if none. (integer) + * @param data The report data. + * @param callback + */ function sendFeatureReport(connectionId: number, reportId: number, 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} + */ var 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}. + */ var onDeviceRemoved: chrome.events.Event<(deviceId: number) => void>; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 4bf47f0655..814a517d52 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -411,4 +411,15 @@ chrome.bluetooth.getDevices((devices) => { }); }); +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; + }); +}); + From 96db4a48a387122dad0a1ccb18bbe14de31ca207 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 16:05:14 +0200 Subject: [PATCH 010/289] InstanceID Typings --- types/chrome-apps/index.d.ts | 53 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 94684df440..ec1c575bac 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -3227,17 +3227,66 @@ declare namespace chrome { //////////////////// /** * Use chrome.instanceID to access the Instance ID service. + * Permissions: "gcm" * @since Chrome 46 */ namespace instanceID { - /** NOT YET IMPLEMENTED */ + interface TokenParams { + authorizedEntity: string; + scope: string; + options?: { [key: string]: string }; + } + interface DeleteTokenParams { + authorizedEntity: string; + 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. */ + var onTokenRefresh: chrome.events.Event<() => void>; } //////////////////// // 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: http://www.w3.org/TR/discovery-api/ * @since Chrome 31 */ namespace mdns { From faec8c41f20367d066a86667e6d034c8f27b3437 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 30 Jul 2018 16:14:33 +0200 Subject: [PATCH 011/289] Typings for mdns complete --- types/chrome-apps/index.d.ts | 44 ++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index ec1c575bac..dcc73ba928 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -3286,11 +3286,51 @@ declare namespace chrome { // 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[Spec link]{@link http://www.w3.org/TR/discovery-api/} + * 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. + */ + var onServiceList: chrome.events.Event<(services: Service[]) => void>; + } //////////////////// From 44a1d68a16d2d96f33f20be06f6a2fb6967fd7d2 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 31 Jul 2018 09:13:07 +0200 Subject: [PATCH 012/289] typings for chrome.syncFileSystem --- types/chrome-apps/index.d.ts | 149 ++++++++++++++++++++++++++++++-- types/chrome-apps/test/index.ts | 11 +++ 2 files changed, 154 insertions(+), 6 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index dcc73ba928..5d7cf325d0 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -4359,12 +4359,13 @@ declare namespace chrome { // 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 @@ -5098,11 +5099,147 @@ declare namespace chrome { // 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.) + */ + enum 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. + */ + enum FileStatus { + "synced", + "pending", + "conflicting" + } + enum ConflictResolutionPolicy { + "last_write_win", + "manual" + } + enum Action { + "added", + "updated", + "deleted" + } + enum 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). */ + var onServiceStatusChanged: chrome.events.Event<(detail: { state: ServiceStatus, description: string }) => void>; + /** Fired when a file has been updated by the background sync service. */ + var onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 814a517d52..f3db9d5cc1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -422,4 +422,15 @@ chrome.hid.getDevices({ }); }); +chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { + if (policy === chrome.syncFileSystem.ConflictResolutionPolicy.manual) { + chrome.syncFileSystem.requestFileSystem((fs) => { + if (fs.root.isFile) { + throw new Error('It was a file!'); + } + }); + } +}) + + From 20d550a1651d6b7ba4abc85adbd9edc98c9eb25f Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 31 Jul 2018 12:26:50 +0200 Subject: [PATCH 013/289] Major cleanup - comments and documentation review --- types/chrome-apps/index.d.ts | 3094 +++++++++++++++---------------- types/chrome-apps/test/index.ts | 2 +- 2 files changed, 1539 insertions(+), 1557 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 5d7cf325d0..8a601d2b38 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -22,23 +22,40 @@ declare namespace chrome { /** @deprecated Should never be used, used to guide migrations. */ type deprecated = never; + // Not proper types, but used to give the programmer a hint // - //////////////////// - // Accessibility Features - //////////////////// /** + * Integer + * Whole number + */ + type integer = number; + /** + * Double + * Decimal number + */ + 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; } @@ -53,7 +70,7 @@ declare namespace chrome { * • 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. */ + /** 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; } @@ -90,14 +107,14 @@ declare namespace chrome { /** * Gets the value of a setting. * @param details Which setting to consider. - * @param callback The callback parameter should be a function that looks like this: + * @param callback The callback parameter should be a function that looks like this: * function(object details) {...}; */ get(details: AccessibilityFeaturesGetArg, callback: (details: AccessibilityFeaturesCallbackArg) => void): void; /** * Sets the value of a setting. * @param details Which setting to change. - * @param callback Called at the completion of the set operation. + * @param callback Called at the completion of the set operation. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ @@ -105,7 +122,7 @@ declare namespace chrome { /** * Clears the setting, restoring any default value. * @param details Which setting to clear. - * @param callback Called at the completion of the clear operation. + * @param callback Called at the completion of the clear operation. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ @@ -115,83 +132,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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var 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; + var switchAccess: AccessibilityFeaturesSetting; /** * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 42. */ - export var animationPolicy: AccessibilityFeaturesSetting; + var 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; @@ -209,7 +228,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. @@ -220,58 +239,59 @@ 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: + * @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: + * @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: + * @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; + var 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' | @@ -359,29 +379,30 @@ declare namespace chrome { * 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; + var onEmbedRequest: EmbedRequestedEvent; /** * Fired when an app is launched from the launcher. */ - export var onLaunched: LaunchedEvent; + var onLaunched: LaunchedEvent; /** * 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; + var onRestarted: RestartedEvent; } //////////////////// // 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 { interface ContentBounds { @@ -638,7 +659,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; /** @@ -696,23 +717,23 @@ declare namespace chrome { * @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; + 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; + 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; + 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[]; + function getAll(): AppWindow[]; /** * Whether the current platform supports windows being visible on all workspaces. */ - export function canSetVisibleOnAllWorkspaces(): boolean; + function canSetVisibleOnAllWorkspaces(): boolean; } @@ -720,12 +741,15 @@ declare namespace chrome { // 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'; interface AudioDeviceInfo { /** The unique identifier of the audio device. */ id: string; @@ -761,10 +785,8 @@ 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; } interface OnLevelChangedEvent { /** @@ -812,42 +834,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)=> 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 {()=> 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; + var 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; + var onMuteChanged: OnMuteChangedEvent; /** Fired when audio devices change, either new devices being added, or existing devices being removed. */ - export var onDeviceListChanged: OnDeviceListChangedEvent; + var 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 { @@ -927,42 +951,46 @@ declare namespace chrome { 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. + * @param callback Called when the search is completed. */ - export function getDevices(callback: (devices: Device[]) => void): void; + 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. + * @param callback Called when the search is completed. */ - export function getDevices(filter: DeviceFilter, callback: (devices: 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; + var onAdapterStateChanged: BluetoothEvent; /** Fired when information about a new Bluetooth device is available. */ - export var onDeviceAdded: BluetoothEvent; + var onDeviceAdded: BluetoothEvent; /** Fired when information about a known Bluetooth device has changed. */ - export var onDeviceChanged: BluetoothEvent; + var 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; + var 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 { @@ -1091,14 +1119,14 @@ declare namespace chrome { /** * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect. * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened. - * @param callback Called when the connect request has completed. + * @param callback Called when the connect request has completed. */ function connect(deviceAddress: string, callback: () => void): void; /** * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect. * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened. * @param properties Connection properties (optional). - * @param callback Called when the connect request has completed. + * @param callback Called when the connect request has completed. */ function connect(deviceAddress: string, properties: IProperties, callback: () => void): void; /** @@ -1110,53 +1138,53 @@ declare namespace chrome { /** * Get the GATT service with the given instance ID. * @param serviceId The instance ID of the requested GATT service. - * @param callback Called with the requested Service object. + * @param callback Called with the requested Service object. */ 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. + * @param callback Called with the created services's unique ID. */ function createService(service: Service, callback: () => void): void; /** * Get all the GATT services that were discovered on the remote device with the given device address. * Note: If service discovery is not yet complete on the device, this API will return a subset (possibly empty) of services. A work around is to add a time based delay and/or call repeatedly until the expected number of services is returned. * @param deviceAddress The Bluetooth address of the remote device whose GATT services should be returned. - * @param callback Called with the list of requested Service objects. + * @param callback Called with the list of requested Service objects. */ function getServices(deviceAddress: string, callback: (result: Service[]) => void): void; /** * Get the GATT characteristic with the given instance ID that belongs to the given GATT service, if the characteristic exists. * @param characteristicId The instance ID of the requested GATT characteristic. - * @param callback Called with the requested Characteristic object. + * @param callback Called with the requested Characteristic object. */ 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. - * @param callback Called with the created characteristic's unique ID. + * @param callback Called with the created characteristic's unique ID. */ function createCharacteristic(characteristic: Characteristic, serviceId: string, callback: (characteristicId: string) => void): void; /** * Get a list of all discovered GATT characteristics that belong to the given service. * @param serviceId The instance ID of the GATT service whose characteristics should be returned. - * @param callback Called with the list of characteristics that belong to the given service. + * @param callback Called with the list of characteristics that belong to the given service. */ function getCharacteristics(serviceId: string, callback: (result: Characteristic[]) => void): void; /** * Get a list of GATT services that are included by the given service. * @param serviceId The instance ID of the GATT service whose included services should be returned. - * @param callback Called with the list of GATT services included from the given service. + * @param callback Called with the list of GATT services included from the given service. */ function getIncludedServices(serviceId: string, callback: (result: Service[]) => void): void; /** * Get the GATT characteristic descriptor with the given instance ID. * @param descriptorId The instance ID of the requested GATT characteristic descriptor. - * @param callback Called with the requested Descriptor object. + * @param callback Called with the requested Descriptor object. */ function getDescriptor(descriptorId: string, callback: (result: Descriptor) => void): void; /** @@ -1164,33 +1192,33 @@ declare namespace chrome { * @since Since Chrome 52. * @param descriptor The descriptor to create. * @param characteristicId ID of the characteristic to create this descriptor for. - * @param callback Called with the created desciptor's unique ID. + * @param callback Called with the created desciptor's unique ID. */ function createDescriptor(descriptor: Descriptor, characteristicId: string, callback: (descriptorId: string) => void): void; /** * Get a list of GATT characteristic descriptors that belong to the given characteristic. * @param characteristicId The instance ID of the GATT characteristic whose descriptors should be returned. - * @param callback Called with the list of descriptors that belong to the given characteristic. + * @param callback Called with the list of descriptors that belong to the given characteristic. */ function getDescriptors(characteristicId: string, callback: (result: Descriptor[]) => void): void; /** * Retrieve the value of a specified characteristic from a remote peripheral. * @param characteristicId The instance ID of the GATT characteristic whose value should be read from the remote device. - * @param callback Called with the Characteristic object whose value was requested. The value field of the returned Characteristic object contains the result of the read request. + * @param callback Called with the Characteristic object whose value was requested. The value field of the returned Characteristic object contains the result of the read request. */ function readCharacteristicValue(characteristicId: string, callback: (result: Characteristic) => void): void; /** * Write the value of a specified characteristic from a remote peripheral. * @param characteristicId The instance ID of the GATT characteristic whose value should be written to. * @param value The value that should be sent to the remote characteristic as part of the write request. - * @param callback Called when the write request has completed. + * @param callback Called when the write request has completed. */ function writeCharacteristicValue(characteristicId: string, value: ArrayBuffer, callback: () => void): void; /** * Enable value notifications/indications from the specified characteristic. Once enabled, an application can listen to notifications using the onCharacteristicValueChanged event. * @see onCharacteristicValueChanged * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on. - * @param callback Called when the request has completed. + * @param callback Called when the request has completed. */ function startCharacteristicNotifications(characteristicId: string, callback: () => void): void; /** @@ -1198,7 +1226,7 @@ declare namespace chrome { * @see onCharacteristicValueChanged * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on. * @param properties Notification session properties (optional). - * @param callback Called when the request has completed. + * @param callback Called when the request has completed. */ function startCharacteristicNotifications(characteristicId: string, properties: IProperties, callback: () => void): void; /** @@ -1216,20 +1244,20 @@ declare namespace chrome { * @since Since Chrome 52. * @param characteristicId The characteristic to send the notication for. * @param notification Notification object - * @param callback Callback called once the notification or indication has been sent successfully. + * @param callback Callback called once the notification or indication has been sent successfully. */ function notifyCharacteristicValueChanged(characteristicId: string, notification: INotification, callback: () => void): void; /** * Retrieve the value of a specified characteristic descriptor from a remote peripheral. * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be read from the remote device. - * @param callback Called with the Descriptor object whose value was requested. The value field of the returned Descriptor object contains the result of the read request. + * @param callback Called with the Descriptor object whose value was requested. The value field of the returned Descriptor object contains the result of the read request. */ function readDescriptorValue(descriptorId: string, callback: (result: Descriptor) => void): void; /** * Write the value of a specified characteristic descriptor from a remote peripheral. * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be written to. * @param value The value that should be sent to the remote descriptor as part of the write request. - * @param callback Called when the write request has completed. + * @param callback Called when the write request has completed. */ function writeDescriptorValue(descriptorId: string, value: ArrayBuffer, callback: () => void): void; /** @@ -1240,7 +1268,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param serviceId Unique ID of a created service. - * @param callback Callback with the result of the register operation. + * @param callback Callback with the result of the register operation. */ function registerService(serviceId: string, callback: () => void): void; /** @@ -1251,7 +1279,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param serviceId Unique ID of a current registered service. - * @param callback Callback with the result of the register operation. + * @param callback Callback with the result of the register operation. */ function unregisterService(serviceId: string, callback: () => void): void; /** @@ -1281,7 +1309,7 @@ declare namespace chrome { * (including the discovery of Bluetooth Low Energy devices). * @since Since Chrome 47. * @param advertisement The advertisement to advertise. - * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement. + * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement. */ function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: number) => void): void; /** @@ -1290,13 +1318,13 @@ declare namespace chrome { * to stop advertising might be to restart the device. * @since Since Chrome 47. * @param advertisementId Id of the advertisement to unregister. - * @param callback Called once the advertisement is unregistered and is no longer being advertised. + * @param callback Called once the advertisement is unregistered and is no longer being advertised. */ function unregisterAdvertisement(advertisementId: number, callback: () => void): void; /** * Resets advertising on the current device. It will unregister and stop all existing advertisements. * @since Since Chrome 61. - * @param callback Called once the advertisements are reset. + * @param callback Called once the advertisements are reset. */ function resetAdvertising(callback: () => void): void; /** @@ -1308,7 +1336,7 @@ declare namespace chrome { * @since Since Chrome 55. * @param minInterval Minimum interval between advertisments (in milliseconds). This cannot be lower than 20ms (as per the spec). * @param maxInterval Maximum interval between advertisments (in milliseconds). This cannot be more than 10240ms (as per the spec). - * @param callback Called once the interval has been set. + * @param callback Called once the interval has been set. */ function setAdvertisingInterval(minInterval: number, maxInterval: number, callback: () => void): void; /** @@ -1385,10 +1413,10 @@ declare namespace chrome { } /** - * 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. + * @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 { @@ -1402,26 +1430,28 @@ declare namespace chrome { persistent?: boolean; /** An application-defined string associated with the socket. */ name?: string; - /** (integer) The size of the buffer used to receive data. The default value is 4096. */ - bufferSize?: number; + /** + * @default 4096 + * @description + * The size of the buffer used to receive data. + * */ + bufferSize?: integer; } interface ListenOptions { /** - * (integer) * 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?: number; + channel?: integer; /** - * (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?: number; + psm?: integer; /** * Length of the socket's listen queue. * The default value depends on the operating system's host subsystem. @@ -1430,10 +1460,9 @@ declare namespace chrome { } interface SocketInfo { /** - * (integer) * The socket identifier. * */ - socketId: number; + socketId: integer; /** * Flag indicating if the socket remains * open when the event page of the application @@ -1446,12 +1475,11 @@ declare namespace chrome { */ name?: string; /** - * (integer) * The size of the buffer used to receive data. * If no buffer size has been specified explictly, * the value is not provided. */ - bufferSize?: number; + bufferSize?: integer; /** * Flag indicating whether a connected socket * blocks its peer from sending more data, or @@ -1483,20 +1511,18 @@ declare namespace chrome { interface CreateInfo { /** - * (integer) * 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: number; + socketId: integer; } interface OnAcceptInfoData { - /** The server socket identifier. (integer) */ - socketId: number; + /** The server socket identifier. */ + socketId: integer; /** - * (integer) * The client socket identifier, i.e. the socket * identifier of the newly established connection. * This socket identifier should be used only with @@ -1505,15 +1531,15 @@ declare namespace chrome { * be explictly un-paused by the application to start * receiving data. */ - clientSocketId: number; + clientSocketId: integer; } enum OnAcceptErrorCode { "system_error", "not_listening" } interface OnAcceptErrorEventData { - /** The server socket identifier. (integer) */ - socketId: number; + /** The server socket identifier. */ + socketId: integer; /** The error message */ errorMessage: string; /** @@ -1527,8 +1553,8 @@ declare namespace chrome { error: OnAcceptErrorCode; } interface OnReceiveEventData { - /** The socket identifier. (integer) */ - socketId: number; + /** The socket identifier. */ + socketId: integer; /** The data received, with a maxium size of bufferSize. */ data: ArrayBuffer; } @@ -1538,8 +1564,8 @@ declare namespace chrome { "not_connected" } interface OnReceiveErrorEventData { - /** The server socket identifier. (integer) */ - socketId: number; + /** The server socket identifier. */ + socketId: integer; /** The error message */ errorMessage: string; /** @@ -1560,22 +1586,22 @@ declare namespace chrome { interface OnReceiveErrorEvent extends chrome.events.Event<(info: OnReceiveErrorEventData) => void> { } /** * Creates a Bluetooth socket. - * @param callback Called when the socket has been created + * @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 + * @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. (integer) + * @param socketId The socket identifier. * @param properties The properties to update. * @param [callback] Called when the properties are updated. */ - function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; /** * Enables or disables a connected socket from * receiving messages from its peer, or a listening @@ -1590,7 +1616,7 @@ declare namespace chrome { * then additional connection requests are refused. * onAccept events are raised only when the socket is un-paused. * - * @param socketId The socket identifier. (integer) + * @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 @@ -1599,41 +1625,41 @@ declare namespace chrome { * See setPaused. The default value is "false". * @param [callback] Callback from the setPaused method. */ - function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; /** * Listen for connections using the RFCOMM protocol. * - * @param socketId The socket identifier. (integer) + * @param socketId The socket identifier. * @param uuid Service UUID to listen on. - * @param callback Called when listen operation completes. + * @param callback Called when listen operation completes. */ - function listenUsingRfcomm(socketId: number, uuid: string, callback: () => void): void; + function listenUsingRfcomm(socketId: integer, uuid: string, callback: () => void): void; /** * Listen for connections using the RFCOMM protocol. * - * @param socketId The socket identifier. (integer) + * @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. + * @param callback Called when listen operation completes. */ - function listenUsingRfcomm(socketId: number, uuid: string, options: ListenOptions, callback: () => void): void; + function listenUsingRfcomm(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void; /** * Listen for connections using the L2CAP protocol. * - * @param socketId The socket identifier. (integer) + * @param socketId The socket identifier. * @param uuid Service UUID to listen on. - * @param callback Called when listen operation completes. + * @param callback Called when listen operation completes. */ - function listenUsingL2cap(socketId: number, uuid: string, callback: () => void): void; + function listenUsingL2cap(socketId: integer, uuid: string, callback: () => void): void; /** * Listen for connections using the L2CAP protocol. * - * @param socketId The socket identifier. (integer) + * @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. + * @param callback Called when listen operation completes. */ - function listenUsingL2cap(socketId: number, uuid: string, options: ListenOptions, callback: () => void): void; + 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, @@ -1644,18 +1670,18 @@ declare namespace chrome { * event will be raised for this socket until the * setPaused(false) method is called. * - * @param socketId The socket identifier. (integer) + * @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. + * @param callback Called when the connect attempt is complete. */ - function connect(socketId: number, address: string, uuid: string, callback: () => void): void; + function connect(socketId: integer, address: string, uuid: string, callback: () => void): void; /** * Disconnects the socket. The socket identifier remains valid. - * @param socketId The socket identifier. (integer) + * @param socketId The socket identifier. * @param [callback] Called when the disconnect attempt is complete. */ - function disconnect(socketId: number, callback?: () => void): void; + function disconnect(socketId: integer, callback?: () => void): void; /** * Disconnects and destroys the socket. * Each socket created should be closed after use. @@ -1663,27 +1689,27 @@ declare namespace chrome { * function is called. However, the socket is guaranteed * to be closed only when the callback is invoked. * - * @param socketId The socket identifier. (integer) - * @param callback Called when the `close` operation completes + * @param socketId The socket identifier. + * @param callback Called when the `close` operation completes */ - function close(socketId: number, callback: () => void): void; + function close(socketId: integer, callback: () => void): void; /** * Sends data on the given Bluetooth socket. - * @param socketId The socket identifier. (integer) + * @param socketId The socket identifier. * @param data The data to send. * @param [callback] Called with the number of bytes sent. */ - function send(socketId: number, data: ArrayBuffer, callback?: (bytesSent: number) => void): void; + function send(socketId: integer, data: ArrayBuffer, callback?: (bytesSent: number) => void): void; /** * Retrieves the state of the given socket. - * @param socketId The socket identifier. (integer) - * @param callback Called when the socket state is available. + * @param socketId The socket identifier. + * @param callback Called when the socket state is available. * Callback returning object containing the socket information. */ - function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + 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. + * @param callback Called when the list of sockets is available. * Returns an array of socket info. */ function getSockets(callback: (sockets: SocketInfo[]) => void): void; @@ -1713,10 +1739,13 @@ declare namespace chrome { var onReceiveError: OnReceiveErrorEvent; } - //////////////////// - // Browser - //////////////////// + ///////////// + // 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. */ @@ -1731,10 +1760,10 @@ declare namespace chrome { * and Chrome profile. If no browser window for the Chrome profile is opened, * a new one is opened prior to creating the new tab. * @param options Configures how the tab should be opened. - * @param callback Called when the tab was successfully + * @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 @@ -1742,24 +1771,29 @@ 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 - //////////////////// + ////////////// + // Commands // + ////////////// /** - * 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': {...} + * @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; } @@ -1767,69 +1801,108 @@ 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) {...}; + * @param callback Called to return the registered 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; + var 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'; + enum 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'; + enum ItemType { + 'normal', + 'checkbox', + 'radio', + 'separator' + } 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. * @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; + /** + * The text for the context selection, if any. + * @since Since Chrome 35. + */ + selectionText?: string; + /** + * A flag indicating the state of a checkbox or radio item after it is clicked. + * @since Since Chrome 35. + */ + checked?: boolean; + /** + * 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; + /** + * A flag indicating whether the element is editable (text input, textarea, etc.). + * @since Since Chrome 35. + */ + editable: boolean; /** * Optional. * @since Since Chrome 35. @@ -1847,12 +1920,6 @@ declare namespace chrome { * If the element is a link, the URL it points to. */ linkUrl?: string; - /** - * Optional. - * @since Since Chrome 35. - * The parent ID, if any, for the item clicked. - */ - parentMenuItemId?: any; /** * Optional. * @since Since Chrome 35. @@ -1862,43 +1929,64 @@ declare namespace chrome { } 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'. */ + /** The type of menu item. Defaults to 'normal' if not specified. */ + type?: ItemType; + /** + * The unique ID to assign to this item. + * Mandatory for event pages. + * Cannot be the same as another ID for this extension. + */ + 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; - /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ - contexts?: 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; + /** + * 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; + /** + * 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. * Whether this context menu item is enabled or disabled. Defaults to true. * @since Since Chrome 20. */ 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. */ + /** 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[]; - /** - * 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. */ + /** 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; - /** - * 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; - /** - * @description Whether the item is visible in the menu. - * @since Since Chrome 62 - */ - visible?: boolean; } interface UpdateProperties { @@ -1912,11 +2000,11 @@ declare namespace chrome { 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. */ + /** 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. + * Whether the item is visible or not. * @since Since Chrome 62 */ visible?: boolean; @@ -1924,66 +2012,60 @@ declare namespace chrome { 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. - */ - export var ACTION_MENU_TOP_LEVEL_LIMIT: number; - /** * Removes all context menu items added by this extension. - * @param callback Called when removal is complete. + * @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; + 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. + * @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; + 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. + * @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; + 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. + * @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; + 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. + * @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; + 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. + * @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 remove(menuItemId: number, callback?: () => void): void; /** * Since Chrome 21. * Fired when a context menu item is clicked. */ - export var onClicked: MenuClickedEvent; + var onClicked: MenuClickedEvent; } @@ -1998,9 +2080,9 @@ declare namespace chrome { */ 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; } @@ -2014,11 +2096,11 @@ 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. + * @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; } //////////////////// @@ -2031,7 +2113,7 @@ declare namespace chrome { namespace events { /** Filters URLs for various 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. */ + /** Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ schemes?: string[]; /** * Optional. @@ -2039,39 +2121,39 @@ declare namespace chrome { * 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. */ urlMatches?: string; - /** Optional. Matches if the path segment of the URL contains a specified string. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. */ + /** 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. @@ -2085,14 +2167,14 @@ declare namespace chrome { interface Event { /** * Registers an event listener callback to an event. - * @param callback Called when an event occurs. The parameters of this function depend on the type of event. + * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * The callback parameter should be a function that looks like this: * function() {...}; */ addListener(callback: T): void; /** * Returns currently registered rules. - * @param callback Called with registered rules. + * @param callback Called with registered rules. * The callback parameter 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. @@ -2101,27 +2183,27 @@ declare namespace chrome { /** * Returns currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are returned. - * @param callback Called with registered rules. + * @param callback Called with registered rules. * The callback parameter 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. */ getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void; /** - * @param callback Listener whose registration status shall be tested. + * @param callback Listener whose registration status shall be tested. */ hasListener(callback: T): boolean; /** * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. - * @param callback Called when rules were unregistered. + * @param callback Called when rules were unregistered. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ removeRules(ruleIdentifiers?: string[], callback?: () => void): void; /** * Unregisters currently registered rules. - * @param callback Called when rules were unregistered. + * @param callback Called when rules were unregistered. * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ @@ -2129,7 +2211,7 @@ declare namespace chrome { /** * Registers rules to handle events. * @param rules Rules to be registered. These do not replace previously registered rules. - * @param callback Called with 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. @@ -2137,7 +2219,7 @@ declare namespace chrome { addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void; /** * Deregisters an event listener callback from an event. - * @param callback Listener that shall be unregistered. + * @param callback Listener that shall be unregistered. * The callback parameter should be a function that looks like this: * function() {...}; */ @@ -2147,11 +2229,11 @@ declare namespace chrome { /** Description of a declarative rule for handling events. */ interface Rule { - /** Optional. Optional priority of this rule. Defaults to 100. */ + /** 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. */ + /** Optional identifier that allows referencing this rule. */ id?: string; /** List of actions that are triggered if one of the condtions is fulfilled. */ actions: any[]; @@ -2176,19 +2258,19 @@ declare namespace chrome { /** * 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'. + * The format of the resulting image. Default is 'jpeg'. * @type {ImageFormat} * @memberof ImageDetails */ 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. + * 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 */ @@ -2197,13 +2279,13 @@ declare namespace chrome { /** * 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. + * 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 */ interface InjectDetails { @@ -2216,38 +2298,38 @@ declare namespace chrome { */ code?: string; /** - * @description JavaScript or CSS file to inject. + * 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. + * 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). + * 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. + * 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'. + * 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'. + * 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 @@ -2297,7 +2379,7 @@ declare namespace chrome { * - 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. */ + /** The suggested file name that will be presented to the user as the default name to read or write. This is */ 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[]; @@ -2326,33 +2408,33 @@ 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; + 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 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. * */ - 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. @@ -2362,15 +2444,15 @@ declare namespace chrome { * 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. */ - 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. */ - export function getVolumeList(callback: (volumes: Volume[]) => void): void; - export var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; + function getVolumeList(callback: (volumes: Volume[]) => void): void; + var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; } @@ -2398,7 +2480,7 @@ declare namespace chrome { 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. */ + /** Tag used by the last notification for the watcher. */ lastTag?: string; } @@ -2411,9 +2493,9 @@ declare namespace chrome { size: number; /** The last modified time of this entry. */ modificationTime: any; - /** Optional. Mime type for the entry. */ + /** 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; } @@ -2461,7 +2543,7 @@ declare namespace chrome { 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. */ + /** The title of the action. It may be ignored for common actions. */ title?: string; } @@ -2482,7 +2564,7 @@ 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. @@ -2519,9 +2601,9 @@ declare namespace chrome { 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) */ + /** 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; } @@ -2635,34 +2717,34 @@ declare namespace chrome { * 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. * 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. + * @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). * 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. + * @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. + * @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. + * @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. * To use, the file_system_provider.notify manifest option must be set to true. @@ -2670,60 +2752,60 @@ declare namespace chrome { * 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. + * @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 notify(options: NotificationOptions, callback: () => void): void; + function notify(options: NotificationOptions, callback: () => 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; + 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; + 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; + 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; + var onOpenFileRequested: OpenFileRequestedEvent; /** Raised when opening a file previously opened with openRequestId is requested to be closed. */ - export var onCloseFileRequested: OpenedFileRequestedEvent; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + var onTruncateRequested: FilePathLengthRequestedEvent; /** Raised when writing contents to a file opened previously with openRequestId is requested. */ - export var onWriteFileRequested: OpenedFileIoRequestedEvent; + 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; + var onAbortRequested: OperationRequestedEvent; /** * 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; + var onConfigureRequested: RequestedEvent; /** * 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; + var onMountRequested: OptionlessRequestedEvent; /** * 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. */ - export var onAddWatcherRequested: EntryPathRecursiveRequestedEvent; + var onAddWatcherRequested: EntryPathRecursiveRequestedEvent; /** * 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. */ - export var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; + var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; } //////////////////// @@ -2748,10 +2830,10 @@ declare namespace chrome { 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). */ + /** 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; /** - * @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; } @@ -2775,7 +2857,7 @@ 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; @@ -2788,40 +2870,40 @@ declare namespace chrome { 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; + 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. - * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty. + * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty. * The callback parameter should be a function that looks like this: * 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. + * @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. - * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems. + * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems. * The callback parameter should be a function that looks like this: * 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; + var onMessage: MessageReceptionEvent; /** 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; + var onMessagesDeleted: MessageDeletionEvent; /** Fired when it was not possible to send a message to the GCM server. */ - export var onSendError: GcmErrorEvent; + var onSendError: GcmErrorEvent; } //////////////////// @@ -2922,39 +3004,39 @@ declare namespace chrome { /** * Enumerate connected HID devices. * @param options The properties to search for on target devices. - * @param callback + * @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 + * 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. + * @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} - * @description Presents a device picker to the user and returns + * 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. + * @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. + * @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; @@ -2964,40 +3046,40 @@ declare namespace chrome { * @param connectionId The connectionId returned by connect. * @param [callback] */ - function disconnect(connectionId: number, callback?: () => void): void; + 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. (integer) + * @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: number, callback: (reportId: number, data: ArrayBuffer) => void): void; + 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. (integer) - * @param reportId The connectionId returned by connect. (integer) + * @param connectionId The connectionId returned by connect. + * @param reportId reportId - The report ID or 0 if none. * @param data The report data. - * @param callback + * @param callback */ - function send(connectionId: number, reportId: number, data: ArrayBuffer, callback: () => void): void; + 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. (integer) - * @param reportId The report ID, or 0 if none. (integer) - * @param callback Will provide `data` which contain the report data, including a report ID prefix if one is sent by 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: number, reportId: number, callback: (data: ArrayBuffer) => void): void; + 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. (integer) - * @param reportId The report ID to use, or 0 if none. (integer) + * @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 + * @param callback */ - function sendFeatureReport(connectionId: number, reportId: number, data: ArrayBuffer, callback: () => void): void; + 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 @@ -3014,7 +3096,7 @@ declare namespace chrome { * @since Chrome 41. * @see[See onDeviceAdded for which events are delivered]{@link https://developer.chrome.com/apps/hid#event-onDeviceAdded}. */ - var onDeviceRemoved: chrome.events.Event<(deviceId: number) => void>; + var onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; } //////////////////// @@ -3028,10 +3110,10 @@ declare namespace chrome { /** 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 */ + * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ language: string; /** The percentage of the detected language */ @@ -3049,28 +3131,28 @@ declare namespace chrome { /** * 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: + * @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 */ - export function getAcceptLanguages(callback: (languages: string[]) => void): void; + function getAcceptLanguages(callback: (languages: string[]) => 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. * @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?: any): string | undefined; /** * 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. * @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 The callback parameter should be a function that looks like this: function(object result) {...}; */ - export function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; + function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; } //////////////////// @@ -3141,55 +3223,55 @@ declare namespace chrome { * 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. * @param details Token options. - * @param callback Called with an OAuth2 access token as specified by the manifest, or undefined if there was an error. + * @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) {...}; */ - 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. * @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. * @param details Token information. - * @param callback Called when the token has been removed from the cache. + * @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. * @param details WebAuth flow options. - * @param callback Called with the URL redirected back to your application. + * @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; + var onSignInChanged: SignInChangeEvent; } //////////////////// @@ -3207,19 +3289,19 @@ declare namespace chrome { * 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. * Since Chrome 25. - * @param callback The callback parameter should be a function that looks like this: + * @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: number, callback: (newState: string) => 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. * @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: number): 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; + var onStateChanged: IdleStateChangedEvent; } //////////////////// @@ -3245,7 +3327,7 @@ declare namespace chrome { * 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. + * @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. */ @@ -3253,7 +3335,7 @@ declare namespace chrome { /** * 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. + * @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. @@ -3262,19 +3344,19 @@ declare namespace chrome { /** * 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. + * @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. + * @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. + * @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; @@ -3317,7 +3399,7 @@ declare namespace chrome { * 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. + * @param callback Callback invoked after ForceDiscovery() has started. */ function forceDiscovery(callback: () => void): void; /** @@ -3417,24 +3499,24 @@ declare namespace chrome { videoCount?: number; } - 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; + function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void; + function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void; + function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void; + function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void; + function startMediaScan(): void; + function cancelMediaScan(): void; + function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void; + function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata; + function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void; + function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void; + function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void; + function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void; + function removeGalleryWatch(galleryId: string): void; + function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void; + function removeAllGalleryWatch(): void; - export var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; - export var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; + var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; + var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } //////////////////////////////////// @@ -3446,57 +3528,57 @@ declare namespace chrome { * NOTE: Most dictionary properties and enum 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'; + 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'; interface ManagedBoolean { /** - * @description The active value currently used by the network configuration manager (e.g. Shill). + * 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. + * 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. + * The property value provided by the user policy. * @type {boolean} * @memberof ManagedBoolean */ UserPolicy?: boolean, /** - * @description The property value provided by the device policy. + * 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. + * 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. + * 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. + * 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. + * 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 */ @@ -3504,49 +3586,49 @@ declare namespace chrome { } interface ManagedLong { /** - * @description The active value currently used by the network configuration manager (e.g. Shill). + * The active value currently used by the network configuration manager (e.g. Shill). * @type {number} * @memberof ManagedLong */ Active?: number, /** - * @description The source from which the effective property value was determined. + * The source from which the effective property value was determined. * @type {string} * @memberof ManagedLong */ Effective?: string, /** - * @description The property value provided by the user policy. + * The property value provided by the user policy. * @type {number} * @memberof ManagedLong */ UserPolicy?: number, /** - * @description The property value provided by the device policy. + * 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. + * 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. + * 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. + * 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. + * 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 */ @@ -3577,7 +3659,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. @@ -3585,9 +3667,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. @@ -3595,13 +3677,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. @@ -3621,7 +3703,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. @@ -3642,79 +3724,79 @@ 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; + var onClosed: NotificationClosedEvent; /** The user clicked in a non-button area of the notification. */ - export var onClicked: NotificationClickedEvent; + var onClicked: NotificationClickedEvent; /** The user pressed a button in the notification. */ - export var onButtonClicked: NotificationButtonClickedEvent; + var onButtonClicked: NotificationButtonClickedEvent; /** * The user changes the permission level. * @since Chrome 32. */ - export var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; + var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; /** * The user clicked on a link for the app's notification settings. * @since Chrome 32. */ - export var onShowSettings: NotificationShowSettingsEvent; + var onShowSettings: NotificationShowSettingsEvent; /** * 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. * The notificationId parameter is required before Chrome 42. * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. + * @param callback Returns the notification id (either supplied or generated) that represents the created notification. * The callback is required before Chrome 42. * 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. * The notificationId parameter is required before Chrome 42. * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. + * @param callback Returns the notification id (either supplied or generated) that represents the created notification. * The callback is required before Chrome 42. * 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. * @param options Contents of the notification to update to. - * @param callback Called to indicate whether a matching notification existed. + * @param callback Called to indicate whether a matching notification existed. * The callback is required before Chrome 42. * 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. - * @param callback Called to indicate whether a matching notification existed. + * @param callback Called to indicate whether a matching notification existed. * The callback is required before Chrome 42. * 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. - * @param callback Returns the set of notification_ids currently in the system. + * @param callback Returns the set of notification_ids currently in the system. * 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. - * @param callback Returns the current permission level. + * @param callback Returns the current permission level. * 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; } //////////////////// @@ -3740,7 +3822,7 @@ declare namespace chrome { interface PermissionsRemovedEvent { /** - * @param callback The callback parameter should be a function that looks like this: + * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The permissions that have been removed. */ @@ -3749,7 +3831,7 @@ declare namespace chrome { interface PermissionsAddedEvent { /** - * @param callback The callback parameter should be a function that looks like this: + * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The newly acquired permissions. */ @@ -3758,37 +3840,37 @@ declare namespace chrome { /** * Checks if the extension has the specified permissions. - * @param callback The callback parameter should be a function that looks like this: + * @param callback The callback parameter should be a function that looks like this: * 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: + * @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; + var onRemoved: PermissionsRemovedEvent; /** Fired when the extension acquires new permissions. */ - export var onAdded: PermissionsAddedEvent; + var onAdded: PermissionsAddedEvent; } //////////////////// @@ -3801,9 +3883,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; } //////////////////// @@ -3820,7 +3902,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; } @@ -3851,17 +3933,17 @@ declare namespace chrome { 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; + var onGetPrintersRequested: PrinterRequestedEvent; /** * 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; + var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; /** Event fired when print manager requests printer capabilities. */ - export var onGetCapabilityRequested: CapabilityRequestedEvent; + var onGetCapabilityRequested: CapabilityRequestedEvent; /** Event fired when print manager requests printing. */ - export var onPrintRequested: PrintRequestedEvent; + var onPrintRequested: PrintRequestedEvent; } //////////////////// @@ -3873,12 +3955,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; + var lastError: LastError | undefined; /** The ID of the extension/app. */ - export var id: string; + var id: string; interface LastError { - /** Optional. Details about the error which occurred. */ + /** Details about the error which occurred. */ message?: string; } @@ -4197,75 +4279,75 @@ 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; + 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 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 + * @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. - * @param callback + * @param callback * 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. @@ -4273,7 +4355,7 @@ 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. @@ -4281,7 +4363,7 @@ 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. @@ -4290,69 +4372,69 @@ 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. * @param url Since Chrome 34. * 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. + * @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; /** * Fired when a connection is made from either an extension process or a content script. * @since Chrome 26. */ - export var onConnect: ExtensionConnectEvent; + var onConnect: ExtensionConnectEvent; /** * Fired when a connection is made from another extension. * @since Chrome 26. */ - export var onConnectExternal: ExtensionConnectEvent; + var 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; + var 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; + var 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; + var onInstalled: RuntimeInstalledEvent; /** Sent after onSuspend to indicate that the app won't be unloaded after all. */ - export var onSuspendCanceled: RuntimeEvent; + var onSuspendCanceled: RuntimeEvent; /** * Fired when a message is sent from either an extension process or a content script. * @since Chrome 26. */ - export var onMessage: ExtensionMessageEvent; + var 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; + var 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; + var onRestartRequired: RuntimeRestartRequiredEvent; /** * 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; + var onUpdateAvailable: RuntimeUpdateAvailableEvent; /** * @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; + var onBrowserUpdateAvailable: RuntimeEvent; } //////////////////// @@ -4410,21 +4492,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 { @@ -4466,28 +4548,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>; + var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } /** @@ -4566,18 +4648,18 @@ declare namespace chrome { * Creates a TCP server socket. * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create - * @param callback Called when the socket has been created. + * @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. * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create * @param properties The socket properties. - * @param callback Called when the socket has been created. + * @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. @@ -4585,9 +4667,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-update * @param socketId The socket identifier. * @param properties The properties to update. - * @param callback Called when the properties are updated. + * @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. @@ -4596,9 +4678,9 @@ declare namespace chrome { * requests. onAccept events are raised only when the socket is un-paused. * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused - * @param callback Callback from the setPaused method. + * @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 @@ -4613,9 +4695,9 @@ declare namespace chrome { * @param backlog Length of the socket's listen queue. The default value * depends on the Operating System (SOMAXCONN), which * ensures a reasonable queue length for most applications. - * @param callback Called when listen operation completes. + * @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 @@ -4627,9 +4709,9 @@ declare namespace chrome { * @param port The port of the local machine. When set to 0, a free port * is chosen dynamically. The dynamically allocated port can * be found by calling getInfo. - * @param callback Called when listen operation completes. + * @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 @@ -4639,9 +4721,9 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-disconnect * @param socketId The socket identifier. - * @param callback Called when the disconnect attempt is complete. + * @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 @@ -4651,33 +4733,33 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-close * @param socketId The socket identifier. - * @param callback Called when the close operation completes. + * @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. * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getInfo * @param socketId The socket identifier. - * @param callback Called when the socket state is available. + * @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. * * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getSockets - * @param callback Called when the list of sockets is available. + * @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>; + var onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4687,7 +4769,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError */ - export var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; + var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; } /** @@ -4789,7 +4871,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. @@ -4798,7 +4880,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. @@ -4806,9 +4888,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-update * @param socketId The socket ID. * @param properties The properties to update. - * @param callback Called when the properties are updated. + * @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 @@ -4817,10 +4899,10 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-setPaused * @param socketId The socket ID. * @param paused Flag to indicate whether to pause or unpause. - * @param callback Called when the socket has been successfully paused or + * @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 @@ -4837,9 +4919,9 @@ declare namespace chrome { * from all local available network interfaces. * @param port The port of the local machine. Use '0' to bind to a free * port. - * @param callback Called when the bind operation completes. + * @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 @@ -4850,9 +4932,9 @@ declare namespace chrome { * @param data The data to send. * @param address The address of the remote machine. * @param port The port of the remote machine. - * @param callback Called when the send operation completes. + * @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. @@ -4862,26 +4944,26 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#method-close * @param socketId The socket ID. - * @param callback Called when the close operation completes. + * @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. * * @see https://developer.chrome.com/apps/sockets_udp#method-getInfo * @param socketId The socket ID. - * @param callback Called when the socket state is available. + * @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. * * @see https://developer.chrome.com/apps/sockets_udp#method-getSockets - * @param callback Called when the list of sockets is available. + * @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. @@ -4890,9 +4972,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup * @param socketId The socket ID. * @param address The group address to join. Domain names are not supported. - * @param callback Called when the joinGroup operation completes. + * @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 @@ -4907,9 +4989,9 @@ declare namespace chrome { * @param socketId The socket ID. * @param address The group address to leave. Domain names are not * supported. - * @param callback Called when the leaveGroup operation completes. + * @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. @@ -4919,9 +5001,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastTimeToLive * @param socketId The socket ID. * @param ttl The time-to-live value. - * @param callback Called when the configuration operation completes. + * @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 @@ -4942,18 +5024,18 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastLoopbackMode * @param socketId The socket ID. * @param enabled Indicate whether to enable loopback mode. - * @param callback Called when the configuration operation completes. + * @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. * * @see https://developer.chrome.com/apps/sockets_udp#method-getJoinedGroups * @param socketId The socket ID. - * @param callback Called with an array of strings of the result. + * @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. @@ -4962,16 +5044,16 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-setBroadcast * @param socketId The socket ID. * @param enabled true to enable broadcast packets, false to disable them. - * @param callback Callback from the setBroadcast method. + * @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>; + var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4981,7 +5063,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError */ - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } //////////////////// @@ -4996,20 +5078,20 @@ declare namespace chrome { interface StorageArea { /** * Gets the amount of space (in bytes) being used by one or more items. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). + * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ getBytesInUse(callback: (bytesInUse: number) => void): void; /** * Gets the amount of space (in bytes) being used by one or more items. * @param keys A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). + * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: number) => void): void; /** * Removes all items from storage. - * @param callback Optional. + * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ clear(callback?: () => void): void; @@ -5017,20 +5099,20 @@ declare namespace chrome { * Sets multiple items. * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. * Primitive values such as numbers will serialize as expected. Values with a typeof 'object' and 'function' will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation). - * @param callback Optional. + * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ set(items: Object, callback?: () => void): void; /** * Removes one or more items from storage. * @param A single key or a list of keys for items to remove. - * @param callback Optional. + * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ remove(keys: string | string[], callback?: () => void): void; /** * Gets one or more items from storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). + * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ get(callback: (items: { [key: string]: any }) => void): void; @@ -5038,16 +5120,16 @@ declare namespace chrome { * Gets one or more items from storage. * @param keys A single key to get, list of keys to get, or a dictionary specifying default values. * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). + * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ get(keys: string | string[] | Object | null, callback: (items: { [key: string]: any }) => void): void; } 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; } @@ -5081,18 +5163,18 @@ 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; + var local: LocalStorageArea; /** Items in the sync storage area are synced using Chrome Sync. */ - export var sync: SyncStorageArea; + var 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; + var managed: StorageArea; /** Fired when one or more items change. */ - export var onChanged: StorageChangedEvent; + var onChanged: StorageChangedEvent; } //////////////////// @@ -5201,7 +5283,7 @@ declare namespace 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. + * @param callback A callback type for requestFileSystem. */ function requestFileSystem(callback: (fileSystem: FileSystem) => void): void; /** @@ -5219,7 +5301,7 @@ declare namespace chrome { /** * Returns the current usage and quota in bytes for the 'syncable' file storage for the app. * @param fileSystem - * @param callback + * @param callback */ function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: number, quotaBytes: number }) => void): void; /** @@ -5233,7 +5315,7 @@ declare namespace chrome { /** * Returns the current sync backend status. * @since Chrome 31. - * @param callback + * @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). */ @@ -5285,7 +5367,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; } //////////////////// @@ -5383,7 +5465,7 @@ declare namespace chrome { } /** - * @description The pairs of point used to calibrate the display. + * The pairs of point used to calibrate the display. * @export * @interface TouchCalibrationPairs */ @@ -5399,13 +5481,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; @@ -5432,20 +5514,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 */ @@ -5497,7 +5579,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>} @@ -5505,123 +5587,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; + var onDisplayChanged: DisplayChangedEvent; } //////////////////// @@ -5641,7 +5723,7 @@ declare namespace chrome { } /** Get physical memory information. */ - export function getInfo(callback: (info: MemoryInfo) => void): void; + function getInfo(callback: (info: MemoryInfo) => void): void; } //////////////////// @@ -5654,7 +5736,7 @@ declare namespace chrome { prefixLength: number; } - export function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; + function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } //////////////////// @@ -5694,23 +5776,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 + * @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; + var onAttached: SystemStorageAttachedEvent; /** Fired when a removable storage is detached from the system. */ - export var onDetached: SystemStorageDetachedEvent; + var onDetached: SystemStorageDetachedEvent; } //////////////////// @@ -5724,9 +5806,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. @@ -5737,14 +5819,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; @@ -5758,7 +5840,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. @@ -5771,7 +5853,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; @@ -5780,52 +5862,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; } //////////////////// @@ -5866,14 +5948,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 { /** @@ -5901,7 +5983,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; /** @@ -5912,7 +5994,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. */ @@ -6009,27 +6091,27 @@ declare namespace chrome { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> { } - export var onDeviceAdded: DeviceEvent; - export var onDeviceRemoved: DeviceEvent; + var onDeviceAdded: DeviceEvent; + var 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; } @@ -6046,9 +6128,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. @@ -6058,7 +6140,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[]; @@ -6077,138 +6159,128 @@ declare namespace chrome { /** * Creates a new VPN configuration that persists across multiple login sessions of the user. * @param name The name of the VPN configuration. - * @param callback Called when the configuration is created or if there is an error. + * @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. + * @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; + var onPlatformMessage: VpnPlatformMessageEvent; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - export var onPacketReceived: VpnPacketReceptionEvent; + var onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ - export var onConfigRemoved: VpnConfigRemovalEvent; + var onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ - export var onConfigCreated: VpnConfigCreationEvent; + var 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; + var 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 { + enum 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; } + enum 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. */ @@ -6217,41 +6289,39 @@ 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 HTMLElement { /** @@ -6266,11 +6336,20 @@ declare namespace chrome { */ 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; @@ -6297,7 +6376,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: @@ -6312,33 +6391,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. @@ -6357,7 +6436,7 @@ declare namespace chrome { * 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. @@ -6369,40 +6448,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; @@ -6457,1059 +6536,962 @@ 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. - * @param callback + * 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. - * @param callback + * 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. - * @param callback + * 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). - * @param callback + * 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. - * @param callback + * Gets the current zoom factor. + * @param callback */ getZoom(callback: (zoomFactor: number) => void): void; /** - * @description Gets the current zoom mode. - * @param callback + * 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. - * @param callback + * 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. - * @param callback + * 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.

- * @param callback + * 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!';
-              }
-            });
- * @param callback + * 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. - * @param callback + * 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; + findupdate: 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'.

- * @param callback + * 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; + loadabort: 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. - * @param callback + * 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 */ - loadcommit: chrome.events.Event; + loadcommit: chrome.events.Event; /** - * @description Fired when a top-level load request has redirected to a different URL. - * @param callback + * Fired when a top-level load request has redirected to a different URL. + * @param callback */ - loadredirect: chrome.events.Event; + loadredirect: chrome.events.Event; /** - * @description Fired when a load has begun. - * @param callback + * Fired when a load has begun. + * @param callback */ - loadstart: chrome.events.Event; + 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.

+ * 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. */ - 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) { + * var 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. + **/ + enum 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. - * @param callback + * 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; /** - * @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; /** - * @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:
+         * 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 var 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 {
+        *   > Disables all zooming in the webview.
+        *     The content will revert to the default zoom level,
+        *     and all attempted zoom changes will be ignored.
+        **/
+        enum ZoomMode {
+            'per-origin',
+            'per-view',
+            'disabled'
+        }
+        enum ConsoleMessageLevel {
             LOG_VERBOSE = -1,
             LOG_INFO = 0,
             LOG_WARNING = 1,
             LOG_ERROR = 2
         }
-        interface IConsoleMessage {
-
+        enum 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 {
-
-            /**
-            * @description The type of modal dialog requested by the guest.
-             */
-            messageType: 'alert' | 'confirm' | 'prompt'
-
-            /**
-            * @description The text the guest attempted to display in the modal dialog.
-             */
-            messageText: string
-
-            /**
-            * @description An interface that can be used to respond to the guest's modal request.
-             */
-            dialog: DialogController
+        enum DialogMessageType {
+            'alert',
+            'confirm',
+            'prompt'
         }
-        interface IExit {
-
+        interface Dialog {
             /**
-            * @description Chrome's internal ID of the process that exited.
+             * The type of modal dialog requested by the guest.
              */
-            processID: number
-
+            messageType: DialogMessageType;
             /**
-            * @description String indicating the reason for the exit.
+             * The text the guest attempted to display in the modal dialog.
              */
-            reason: 'normal' | 'abnormal' | 'crash' | 'kill'
+            messageText: string;
+            /**
+             * An interface that can be used to respond to the guest's modal request.
+             */
+            dialog: DialogController;
         }
-        interface IFindupdate {
-
-            /**
-            * @description The string that is being searched for in the page.
-             */
-            searchText: string
-
-            /**
-            * @description The number of matches found for searchText on the page so far.
-             */
-            numberOfMatches: number
-
-            /**
-            * @description The ordinal number of the current active match, if it has been found. This will be 0 until then.
-             */
-            activeMatchOrdinal: number
-
-            /**
-            * @description Describes a rectangle around the active match, if it has been found, in screen coordinates.
-             */
-            selectionRect: SelectionRect
-
-            /**
-            * @description Indicates whether the find request was canceled.
-             */
-            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.
-             */
-            finalUpdate: string
+        enum ExitReason {
+            'normal',
+            'abnormal',
+            'crash',
+            'kill'
         }
-        interface ILoadabort {
-
-            /**
-            * @description Requested URL.
-             */
-            url: string
-
-            /**
-            * @description Whether the load was top-level or in a subframe.
-             */
-            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'
+        interface Exit {
+            /** Chrome's internal ID of the process that exited. */
+            processID: number;
+            /** String indicating the reason for the exit. */
+            reason: ExitReason;
         }
-        interface ILoadcommit {
-
+        interface FindUpdate {
             /**
-            * @description The URL that committed.
+             * The string that is being searched for in the page.
              */
-            url: string
-
+            searchText: string;
             /**
-            * @description Whether the load is top-level or in a subframe.
+             * The number of matches found for searchText on the page so far.
              */
-            isTopLevel: boolean
+            numberOfMatches: number;
+            /**
+             * The ordinal number of the current active match,
+             * if it has been found. This will be 0 until then.
+             */
+            activeMatchOrdinal: number;
+            /**
+             * Describes a rectangle around the active match,
+             * if it has been found, in screen coordinates.
+             */
+            selectionRect: SelectionRect;
+            /**
+             * Indicates whether the find request was canceled.
+             */
+            canceled: boolean;
+            /**
+             * Indicates that all find requests have completed
+             * and that no more findupdate events will be fired
+             * until more find requests are made.
+             */
+            finalUpdate: string;
         }
-        /**ILoadredirect (Auto generated interface) */
-        interface ILoadredirect {
-
+        interface LoadAbort {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load was top-level or in a subframe. */
+            isTopLevel: boolean;
             /**
-            * @description The requested URL before the redirect.
+             * 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.
              */
-            oldUrl: string
-
+            code: integer;
             /**
-            * @description The new URL after the redirect.
+             * 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.
              */
-            newUrl: string
-
-            /**
-            * @description Whether or not the redirect happened at top-level or in a subframe.
-             */
-            isTopLevel: boolean
+            reason: LoadAbortReason;
         }
-        /**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 LoadCommit {
+            /** The URL that committed. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**INewwindow (Auto generated interface) */
-        interface INewwindow {
-
-            /**
-            * @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
-
-            /**
-            * @description The target URL requested for the new window.
-             */
-            targetUrl: string
-
-            /**
-            * @description The initial width requested for the new window.
-             */
-            initialWidth: number
-
-            /**
-            * @description The initial height requested for the new window.
-             */
-            initialHeight: number
-
-            /**
-            * @description 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'
+        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;
         }
-        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;
+        interface LoadStart {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-
-        /**IResponsive (Auto generated interface) */
-        interface IResponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that became responsive.
-             */
-            processID: number
+        enum WindowOpenDisposition {
+            'ignore',
+            'save_to_disk',
+            'current_tab',
+            'new_background_tab',
+            'new_foreground_tab',
+            'new_window',
+            'new_popup'
         }
-        /**ISizechanged (Auto generated interface) */
-        interface ISizechanged {
-
+        interface NewWindow {
             /**
-            * @description Old width of embedded web content.
-             */
-            oldWidth: number
+             * 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 Old height of embedded web content.
-             */
-            oldHeight: number
+            /** The target URL requested for the new window. */
+            targetUrl: string;
 
-            /**
-            * @description New width of embedded web content.
-             */
-            newWidth: number
+            /** The initial width requested for the new window. */
+            initialWidth: number;
 
-            /**
-            * @description New height of embedded web content.
-             */
-            newHeight: number
+            /** The initial height requested for the new window. */
+            initialHeight: number;
+
+            /** The requested name of the new window. */
+            name: string;
+
+            /** The requested disposition of the new window. */
+            windowOpenDisposition: WindowOpenDisposition;
         }
-        /**IUnresponsive (Auto generated interface) */
-        interface IUnresponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that has become unresponsive.
-             */
-            processID: number
+        enum RequestedPermission {
+            'media',
+            'geolocation',
+            'pointerLock',
+            'download',
+            'loadplugin',
+            'filesystem',
+            'fullscreen'
         }
-        /**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 PermissionRequest {
+            /** The type of permission being requested. */
+            permission: RequestedPermission;
+            /** An object which holds details of the requested permission.*/
+            request: PermissionRequestHandler;
+        }
+        interface ProcessResponsive {
+            /** Chrome's internal ID of the process that became responsive. */
+            processID: 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;
+        }
+        interface ProcessUnresponsive {
+            /** Chrome's internal ID of the process that has become unresponsive. */
+            processID: number;
+        }
+        interface ZoomChange {
+            /** The page's previous zoom factor. */
+            oldZoomFactor: number;
+            /** The new zoom factor that the page was zoomed to. */
+            newZoomFactor: number;
         }
-
     }
-
 }
 
 /////////////////////
diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts
index f3db9d5cc1..d970c58c55 100644
--- a/types/chrome-apps/test/index.ts
+++ b/types/chrome-apps/test/index.ts
@@ -431,6 +431,6 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => {
         });
     }
 })
-
+chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT;
 
 

From 5ff309eca1aea5f308b4e9ab13d6fb049728efd8 Mon Sep 17 00:00:00 2001
From: Nikolai Ommundsen 
Date: Tue, 31 Jul 2018 14:19:09 +0200
Subject: [PATCH 014/289] More cleanup, comment shortening, bugfixing, updates

---
 types/chrome-apps/index.d.ts    | 972 +++++++++++++++++++++-----------
 types/chrome-apps/test/index.ts |   2 -
 2 files changed, 658 insertions(+), 316 deletions(-)

diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts
index 8a601d2b38..85cfb27666 100644
--- a/types/chrome-apps/index.d.ts
+++ b/types/chrome-apps/index.d.ts
@@ -26,12 +26,10 @@ declare namespace chrome {
 
     /**
      * Integer
-     * Whole number
      */
     type integer = number;
     /**
      * Double
-     * Decimal number
      */
     type double = number;
 
@@ -1866,77 +1864,103 @@ declare namespace chrome {
             'separator'
         }
 
+        enum MediaType {
+            'image',
+            'video',
+            'audio'
+        }
+
         interface OnClickData {
             /**
              * The ID of the menu item that was clicked.
              * @since Since Chrome 35.
              */
             menuItemId: integer | string;
+
             /**
              * The parent ID, if any, for the item clicked.
              * @since Since Chrome 35.
              */
             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;
+
+            /**
+             * If the element is a link, the URL it points to.
+             * @since Since Chrome 35.
+             */
+            linkUrl?: string;
+
+            /**
+             * 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 the state of a checkbox or radio item after it is clicked.
-             * @since Since Chrome 35.
-             */
-            checked?: boolean;
-            /**
-             * 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;
+
             /**
              * A flag indicating whether the element is editable (text input, textarea, etc.).
              * @since Since Chrome 35.
              */
             editable: boolean;
+
             /**
-             * Optional.
-             * @since Since Chrome 35.
              * 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.
-             * 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.
-             */
-            linkUrl?: string;
-            /**
-             * Optional.
-             * @since Since Chrome 35.
-             * Will be present for elements with a 'src' URL.
-             */
-            srcUrl?: string;
+            checked?: boolean;
         }
 
         interface CreateProperties {
             /** The type of menu item. Defaults to 'normal' if not specified.  */
             type?: ItemType;
+
             /**
              * The unique ID to assign to this item.
              * Mandatory for event pages.
              * Cannot be the same as another ID for this extension.
              */
             id?: string;
+
             /**
              * The text to be displayed in the item;
              * this is required unless type is 'separator'.
@@ -1949,6 +1973,7 @@ declare namespace chrome {
              * to Pig Latin'.
              **/
             title?: string;
+
             /**
              * The initial state of a checkbox or radio item:
              * true for selected and false for unselected.
@@ -1956,115 +1981,101 @@ declare namespace chrome {
              * 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;
+
             /**
              * 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;
+
+            /** The ID of a parent menu item; this makes the item a child of a previously added item.  */
+            parentId?: integer | 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[];
+
             /**
-             * Optional.
-             * Whether this context menu item is enabled or disabled. Defaults to true.
-             * @since Since Chrome 20.
+             * 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
              */
             enabled?: boolean;
-            /** 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[];
-            /** The ID of a parent menu item; this makes the item a child of a previously added item.  */
-            parentId?: any;
         }
 
         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;
-            /** Note: You cannot change an item to be a child of one of its own descendants.  */
-            parentId?: any;
-            type?: string;
-            /**
-              * 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> { }
 
-        /**
-         * 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() {...};
-         */
-        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() {...};
+         * @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.
          */
         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() {...};
-         */
-        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() {...};
-         */
-        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() {...};
-         */
-        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() {...};
-         */
-        function remove(menuItemId: number, callback?: () => void): void;
 
         /**
-         * Since Chrome 21.
-         * Fired when a context menu item is clicked.
+         * 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.
+         */
+        function removeAll(callback?: () => void): void;
+
+        /** Fired when a context menu item is clicked. */
         var onClicked: MenuClickedEvent;
 
     }
@@ -2073,10 +2084,19 @@ declare namespace chrome {
     // Document Scan
     ////////////////////
     /**
-     * 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.
+     * 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 {
@@ -2103,66 +2123,97 @@ declare namespace chrome {
         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. */
         interface UrlFilter {
-            /** 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.
-             */
-            urlMatches?: string;
-            /** Matches if the path segment of the URL contains a specified string.  */
-            pathContains?: string;
-            /** Matches if the host name of the URL ends with a specified string.  */
-            hostSuffix?: string;
-            /** Matches if the host name of the URL starts with a specified string.  */
-            hostPrefix?: string;
-            /** 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.  */
+             * 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 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 query segment of the URL ends with a specified string.  */
-            querySuffix?: 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 host name of the URL is equal to a specified string.  */
             hostEquals?: 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 query segment of the URL contains a specified string.  */
-            queryContains?: 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.  */
-            pathPrefix?: string;
-            /** Matches if the path segment of the URL is equal to 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 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 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[];
+            /** 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.
-              * 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 {
             /**
@@ -2229,126 +2280,166 @@ declare namespace chrome {
 
         /** Description of a declarative rule for handling events. */
         interface Rule {
-            /** Optional priority of this rule. Defaults to 100.  */
-            priority?: number;
-            /** List of conditions that can trigger the actions. */
-            conditions: any[];
-            /** 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.
          **/
-        type ImageFormat = 'jpeg' | 'png';
+        enum ImageFormat {
+            'jpeg',
+            'png'
+        }
         /**
          * Details about the format and quality of an image.
          */
         interface ImageDetails {
-            /**
-              * The format of the resulting image. Default is 'jpeg'.
-             * @type {ImageFormat}
-             * @memberof ImageDetails
-             */
+            /** The format of the resulting image. Default is 'jpeg'. */
             format?: ImageFormat;
+
             /**
-              * 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.
          **/
-        type RunAt = 'document_start' | 'document_end' | 'document_idle';
+        enum RunAt {
+            'document_start',
+            'document_end',
+            'document_idle'
+        }
         /**
          * The origin of injected CSS.
          **/
-        type CSSOrigin = 'author' | 'user';
+        enum CSSOrigin {
+            'author',
+            'user'
+        }
         /**
-          * 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;
-            /**
-              * JavaScript or CSS file to inject.
-             * @type {string}
-             * @memberof InjectDetails
-             */
-            file?: string;
-            /**
-              * 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;
-            /**
-              * 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;
-            /**
-              * 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;
-            /**
-              * The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'.
-             * @type {RunAt}
-             * @memberof InjectDetails
-             */
-            runAt: RunAt;
-            /**
-              * 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 {
-
+        enum ChildChangeType {
+            'created',
+            'removed',
+            'changed'
+        }
+        enum ChooseEntryOptionsTypes {
+            'openFile',
+            'openWritableFile',
+            'saveFile',
+            'openDirectory'
+        }
         interface AcceptOptions {
             /**
              * This is the optional text description for this option.
@@ -2370,16 +2461,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 */
+            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[];
@@ -2390,17 +2491,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;
         }
 
@@ -2426,13 +2533,17 @@ declare namespace chrome {
         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. */
         function restoreEntry(id: string, callback: (entry: Entry) => void): void;
-        /** Returns whether the app has permission to restore the entry with the given id. */
+        /**
+         * 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.
          * */
         function retainEntry(entry: Entry): string;
         /**
@@ -2443,6 +2554,7 @@ 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.
          */
         function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void;
         /**
@@ -2450,8 +2562,13 @@ declare namespace chrome {
          * 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.
          */
         function getVolumeList(callback: (volumes: Volume[]) => void): void;
+        /**
+         * Called when a list of available volumes is changed.
+         * @since Chrome 44.
+         */
         var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>;
     }
 
@@ -2460,76 +2577,165 @@ 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 (enum 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;
+        /**
+         * 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.
+         * */
+        enum 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"
         }
-
-        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;
+        /** Mode of opening a file. Used by onOpenFileRequested. */
+        enum OpenFileMode {
+            "READ",
+            "WRITE"
+        }
+        /** Type of a change detected on the observed directory. */
+        enum 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.
+         */
+        enum 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;
+            modificationTime?: Date;
             /** Mime type for the entry.  */
             mimeType?: string;
-            /** 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;
@@ -2539,15 +2745,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;
+            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;
@@ -2564,20 +2769,27 @@ declare namespace chrome {
             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;
             /**
-             * 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;
             /**
-             * 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 {
@@ -2589,7 +2801,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 {
@@ -2599,11 +2811,20 @@ 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;
+            /**
+             * 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[];
-            /** 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;
         }
 
@@ -2611,7 +2832,7 @@ declare namespace chrome {
             /** The identifier of the file system related to this operation. */
             fileSystemId: string;
             /** The unique identifier of this request. */
-            requestId: number;
+            requestId: integer;
         }
 
         interface EntryPathRequestedEventOptions extends RequestedEventOptions {
@@ -2619,7 +2840,37 @@ declare namespace chrome {
             entryPath: string;
         }
 
+        interface GetActionsRequestedEventOptions extends RequestedEventOptions {
+            /** The path of the entry to which this operation is related to. */
+            entryPaths: string[];
+        }
+
         interface MetadataRequestedEventOptions extends 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;
         }
@@ -2636,19 +2887,19 @@ declare namespace chrome {
 
         interface OpenFileRequestedEventOptions extends FilePathRequestedEventOptions {
             /** Whether the file will be used for reading or writing. */
-            mode: string;
+            mode: OpenFileMode;
         }
 
         interface OpenedFileRequestedEventOptions extends RequestedEventOptions {
             /** A request ID used to open the file. */
-            openRequestId: number;
+            openRequestId: integer;
         }
 
-        interface OpenedFileOffsetRequestedEventOptions extends OpenedFileRequestedEventOptions {
+        interface ReadFileRequestedEventOptions extends OpenedFileRequestedEventOptions {
             /** 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 {
@@ -2685,33 +2936,35 @@ declare namespace chrome {
             operationRequestId: number;
         }
 
-        interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> { }
+        interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { }
+        interface ActionsRequestedEvent extends chrome.events.Event<(options: GetActionsRequestedEventOptions, successCallback: (actions: Action[]) => void, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { }
+        interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface ReadFileRequestedEvent extends chrome.events.Event<(options: ReadFileRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
-        interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> { }
+        interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
+
+        interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
 
         /**
          * 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.
@@ -2722,6 +2975,7 @@ declare namespace chrome {
          * function() {...};
          */
         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).
          * In case of an error, runtime.lastError will be set with a corresponding error code.
@@ -2730,6 +2984,7 @@ declare namespace chrome {
          * function() {...};
          */
         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.
@@ -2737,6 +2992,7 @@ declare namespace chrome {
          * function(array of FileSystemInfo fileSystems) {...};
          */
         function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void;
+
         /**
          * Returns information about a file system with the passed fileSystemId.
          * @since Since Chrome 42.
@@ -2745,6 +3001,7 @@ declare namespace chrome {
          * function(FileSystemInfo fileSystem) {...};
          */
         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.
          * To use, the file_system_provider.notify manifest option must be set to true.
@@ -2758,34 +3015,108 @@ declare namespace chrome {
          */
         function notify(options: NotificationOptions, callback: () => 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.  */
+        /**
+         * 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.
+         */
         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. */
+
+        /**
+         * 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.
+         */
         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. */
+
+        /**
+         * 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.
+         **/
+        var onGetActionsRequested: ActionsRequestedEvent;
+
+        /**
+         * 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.
+         */
         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. */
+
+        /**
+         * 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.
+         */
         var onOpenFileRequested: OpenFileRequestedEvent;
-        /** Raised when opening a file previously opened with openRequestId is requested to be closed. */
+
+        /**
+         * Raised when opening a file previously opened
+         * with openRequestId is requested to be closed.
+         */
         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. */
-        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. */
+
+        /**
+         * 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.
+         */
+        var onReadFileRequested: ReadFileRequestedEvent;
+
+        /**
+         * 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.
+         */
         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. */
+
+        /**
+         * 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.
+         */
         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. */
+
+        /**
+         * Raised when creating a file is requested.
+         * If the file already exists, then errorCallback must be called with the 'EXISTS' error code.
+         */
         var onCreateFileRequested: FilePathRequestedEvent;
-        /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */
+
+        /**
+         * Raised when copying an entry (recursively if a directory) is requested.
+         * If an error occurs, then errorCallback must be called.
+         */
         var onCopyEntryRequested: SourceTargetPathRequestedEvent;
-        /** Raised when moving an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */
+
+        /**
+         * Raised when moving an entry (recursively if a directory) is requested.
+         * If an error occurs, then errorCallback must be called.
+         */
         var onMoveEntryRequested: SourceTargetPathRequestedEvent;
-        /** Raised when truncating a file to a desired length is requested. If an error occurs, then errorCallback must be called. */
+
+        /**
+         * Raised when truncating a file to a desired length is requested.
+         * If an error occurs, then errorCallback must be called.
+         */
         var onTruncateRequested: FilePathLengthRequestedEvent;
+
         /** Raised when writing contents to a file opened previously with openRequestId is requested. */
         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. */
+
+        /**
+         * 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.
+         */
         var onAbortRequested: OperationRequestedEvent;
+
         /**
          * 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.
@@ -2798,14 +3129,20 @@ declare namespace chrome {
         var onMountRequested: OptionlessRequestedEvent;
         /**
          * 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.
+         * @since Since Chrome 45.
          */
         var onAddWatcherRequested: EntryPathRecursiveRequestedEvent;
         /**
          * 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.
+         * @since Since Chrome 45.
          */
         var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent;
+        /**
+         * 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.
+         */
+        var onExecuteActionRequested: EntryPathRecursiveRequestedEvent;
     }
 
     ////////////////////
@@ -6324,10 +6661,9 @@ declare namespace chrome {
           * WebView element from html
          */
         interface HTMLWebViewElement extends HTMLElement {
-            /**
-             * This sets the guest content's window.name object.
-             */
+            /** 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.
@@ -6335,6 +6671,7 @@ 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'),
@@ -6345,6 +6682,7 @@ declare namespace chrome {
              * 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,
@@ -6353,19 +6691,25 @@ declare namespace chrome {
              * 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.
@@ -7126,14 +7470,14 @@ declare namespace chrome {
              * @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;
 
             /**
              * 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;
 
             /**
              * Removes all context menu items added to this webview.
diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts
index d970c58c55..dc8e09d5d8 100644
--- a/types/chrome-apps/test/index.ts
+++ b/types/chrome-apps/test/index.ts
@@ -432,5 +432,3 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => {
     }
 })
 chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT;
-
-

From 7a81f6537fc71dda88cd7431a65bd90f966892bd Mon Sep 17 00:00:00 2001
From: Nikolai Ommundsen 
Date: Tue, 31 Jul 2018 16:06:38 +0200
Subject: [PATCH 015/289] Cleanup and fixes: Continued (WIP)

---
 types/chrome-apps/index.d.ts    | 1315 ++++++++++++++++++++-----------
 types/chrome-apps/test/index.ts |    2 +
 2 files changed, 877 insertions(+), 440 deletions(-)

diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts
index 85cfb27666..5a5a6645f5 100644
--- a/types/chrome-apps/index.d.ts
+++ b/types/chrome-apps/index.d.ts
@@ -105,14 +105,14 @@ declare namespace chrome {
             /**
              * Gets the value of a setting.
              * @param details Which setting to consider.
-              * @param callback The callback parameter should be a function that looks like this:
+             * @param callback The callback parameter should be a function that looks like this:
              * function(object details) {...};
              */
             get(details: AccessibilityFeaturesGetArg, callback: (details: AccessibilityFeaturesCallbackArg) => void): void;
             /**
              * Sets the value of a setting.
              * @param details Which setting to change.
-              * @param callback Called at the completion of the set operation.
+             * @param callback Called at the completion of the set operation.
              * If you specify the callback parameter, it should be a function that looks like this:
              * function() {...};
              */
@@ -120,7 +120,7 @@ declare namespace chrome {
             /**
              * Clears the setting, restoring any default value.
              * @param details Which setting to clear.
-              * @param callback Called at the completion of the clear operation.
+             * @param callback Called at the completion of the clear operation.
              * If you specify the callback parameter, it should be a function that looks like this:
              * function() {...};
              */
@@ -240,39 +240,39 @@ declare namespace chrome {
         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:
+         * @param callback The callback parameter should be a function that looks like this:
          * @example function(array of Alarm alarms) {...};
          */
         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) {...};
          */
         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) {...};
          */
         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) {...};
          */
         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:
+         * @param callback The callback parameter should be a function that looks like this:
          * @example function( Alarm alarm) {...};
          */
         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:
+         * @param callback The callback parameter should be a function that looks like this:
          * @example function( Alarm alarm) {...};
          */
         function get(name: string, callback: (alarm: Alarm) => void): void;
@@ -740,7 +740,7 @@ declare namespace chrome {
     ////////////////////
     /**
      * @since Since Chrome 59.
-     * @requires Permissions: "audio"
+     * @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.
@@ -954,13 +954,13 @@ declare namespace chrome {
         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.
+         * @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.
+         * @param callback Called when the search is completed.
          */
         function getDevices(filter: DeviceFilter, callback: (devices: Device[]) => void): void;
         /**
@@ -1117,14 +1117,14 @@ declare namespace chrome {
         /**
          * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect.
          * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened.
-          * @param callback Called when the connect request has completed.
+         * @param callback Called when the connect request has completed.
          */
         function connect(deviceAddress: string, callback: () => void): void;
         /**
          * Establishes a connection between the application and the device with the given address. A device may be already connected and its GATT services available without calling connect, however, an app that wants to access GATT services of a device should call this function to make sure that a connection to the device is maintained. If the device is not connected, all GATT services of the device will be discovered after a successful call to connect.
          * @param deviceAddress The Bluetooth address of the remote device to which a GATT connection should be opened.
          * @param properties Connection properties (optional).
-          * @param callback Called when the connect request has completed.
+         * @param callback Called when the connect request has completed.
          */
         function connect(deviceAddress: string, properties: IProperties, callback: () => void): void;
         /**
@@ -1136,27 +1136,27 @@ declare namespace chrome {
         /**
          * Get the GATT service with the given instance ID.
          * @param serviceId The instance ID of the requested GATT service.
-          * @param callback Called with the requested Service object.
+         * @param callback Called with the requested Service object.
          */
         function getService(serviceId: string, callback: (result: Service) => void): void;
         /**
           * 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.
+         * @param callback Called with the created services's unique ID.
          */
         function createService(service: Service, callback: () => void): void;
         /**
          * Get all the GATT services that were discovered on the remote device with the given device address.
          * Note: If service discovery is not yet complete on the device, this API will return a subset (possibly empty) of services. A work around is to add a time based delay and/or call repeatedly until the expected number of services is returned.
          * @param deviceAddress The Bluetooth address of the remote device whose GATT services should be returned.
-          * @param callback Called with the list of requested Service objects.
+         * @param callback Called with the list of requested Service objects.
          */
         function getServices(deviceAddress: string, callback: (result: Service[]) => void): void;
         /**
          * Get the GATT characteristic with the given instance ID that belongs to the given GATT service, if the characteristic exists.
          * @param characteristicId The instance ID of the requested GATT characteristic.
-          * @param callback Called with the requested Characteristic object.
+         * @param callback Called with the requested Characteristic object.
          */
         function getCharacteristic(characteristicId: string, callback: (result: Characteristic) => void): void;
         /**
@@ -1164,25 +1164,25 @@ declare namespace chrome {
          * @since Since Chrome 52.
          * @param characteristic The characteristic to create.
          * @param serviceId ID of the service to create this characteristic for.
-          * @param callback Called with the created characteristic's unique ID.
+         * @param callback Called with the created characteristic's unique ID.
          */
         function createCharacteristic(characteristic: Characteristic, serviceId: string, callback: (characteristicId: string) => void): void;
         /**
          * Get a list of all discovered GATT characteristics that belong to the given service.
          * @param serviceId The instance ID of the GATT service whose characteristics should be returned.
-          * @param callback Called with the list of characteristics that belong to the given service.
+         * @param callback Called with the list of characteristics that belong to the given service.
          */
         function getCharacteristics(serviceId: string, callback: (result: Characteristic[]) => void): void;
         /**
          * Get a list of GATT services that are included by the given service.
          * @param serviceId The instance ID of the GATT service whose included services should be returned.
-          * @param callback Called with the list of GATT services included from the given service.
+         * @param callback Called with the list of GATT services included from the given service.
          */
         function getIncludedServices(serviceId: string, callback: (result: Service[]) => void): void;
         /**
          * Get the GATT characteristic descriptor with the given instance ID.
          * @param descriptorId The instance ID of the requested GATT characteristic descriptor.
-          * @param callback Called with the requested Descriptor object.
+         * @param callback Called with the requested Descriptor object.
          */
         function getDescriptor(descriptorId: string, callback: (result: Descriptor) => void): void;
         /**
@@ -1190,33 +1190,33 @@ declare namespace chrome {
          * @since Since Chrome 52.
          * @param descriptor The descriptor to create.
          * @param characteristicId ID of the characteristic to create this descriptor for.
-          * @param callback Called with the created desciptor's unique ID.
+         * @param callback Called with the created desciptor's unique ID.
          */
         function createDescriptor(descriptor: Descriptor, characteristicId: string, callback: (descriptorId: string) => void): void;
         /**
          * Get a list of GATT characteristic descriptors that belong to the given characteristic.
          * @param characteristicId The instance ID of the GATT characteristic whose descriptors should be returned.
-          * @param callback Called with the list of descriptors that belong to the given characteristic.
+         * @param callback Called with the list of descriptors that belong to the given characteristic.
          */
         function getDescriptors(characteristicId: string, callback: (result: Descriptor[]) => void): void;
         /**
          * Retrieve the value of a specified characteristic from a remote peripheral.
          * @param characteristicId The instance ID of the GATT characteristic whose value should be read from the remote device.
-          * @param callback Called with the Characteristic object whose value was requested. The value field of the returned Characteristic object contains the result of the read request.
+         * @param callback Called with the Characteristic object whose value was requested. The value field of the returned Characteristic object contains the result of the read request.
          */
         function readCharacteristicValue(characteristicId: string, callback: (result: Characteristic) => void): void;
         /**
          * Write the value of a specified characteristic from a remote peripheral.
          * @param characteristicId The instance ID of the GATT characteristic whose value should be written to.
          * @param value The value that should be sent to the remote characteristic as part of the write request.
-          * @param callback Called when the write request has completed.
+         * @param callback Called when the write request has completed.
          */
         function writeCharacteristicValue(characteristicId: string, value: ArrayBuffer, callback: () => void): void;
         /**
          * Enable value notifications/indications from the specified characteristic. Once enabled, an application can listen to notifications using the onCharacteristicValueChanged event.
          * @see onCharacteristicValueChanged
          * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on.
-          * @param callback Called when the request has completed.
+         * @param callback Called when the request has completed.
          */
         function startCharacteristicNotifications(characteristicId: string, callback: () => void): void;
         /**
@@ -1224,7 +1224,7 @@ declare namespace chrome {
          * @see onCharacteristicValueChanged
          * @param characteristicId The instance ID of the GATT characteristic that notifications should be enabled on.
          * @param properties Notification session properties (optional).
-          * @param callback Called when the request has completed.
+         * @param callback Called when the request has completed.
          */
         function startCharacteristicNotifications(characteristicId: string, properties: IProperties, callback: () => void): void;
         /**
@@ -1242,20 +1242,20 @@ declare namespace chrome {
          * @since Since Chrome 52.
          * @param characteristicId The characteristic to send the notication for.
          * @param notification Notification object
-          * @param callback Callback called once the notification or indication has been sent successfully.
+         * @param callback Callback called once the notification or indication has been sent successfully.
          */
         function notifyCharacteristicValueChanged(characteristicId: string, notification: INotification, callback: () => void): void;
         /**
          * Retrieve the value of a specified characteristic descriptor from a remote peripheral.
          * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be read from the remote device.
-          * @param callback Called with the Descriptor object whose value was requested. The value field of the returned Descriptor object contains the result of the read request.
+         * @param callback Called with the Descriptor object whose value was requested. The value field of the returned Descriptor object contains the result of the read request.
          */
         function readDescriptorValue(descriptorId: string, callback: (result: Descriptor) => void): void;
         /**
          * Write the value of a specified characteristic descriptor from a remote peripheral.
          * @param descriptorId The instance ID of the GATT characteristic descriptor whose value should be written to.
          * @param value The value that should be sent to the remote descriptor as part of the write request.
-          * @param callback Called when the write request has completed.
+         * @param callback Called when the write request has completed.
          */
         function writeDescriptorValue(descriptorId: string, value: ArrayBuffer, callback: () => void): void;
         /**
@@ -1266,7 +1266,7 @@ declare namespace chrome {
          * The peripheral permission may not be available to all apps.
          * @since Since Chrome 52.
          * @param serviceId Unique ID of a created service.
-          * @param callback Callback with the result of the register operation.
+         * @param callback Callback with the result of the register operation.
          */
         function registerService(serviceId: string, callback: () => void): void;
         /**
@@ -1277,7 +1277,7 @@ declare namespace chrome {
          * The peripheral permission may not be available to all apps.
          * @since Since Chrome 52.
          * @param serviceId Unique ID of a current registered service.
-          * @param callback Callback with the result of the register operation.
+         * @param callback Callback with the result of the register operation.
          */
         function unregisterService(serviceId: string, callback: () => void): void;
         /**
@@ -1307,7 +1307,7 @@ declare namespace chrome {
          *  (including the discovery of Bluetooth Low Energy devices).
          * @since Since Chrome 47.
          * @param advertisement The advertisement to advertise.
-          * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement.
+         * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement.
          */
         function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: number) => void): void;
         /**
@@ -1316,13 +1316,13 @@ declare namespace chrome {
          *  to stop advertising might be to restart the device.
          * @since Since Chrome 47.
          * @param advertisementId Id of the advertisement to unregister.
-          * @param callback Called once the advertisement is unregistered and is no longer being advertised.
+         * @param callback Called once the advertisement is unregistered and is no longer being advertised.
          */
         function unregisterAdvertisement(advertisementId: number, callback: () => void): void;
         /**
          * Resets advertising on the current device. It will unregister and stop all existing advertisements.
          * @since Since Chrome 61.
-          * @param callback Called once the advertisements are reset.
+         * @param callback Called once the advertisements are reset.
          */
         function resetAdvertising(callback: () => void): void;
         /**
@@ -1334,7 +1334,7 @@ declare namespace chrome {
          * @since Since Chrome 55.
          * @param minInterval Minimum interval between advertisments (in milliseconds). This cannot be lower than 20ms (as per the spec).
          * @param maxInterval Maximum interval between advertisments (in milliseconds). This cannot be more than 10240ms (as per the spec).
-          * @param callback Called once the interval has been set.
+         * @param callback Called once the interval has been set.
          */
         function setAdvertisingInterval(minInterval: number, maxInterval: number, callback: () => void): void;
         /**
@@ -1349,7 +1349,7 @@ declare namespace chrome {
          * 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>;
         /** Fired when a GATT service that was previously discovered on a remote device has been removed. */
@@ -1465,7 +1465,7 @@ declare namespace chrome {
              * Flag indicating if the socket remains
              * open when the event page of the application
              * is unloaded (see SocketProperties.persistent).
-             * The default value is "false".
+             * The default value is 'false'.
              */
             persistent: boolean;
             /**
@@ -1484,7 +1484,7 @@ declare namespace chrome {
              * 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".
+             * See setPaused. The default value is 'false'.
              */
             paused: boolean;
             /**
@@ -1532,8 +1532,8 @@ declare namespace chrome {
             clientSocketId: integer;
         }
         enum OnAcceptErrorCode {
-            "system_error",
-            "not_listening"
+            'system_error',
+            'not_listening'
         }
         interface OnAcceptErrorEventData {
             /** The server socket identifier. */
@@ -1557,9 +1557,9 @@ declare namespace chrome {
             data: ArrayBuffer;
         }
         enum OnReceiveErrorCode {
-            "disconnected",
-            "system_error",
-            "not_connected"
+            'disconnected',
+            'system_error',
+            'not_connected'
         }
         interface OnReceiveErrorEventData {
             /** The server socket identifier. */
@@ -1584,13 +1584,13 @@ declare namespace chrome {
         interface OnReceiveErrorEvent extends chrome.events.Event<(info: OnReceiveErrorEventData) => void> { }
         /**
          * Creates a Bluetooth socket.
-          * @param callback Called when the socket has been created
+         * @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
+         * @param callback Called when the socket has been created
          */
         function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
         /**
@@ -1604,7 +1604,7 @@ declare namespace chrome {
          * 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
+         * 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
@@ -1620,7 +1620,7 @@ declare namespace chrome {
              * 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".
+             * See setPaused. The default value is 'false'.
          * @param [callback] Callback from the setPaused method.
          */
         function setPaused(socketId: integer, paused: boolean, callback?: () => void): void;
@@ -1629,7 +1629,7 @@ declare namespace chrome {
          *
          * @param socketId The socket identifier.
          * @param uuid Service UUID to listen on.
-          * @param callback Called when listen operation completes.
+         * @param callback Called when listen operation completes.
          */
         function listenUsingRfcomm(socketId: integer, uuid: string, callback: () => void): void;
         /**
@@ -1638,7 +1638,7 @@ declare namespace chrome {
          * @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.
+         * @param callback Called when listen operation completes.
          */
         function listenUsingRfcomm(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void;
         /**
@@ -1646,7 +1646,7 @@ declare namespace chrome {
          *
          * @param socketId The socket identifier.
          * @param uuid Service UUID to listen on.
-          * @param callback Called when listen operation completes.
+         * @param callback Called when listen operation completes.
          */
         function listenUsingL2cap(socketId: integer, uuid: string, callback: () => void): void;
         /**
@@ -1655,7 +1655,7 @@ declare namespace chrome {
          * @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.
+         * @param callback Called when listen operation completes.
          */
         function listenUsingL2cap(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void;
         /**
@@ -1671,7 +1671,7 @@ declare namespace chrome {
          * @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.
+         * @param callback Called when the connect attempt is complete.
          */
         function connect(socketId: integer, address: string, uuid: string, callback: () => void): void;
         /**
@@ -1688,7 +1688,7 @@ declare namespace chrome {
          * to be closed only when the callback is invoked.
          *
          * @param socketId The socket identifier.
-          * @param callback Called when the `close` operation completes
+         * @param callback Called when the `close` operation completes
          */
         function close(socketId: integer, callback: () => void): void;
         /**
@@ -1701,13 +1701,13 @@ declare namespace chrome {
         /**
          * Retrieves the state of the given socket.
          * @param socketId The socket identifier.
-          * @param callback Called when the socket state is available.
+         * @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.
+         * @param callback Called when the list of sockets is available.
          *                 Returns an array of socket info.
          */
         function getSockets(callback: (sockets: SocketInfo[]) => void): void;
@@ -1758,7 +1758,7 @@ declare namespace chrome {
          * and Chrome profile. If no browser window for the Chrome profile is opened,
          * a new one is opened prior to creating the new tab.
          * @param options Configures how the tab should be opened.
-          * @param callback Called when the tab was successfully
+         * @param callback Called when the tab was successfully
          * created, or failed to be created. If failed, runtime.lastError will be set.
          */
         function openTab(options: Options, callback: () => void): void;
@@ -1799,7 +1799,7 @@ 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.
+         * @param callback Called to return the registered commands.
          */
         function getAll(callback: (commands: Command[]) => void): void;
 
@@ -2116,7 +2116,7 @@ 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.
+         * @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) {...};
          */
@@ -2218,14 +2218,14 @@ declare namespace chrome {
         interface Event {
             /**
              * Registers an event listener callback to an event.
-              * @param callback Called when an event occurs. The parameters of this function depend on the type of event.
+             * @param callback Called when an event occurs. The parameters of this function depend on the type of event.
              * The callback parameter should be a function that looks like this:
              * function() {...};
              */
             addListener(callback: T): void;
             /**
              * Returns currently registered rules.
-              * @param callback Called with registered rules.
+             * @param callback Called with registered rules.
              * The callback parameter 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.
@@ -2234,27 +2234,27 @@ declare namespace chrome {
             /**
              * Returns currently registered rules.
              * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are returned.
-              * @param callback Called with registered rules.
+             * @param callback Called with registered rules.
              * The callback parameter 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.
              */
             getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void;
             /**
-              * @param callback Listener whose registration status shall be tested.
+             * @param callback Listener whose registration status shall be tested.
              */
             hasListener(callback: T): boolean;
             /**
              * Unregisters currently registered rules.
              * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered.
-              * @param callback Called when rules were unregistered.
+             * @param callback Called when rules were unregistered.
              * If you specify the callback parameter, it should be a function that looks like this:
              * function() {...};
              */
             removeRules(ruleIdentifiers?: string[], callback?: () => void): void;
             /**
              * Unregisters currently registered rules.
-              * @param callback Called when rules were unregistered.
+             * @param callback Called when rules were unregistered.
              * If you specify the callback parameter, it should be a function that looks like this:
              * function() {...};
              */
@@ -2262,7 +2262,7 @@ declare namespace chrome {
             /**
              * Registers rules to handle events.
              * @param rules Rules to be registered. These do not replace previously registered rules.
-              * @param callback Called with 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.
@@ -2270,7 +2270,7 @@ declare namespace chrome {
             addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void;
             /**
              * Deregisters an event listener callback from an event.
-              * @param callback Listener that shall be unregistered.
+             * @param callback Listener that shall be unregistered.
              * The callback parameter should be a function that looks like this:
              * function() {...};
              */
@@ -2424,9 +2424,9 @@ declare namespace chrome {
      * All failures are notified via chrome.runtime.lastError.
      * @since Availability: Since Chrome 24.
      * @requires Permissions:
-     *   "fileSystem"
-     *   {"fileSystem": ["write"]}
-     *   {"fileSystem": ["write", "retainEntries", "directory"]}
+     *   'fileSystem'
+     *   {'fileSystem': ['write']}
+     *   {'fileSystem': ['write', 'retainEntries', 'directory']}
      */
     namespace fileSystem {
         enum ChildChangeType {
@@ -2591,7 +2591,7 @@ declare namespace chrome {
      * 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 (enum of "file", "device", or "network") - required**
+     * **source (enum 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.
@@ -2606,48 +2606,48 @@ declare namespace chrome {
         /**
          * 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.
+         * For success, 'OK' must be used.
          * */
         enum 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"
+            '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. */
         enum OpenFileMode {
-            "READ",
-            "WRITE"
+            'READ',
+            'WRITE'
         }
         /** Type of a change detected on the observed directory. */
         enum ChangeType {
-            "CHANGED",
-            "DELETED"
+            '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
+         * 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.
          */
         enum CommonActionId {
-            "SAVE_FOR_OFFLINE",
-            "OFFLINE_NOT_NECESSARY",
-            "SHARE"
+            'SAVE_FOR_OFFLINE',
+            'OFFLINE_NOT_NECESSARY',
+            'SHARE'
         }
 
         interface EntryMetadata {
@@ -2778,7 +2778,7 @@ declare namespace chrome {
              * 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;
             /**
              * Whether the file system supports the tag field for observed directories.
              * @since Since Chrome 45.
@@ -2827,25 +2827,44 @@ declare namespace chrome {
              */
             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: integer;
+            /**
+             * @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 GetActionsRequestedEventOptions extends RequestedEventOptions {
-            /** The path of the entry to which this operation is related to. */
-            entryPaths: string[];
-        }
-
-        interface MetadataRequestedEventOptions extends EntryPathRequestedEventOptions {
+        interface MetadataRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions {
             /**
              * Set to true if is_directory value is requested
              * @since Chrome 49.
@@ -2871,163 +2890,215 @@ declare namespace chrome {
              * @since Chrome 49.
              */
             mimeType: boolean;
-            /** Set to true if the thumbnail is requested. */
+            /**
+             * 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: OpenFileMode;
         }
-
-        interface OpenedFileRequestedEventOptions extends RequestedEventOptions {
+        interface CloseFileRequestedEventOptions extends _internal_.RequestedEventOptions {
             /** A request ID used to open the file. */
             openRequestId: integer;
         }
-
-        interface ReadFileRequestedEventOptions 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: double;
             /** Number of bytes to be returned. */
             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: ProviderError) => void) => void> { }
 
-        interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface ActionsRequestedEvent extends chrome.events.Event<(options: GetActionsRequestedEventOptions, successCallback: (actions: Action[]) => void, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface ReadFileRequestedEvent extends chrome.events.Event<(options: ReadFileRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: ProviderError) => void) => void> { }
-
-        interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: ProviderError) => 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() {...};
+         *
+         * @param callback A generic result callback to indicate success or failure.
          */
         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() {...};
+         *
+         * @param callback A generic result callback to indicate success or failure.
          */
         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) {...};
+         * @param callback Callback to receive the result of getAll function.
          */
         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) {...};
+         * @param callback Callback to receive the result of get function.
          */
         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() {...};
+         *
+         * @param callback A generic result callback to indicate success or failure.
+         * @since Since Chrome 45.
          */
         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.
          */
-        var onUnmountRequested: RequestedEvent;
+        var 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.
          */
-        var onGetMetadataRequested: MetadataRequestedEvent;
+        var 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.
@@ -3037,75 +3108,123 @@ declare namespace chrome {
          * In case of an error, errorCallback must be called.
          * @since Since Chrome 48.
          **/
-        var onGetActionsRequested: ActionsRequestedEvent;
+        var 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.
          */
-        var onReadDirectoryRequested: DirectoryPathRequestedEvent;
+        var 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.
          */
-        var onOpenFileRequested: OpenFileRequestedEvent;
+        var 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.
          */
-        var onCloseFileRequested: OpenedFileRequestedEvent;
+        var 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.
          */
-        var onReadFileRequested: ReadFileRequestedEvent;
+        var 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.
          */
-        var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent;
+        var 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.
          */
-        var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent;
+        var 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.
          */
-        var onCreateFileRequested: FilePathRequestedEvent;
+        var 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.
          */
-        var onCopyEntryRequested: SourceTargetPathRequestedEvent;
+        var 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.
          */
-        var onMoveEntryRequested: SourceTargetPathRequestedEvent;
+        var 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.
          */
-        var onTruncateRequested: FilePathLengthRequestedEvent;
+        var onTruncateRequested: chrome.events.Event<(
+            options: TruncateRequestedEventOptions,
+            successCallback: () => void,
+            errorCallback: (error: ProviderError) => void
+        ) => void>;
 
         /** Raised when writing contents to a file opened previously with openRequestId is requested. */
-        var onWriteFileRequested: OpenedFileIoRequestedEvent;
+        var onWriteFileRequested: chrome.events.Event<(
+            options: WriteFileRequestedEventOptions,
+            successCallback: () => void,
+            errorCallback: (error: ProviderError) => void
+        ) => void>;
 
         /**
          * Raised when aborting an operation with operationRequestId is requested.
@@ -3115,62 +3234,120 @@ declare namespace chrome {
          * operation must not be called, as they will be ignored. Despite calling
          * errorCallback, the request may be forcibly aborted.
          */
-        var onAbortRequested: OperationRequestedEvent;
+        var 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.
+         * 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.
          */
-        var onConfigureRequested: RequestedEvent;
+        var 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.
          */
-        var onMountRequested: OptionlessRequestedEvent;
+        var 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.
+         * Raised when setting a new directory watcher is requested.
+         * If an error occurs, then errorCallback must be called.
          * @since Since Chrome 45.
          */
-        var onAddWatcherRequested: EntryPathRecursiveRequestedEvent;
+        var 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.
+         * Raised when the watcher should be removed.
+         * If an error occurs, then errorCallback must be called.
          * @since Since Chrome 45.
          */
-        var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent;
+        var 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.
+         * 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.
          */
-        var onExecuteActionRequested: EntryPathRecursiveRequestedEvent;
+        var 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;
             /** 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;
+            timeToLive?: integer;
             /**
-              * 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;
         }
@@ -3200,19 +3377,10 @@ declare namespace chrome {
             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 */
-        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.
-          * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty.
+         * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty.
          * The callback parameter should be a function that looks like this:
          * function(string registrationId) {...};
          * Parameter registrationId: A registration ID assigned to the application by the GCM.
@@ -3220,7 +3388,7 @@ declare namespace chrome {
         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.
+         * @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() {...};
          */
@@ -3228,7 +3396,7 @@ declare namespace chrome {
         /**
          * Sends a message according to its contents.
          * @param message A message to send to the other party via GCM.
-          * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems.
+         * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems.
          * The callback parameter should be a function that looks like this:
          * function(string messageId) {...};
          * Parameter messageId: The ID of the message that the callback was issued for.
@@ -3236,16 +3404,16 @@ declare namespace chrome {
         function send(message: OutgoingMessage, callback: (messageId: string) => void): void;
 
         /** Fired when a message is received through GCM. */
-        var onMessage: MessageReceptionEvent;
+        var 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. */
-        var onMessagesDeleted: MessageDeletionEvent;
+        var onMessagesDeleted: chrome.events.Event<() => void>;
         /** Fired when it was not possible to send a message to the GCM server. */
-        var onSendError: GcmErrorEvent;
+        var 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.
@@ -3254,25 +3422,25 @@ declare namespace chrome {
      * and executing the function's regular callback. The callback's regular
      * parameters will be undefined in this case.
      *
-     * Permissions: "hid"
-     * @since Available since Chrome 38
+     * @requires Permissions: 'hid'
+     * @since Available since Chrome 38.
      */
     namespace hid {
         interface Collection {
             /** HID usage page identifier. */
-            usagePage: number;
+            usagePage: integer;
             /** Page-defined usage identifier. */
-            usage: number;
+            usage: integer;
             /** Report IDs which belong to the collection and to its children. */
-            reportIds: number[];
+            reportIds: integer[];
         }
         interface HidDeviceInfo {
             /** Opaque device ID. */
-            deviceId: number;
+            deviceId: integer;
             /** Vendor ID. */
-            vendorId: number;
+            vendorId: integer;
             /** Product ID. */
-            productId: number;
+            productId: integer;
             /**
              * The product name read from the device, if available.
              * @since Chrome 46
@@ -3288,26 +3456,27 @@ declare namespace chrome {
              */
             collections: Collection[];
             /** Top-level collection's maximum input report size. */
-            maxInputReportSize: number;
+            maxInputReportSize: integer;
             /** Top-level collection's maximum output report size. */
-            maxOutputReportSize: number;
+            maxOutputReportSize: integer;
             /** Top-level collection's maximum feature report size. */
-            maxFeatureReportSize: number;
+            maxFeatureReportSize: integer;
             /**
              * Raw device report descriptor (not available on Windows).
              * @since Chrome 42
              * */
             reportDescriptor: ArrayBuffer;
         }
+        /** @since Chrome 39. */
         interface DeviceFilter {
             /** Device vendor ID. */
-            vendorId?: number;
+            vendorId?: integer;
             /** Device product ID, only checked only if the vendor ID matches. */
-            productId?: number;
+            productId?: integer;
             /** HID usage page identifier. */
-            usagePage?: number;
+            usagePage?: integer;
             /** HID usage identifier, checked only if the HID usage page matches. */
-            usage?: number;
+            usage?: integer;
         }
         interface DeviceOptions {
             /**
@@ -3338,45 +3507,51 @@ declare namespace chrome {
              */
             filters?: DeviceFilter[];
         }
+
         /**
          * Enumerate connected HID devices.
          * @param options The properties to search for on target devices.
-          * @param callback
+         * @param callback
          */
         function getDevices(options: DeviceOptions, callback: (devices: HidDeviceInfo[]) => void): void;
+
         /**
-         * @requires(dev) Dev channel only!
+         * @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
+         * @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.
+         * @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!
+         * @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
+         * 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.
+         * @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.
+         * @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.
@@ -3384,39 +3559,44 @@ declare namespace chrome {
          * @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:
+         * @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
+         * @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.
+         * @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
+         * @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
@@ -3427,6 +3607,7 @@ declare namespace chrome {
          * @see[permissions.request]{@link https://developer.chrome.com/apps/permissions#method-request}
          */
         var 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.
@@ -3436,14 +3617,214 @@ declare namespace chrome {
         var 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}
+         */
+        enum 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 {
             /**
@@ -3451,10 +3832,10 @@ declare namespace chrome {
               * 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}.
               * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */
-            language: string;
+            language: kLanguageInfoTable;
 
             /** The percentage of the detected language */
-            percentage: number;
+            percentage: integer;
         }
 
         /** Holds detected language reliability and array of DetectedLanguage */
@@ -3462,60 +3843,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.
          */
-        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 Up to 9 substitution strings, if the message requires any.
          */
-        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.
          */
         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.
          */
         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.
              */
@@ -3530,9 +3926,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;
         }
 
@@ -3542,7 +3946,9 @@ declare namespace chrome {
         }
 
         interface WebAuthFlowOptions {
-            /** The URL that initiates the auth flow. */
+            /**
+             * The URL that initiates the auth flow.
+             */
             url: string;
             /**
              * Optional.
@@ -3553,49 +3959,69 @@ 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.
          */
         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.
          */
         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.
          */
         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() {...};
+         * @param callback Called when the token has been removed from the cache.
          */
         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.
+         * @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) {...};
          */
         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/*.
@@ -3608,37 +4034,46 @@ declare namespace chrome {
          * Fired when signin state changes for an account on the user's profile.
          * @since Chrome 33.
          */
-        var onSignInChanged: SignInChangeEvent;
+        var 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> { }
-
+        enum 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.
          * Since Chrome 25.
-          * @param callback The callback parameter should be a function that looks like this:
+         * @param callback The callback parameter should be a function that looks like this:
          * function( IdleState newState) {...};
          */
-        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.
          */
-        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. */
-        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.
+         */
+        var onStateChanged: chrome.events.Event<(newState: IdleState) => void>;
     }
 
     ////////////////////
@@ -3646,7 +4081,7 @@ declare namespace chrome {
     ////////////////////
     /**
      * Use chrome.instanceID to access the Instance ID service.
-     * Permissions: "gcm"
+     * Permissions: 'gcm'
      * @since Chrome 46
      */
     namespace instanceID {
@@ -3664,7 +4099,7 @@ declare namespace chrome {
          * 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.
+         * @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.
          */
@@ -3672,7 +4107,7 @@ declare namespace chrome {
         /**
          * 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.
+         * @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.
@@ -3681,19 +4116,19 @@ declare namespace chrome {
         /**
          * 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.
+         * @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.
+         * @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.
+         * @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;
@@ -3707,7 +4142,7 @@ declare namespace chrome {
     /**
      * Use the chrome.mdns API to discover services over mDNS.
      * This comprises a subset of the features of the NSD spec: @see[Spec link]{@link http://www.w3.org/TR/discovery-api/}
-     * Permissions: "mdns"
+     * Permissions: 'mdns'
      * @since Chrome 31
      */
     namespace mdns {
@@ -3736,7 +4171,7 @@ declare namespace chrome {
          * 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.
+         * @param callback Callback invoked after ForceDiscovery() has started.
          */
         function forceDiscovery(callback: () => void): void;
         /**
@@ -4082,7 +4517,7 @@ declare namespace chrome {
          * @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.
          * The notificationId parameter is required before Chrome 42.
          * @param options Contents of the notification.
-          * @param callback Returns the notification id (either supplied or generated) that represents the created notification.
+         * @param callback Returns the notification id (either supplied or generated) that represents the created notification.
          * The callback is required before Chrome 42.
          * If you specify the callback parameter, it should be a function that looks like this:
          * function(string notificationId) {...};
@@ -4093,7 +4528,7 @@ declare namespace chrome {
          * @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.
          * The notificationId parameter is required before Chrome 42.
          * @param options Contents of the notification.
-          * @param callback Returns the notification id (either supplied or generated) that represents the created notification.
+         * @param callback Returns the notification id (either supplied or generated) that represents the created notification.
          * The callback is required before Chrome 42.
          * If you specify the callback parameter, it should be a function that looks like this:
          * function(string notificationId) {...};
@@ -4103,7 +4538,7 @@ declare namespace chrome {
          * Updates an existing notification.
          * @param notificationId The id of the notification to be updated. This is returned by notifications.create method.
          * @param options Contents of the notification to update to.
-          * @param callback Called to indicate whether a matching notification existed.
+         * @param callback Called to indicate whether a matching notification existed.
          * The callback is required before Chrome 42.
          * If you specify the callback parameter, it should be a function that looks like this:
          * function(boolean wasUpdated) {...};
@@ -4112,7 +4547,7 @@ declare namespace chrome {
         /**
          * Clears the specified notification.
          * @param notificationId The id of the notification to be cleared. This is returned by notifications.create method.
-          * @param callback Called to indicate whether a matching notification existed.
+         * @param callback Called to indicate whether a matching notification existed.
          * The callback is required before Chrome 42.
          * If you specify the callback parameter, it should be a function that looks like this:
          * function(boolean wasCleared) {...};
@@ -4121,7 +4556,7 @@ declare namespace chrome {
         /**
          * Retrieves all the notifications.
          * @since Chrome 29.
-          * @param callback Returns the set of notification_ids currently in the system.
+         * @param callback Returns the set of notification_ids currently in the system.
          * The callback parameter should be a function that looks like this:
          * function(object notifications) {...};
          */
@@ -4129,7 +4564,7 @@ declare namespace chrome {
         /**
          * Retrieves whether the user has enabled notifications from this app or extension.
          * @since Chrome 32.
-          * @param callback Returns the current permission level.
+         * @param callback Returns the current permission level.
          * The callback parameter should be a function that looks like this:
          * function( PermissionLevel level) {...};
          */
@@ -4159,7 +4594,7 @@ declare namespace chrome {
 
         interface PermissionsRemovedEvent {
             /**
-              * @param callback The callback parameter should be a function that looks like this:
+             * @param callback The callback parameter should be a function that looks like this:
              * function( Permissions permissions) {...};
              * Parameter permissions: The permissions that have been removed.
              */
@@ -4168,7 +4603,7 @@ declare namespace chrome {
 
         interface PermissionsAddedEvent {
             /**
-              * @param callback The callback parameter should be a function that looks like this:
+             * @param callback The callback parameter should be a function that looks like this:
              * function( Permissions permissions) {...};
              * Parameter permissions: The newly acquired permissions.
              */
@@ -4177,28 +4612,28 @@ declare namespace chrome {
 
         /**
          * Checks if the extension has the specified permissions.
-          * @param callback The callback parameter should be a function that looks like this:
+         * @param callback The callback parameter should be a function that looks like this:
          * function(boolean result) {...};
          * Parameter result: True if the extension has the specified permissions.
          */
         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:
+         * @param callback The callback parameter should be a function that looks like this:
          * function( Permissions permissions) {...};
          * Parameter permissions: The extension's active permissions.
          */
         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.
          */
         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.
          */
@@ -4645,7 +5080,7 @@ declare namespace chrome {
         /**
          * Returns information about the current platform.
          * @since Chrome 29.
-          * @param callback Called with results
+         * @param callback Called with results
          */
         function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void;
         /**
@@ -4661,7 +5096,7 @@ declare namespace chrome {
         /**
          * Requests an update check for this app/extension.
          * @since Chrome 25.
-          * @param callback
+         * @param callback
          * 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.
          */
@@ -4715,7 +5150,7 @@ declare namespace chrome {
          * @since Chrome 41.
          * @param url Since Chrome 34.
          * 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.
+         * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set.
          */
         function setUninstallURL(url: string, callback?: () => void): void;
         /**
@@ -4985,7 +5420,7 @@ declare namespace chrome {
          * Creates a TCP server socket.
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create
-          * @param callback Called when the socket has been created.
+         * @param callback Called when the socket has been created.
          */
         function create(callback: (createInfo: CreateInfo) => void): void;
 
@@ -4994,7 +5429,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create
          * @param properties The socket properties.
-          * @param callback   Called when the socket has been created.
+         * @param callback   Called when the socket has been created.
          */
         function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
 
@@ -5004,7 +5439,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-update
          * @param socketId   The socket identifier.
          * @param properties The properties to update.
-          * @param callback   Called when the properties are updated.
+         * @param callback   Called when the properties are updated.
          */
         function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
 
@@ -5015,7 +5450,7 @@ declare namespace chrome {
          * requests. onAccept events are raised only when the socket is un-paused.
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused
-          * @param callback Callback from the setPaused method.
+         * @param callback Callback from the setPaused method.
          */
         function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
 
@@ -5032,7 +5467,7 @@ declare namespace chrome {
          * @param backlog  Length of the socket's listen queue. The default value
          *                 depends on the Operating System (SOMAXCONN), which
          *                 ensures a reasonable queue length for most applications.
-          * @param callback Called when listen operation completes.
+         * @param callback Called when listen operation completes.
          */
         function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void;
 
@@ -5046,7 +5481,7 @@ declare namespace chrome {
          * @param port     The port of the local machine. When set to 0, a free port
          *                 is chosen dynamically. The dynamically allocated port can
          *                 be found by calling getInfo.
-          * @param callback Called when listen operation completes.
+         * @param callback Called when listen operation completes.
          */
         function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void;
 
@@ -5058,7 +5493,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-disconnect
          * @param socketId The socket identifier.
-          * @param callback Called when the disconnect attempt is complete.
+         * @param callback Called when the disconnect attempt is complete.
          */
         function disconnect(socketId: number, callback?: () => void): void;
 
@@ -5070,7 +5505,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-close
          * @param socketId The socket identifier.
-          * @param callback Called when the close operation completes.
+         * @param callback Called when the close operation completes.
          */
         function close(socketId: number, callback?: () => void): void;
 
@@ -5079,7 +5514,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getInfo
          * @param socketId The socket identifier.
-          * @param callback Called when the socket state is available.
+         * @param callback Called when the socket state is available.
          */
         function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
 
@@ -5087,7 +5522,7 @@ declare namespace chrome {
          * Retrieves the list of currently opened sockets owned by the application.
          *
          * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getSockets
-          * @param callback Called when the list of sockets is available.
+         * @param callback Called when the list of sockets is available.
          */
         function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
 
@@ -5225,7 +5660,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-update
          * @param socketId   The socket ID.
          * @param properties The properties to update.
-          * @param callback   Called when the properties are updated.
+         * @param callback   Called when the properties are updated.
          */
         function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
 
@@ -5236,7 +5671,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-setPaused
          * @param socketId The socket ID.
          * @param paused   Flag to indicate whether to pause or unpause.
-          * @param callback Called when the socket has been successfully paused or
+         * @param callback Called when the socket has been successfully paused or
          *                 unpaused.
          */
         function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
@@ -5256,7 +5691,7 @@ declare namespace chrome {
          *                 from all local available network interfaces.
          * @param port     The port of the local machine. Use '0' to bind to a free
          *                 port.
-          * @param callback Called when the bind operation completes.
+         * @param callback Called when the bind operation completes.
          */
         function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void;
 
@@ -5269,7 +5704,7 @@ declare namespace chrome {
          * @param data     The data to send.
          * @param address  The address of the remote machine.
          * @param port     The port of the remote machine.
-          * @param callback Called when the send operation completes.
+         * @param callback Called when the send operation completes.
          */
         function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void;
 
@@ -5281,7 +5716,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_udp#method-close
          * @param socketId The socket ID.
-          * @param callback Called when the close operation completes.
+         * @param callback Called when the close operation completes.
          */
         function close(socketId: number, callback?: () => void): void;
 
@@ -5290,7 +5725,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_udp#method-getInfo
          * @param socketId The socket ID.
-          * @param callback Called when the socket state is available.
+         * @param callback Called when the socket state is available.
          */
         function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
 
@@ -5298,7 +5733,7 @@ declare namespace chrome {
          * Retrieves the list of currently opened sockets owned by the application.
          *
          * @see https://developer.chrome.com/apps/sockets_udp#method-getSockets
-          * @param callback Called when the list of sockets is available.
+         * @param callback Called when the list of sockets is available.
          */
         function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
 
@@ -5309,7 +5744,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup
          * @param socketId The socket ID.
          * @param address  The group address to join. Domain names are not supported.
-          * @param callback Called when the joinGroup operation completes.
+         * @param callback Called when the joinGroup operation completes.
          */
         function joinGroup(socketId: number, address: string, callback: (result: number) => void): void;
 
@@ -5326,7 +5761,7 @@ declare namespace chrome {
          * @param socketId The socket ID.
          * @param address  The group address to leave. Domain names are not
          *                 supported.
-          * @param callback Called when the leaveGroup operation completes.
+         * @param callback Called when the leaveGroup operation completes.
          */
         function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void;
 
@@ -5338,7 +5773,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastTimeToLive
          * @param socketId The socket ID.
          * @param ttl      The time-to-live value.
-          * @param callback Called when the configuration operation completes.
+         * @param callback Called when the configuration operation completes.
          */
         function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void;
 
@@ -5361,7 +5796,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastLoopbackMode
          * @param socketId The socket ID.
          * @param enabled  Indicate whether to enable loopback mode.
-          * @param callback Called when the configuration operation completes.
+         * @param callback Called when the configuration operation completes.
          */
         function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void;
 
@@ -5370,7 +5805,7 @@ declare namespace chrome {
          *
          * @see https://developer.chrome.com/apps/sockets_udp#method-getJoinedGroups
          * @param socketId The socket ID.
-          * @param callback Called with an array of strings of the result.
+         * @param callback Called with an array of strings of the result.
          */
         function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void;
 
@@ -5381,7 +5816,7 @@ declare namespace chrome {
          * @see https://developer.chrome.com/apps/sockets_udp#method-setBroadcast
          * @param socketId The socket ID.
          * @param enabled  true to enable broadcast packets, false to disable them.
-          * @param callback Callback from the setBroadcast method.
+         * @param callback Callback from the setBroadcast method.
          */
         function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void;
 
@@ -5415,20 +5850,20 @@ declare namespace chrome {
         interface StorageArea {
             /**
              * Gets the amount of space (in bytes) being used by one or more items.
-              * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
+             * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
              * Parameter bytesInUse: Amount of space being used in storage, in bytes.
              */
             getBytesInUse(callback: (bytesInUse: number) => void): void;
             /**
              * Gets the amount of space (in bytes) being used by one or more items.
              * @param keys A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage.
-              * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
+             * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
              * Parameter bytesInUse: Amount of space being used in storage, in bytes.
              */
             getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: number) => void): void;
             /**
              * Removes all items from storage.
-              * @param callback Optional.
+             * @param callback Optional.
              * Callback on success, or on failure (in which case runtime.lastError will be set).
              */
             clear(callback?: () => void): void;
@@ -5436,20 +5871,20 @@ declare namespace chrome {
              * Sets multiple items.
              * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected.
              * Primitive values such as numbers will serialize as expected. Values with a typeof 'object' and 'function' will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation).
-              * @param callback Optional.
+             * @param callback Optional.
              * Callback on success, or on failure (in which case runtime.lastError will be set).
              */
             set(items: Object, callback?: () => void): void;
             /**
              * Removes one or more items from storage.
              * @param A single key or a list of keys for items to remove.
-              * @param callback Optional.
+             * @param callback Optional.
              * Callback on success, or on failure (in which case runtime.lastError will be set).
              */
             remove(keys: string | string[], callback?: () => void): void;
             /**
              * Gets one or more items from storage.
-              * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
+             * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
              * Parameter items: Object with items in their key-value mappings.
              */
             get(callback: (items: { [key: string]: any }) => void): void;
@@ -5457,7 +5892,7 @@ declare namespace chrome {
              * Gets one or more items from storage.
              * @param keys A single key to get, list of keys to get, or a dictionary specifying default values.
              * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage.
-              * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
+             * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
              * Parameter items: Object with items in their key-value mappings.
              */
             get(keys: string | string[] | Object | null, callback: (items: { [key: string]: any }) => void): void;
@@ -5524,55 +5959,55 @@ declare namespace chrome {
      * the same data can be available across different clients. Read Manage Data for
      * more on using this API.
      *
-     * @requires[Permissions: "syncFileSystem"]
+     * @requires[Permissions: 'syncFileSystem']
      * @see[Learn more: Manage Data]{@link https://developer.chrome.com/apps/app_storage}
      * @since Chrome 27
      */
     namespace syncFileSystem {
         /**
-         * "initializing"
+         * 'initializing'
          *  - The sync service is being initialized (e.g. restoring data from the database, checking connectivity and authenticating to the service etc).
-         * "running"
+         * 'running'
          *  - The sync service is up and running.
-         * "authentication_required"
+         * 'authentication_required'
          *  - The sync service is not synchronizing files because the remote service needs to be authenticated by the user to proceed.
-         * "temporary_unavailable"
+         * '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"
+         * '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.)
          */
         enum ServiceStatus {
-            "initializing",
-            "running",
-            "authentication_required",
-            "temporary_unavailable",
-            "disabled"
+            'initializing',
+            'running',
+            'authentication_required',
+            'temporary_unavailable',
+            'disabled'
         }
         /**
-         * "synced"
+         * 'synced'
          *  - Not conflicting and has no pending local changes.
-         * "pending"
+         * 'pending'
          *  - Has one or more pending local changes that haven't been synchronized.
-         * "conflicting"
+         * 'conflicting'
          *  - File conflicts with remote version and must be resolved manually.
          */
         enum FileStatus {
-            "synced",
-            "pending",
-            "conflicting"
+            'synced',
+            'pending',
+            'conflicting'
         }
         enum ConflictResolutionPolicy {
-            "last_write_win",
-            "manual"
+            'last_write_win',
+            'manual'
         }
         enum Action {
-            "added",
-            "updated",
-            "deleted"
+            'added',
+            'updated',
+            'deleted'
         }
         enum Direction {
-            "local_to_remote",
-            "remote_to_local"
+            'local_to_remote',
+            'remote_to_local'
         }
         interface FileStatusInfo {
             /** One of the Entry's originally given to getFileStatuses. */
@@ -5620,7 +6055,7 @@ declare namespace 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.
+         * @param callback A callback type for requestFileSystem.
          */
         function requestFileSystem(callback: (fileSystem: FileSystem) => void): void;
         /**
@@ -5638,7 +6073,7 @@ declare namespace chrome {
         /**
          * Returns the current usage and quota in bytes for the 'syncable' file storage for the app.
          * @param fileSystem
-          * @param callback
+         * @param callback
          */
         function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: number, quotaBytes: number }) => void): void;
         /**
@@ -5652,7 +6087,7 @@ declare namespace chrome {
         /**
          * Returns the current sync backend status.
          * @since Chrome 31.
-          * @param callback
+         * @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). */
@@ -6116,7 +6551,7 @@ declare namespace chrome {
         function getInfo(callback: (info: StorageUnitInfo[]) => void): void;
         /**
          * Ejects a removable storage device.
-          * @param callback
+         * @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.
          */
         function ejectDevice(id: string, callback: (result: string) => void): void;
@@ -6225,14 +6660,14 @@ declare namespace chrome {
         /**
          * 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 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.
          */
         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 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.
+         * @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.
          */
         function speak(utterance: string, options: SpeakOptions, callback?: Function): void;
         /**
@@ -6320,7 +6755,7 @@ declare namespace chrome {
             /**
              * Sets the value of a setting.
              * @param details Which setting to change.
-              * @param callback Called at the completion of the set operation.
+             * @param callback Called at the completion of the set operation.
              */
             set(details: ChromeSettingSetDetails, callback?: Function): void;
             /**
@@ -6331,7 +6766,7 @@ declare namespace chrome {
             /**
              * Clears the setting, restoring any default value.
              * @param details Which setting to clear.
-              * @param callback 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. */
@@ -6496,26 +6931,26 @@ declare namespace chrome {
         /**
          * Creates a new VPN configuration that persists across multiple login sessions of the user.
          * @param name The name of the VPN configuration.
-          * @param callback Called when the configuration is created or if there is an error.
+         * @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.
          */
         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 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.
          */
         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.
+         * @param callback Called when the parameters are set or if there is an error.
          */
         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 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.
          */
         function sendPacket(data: ArrayBuffer, callback?: Function): void;
         /**
@@ -6523,7 +6958,7 @@ declare namespace chrome {
          * @param state The VPN session state of the VPN client.
          * connected: VPN connection was successful.
          * failure: VPN connection failed.
-          * @param callback 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.
          */
         function notifyConnectionStateChanged(state: string, callback?: Function): void;
 
@@ -6819,13 +7254,13 @@ declare namespace chrome {
 
             /**
              * 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.
+            * @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;
             /**
              * Captures the visible region of the webview.
              * @param options
-             * @param callback
+            * @param callback
              */
             captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void;
 
@@ -6903,7 +7338,7 @@ declare namespace chrome {
              * 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
+            * @param callback
              */
             clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void;
 
@@ -6913,7 +7348,7 @@ declare namespace chrome {
              * 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
+            * @param callback
              */
             executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void;
 
@@ -6921,13 +7356,13 @@ declare namespace chrome {
              * 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
+            * @param callback
              */
             find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void;
 
             /**
              * Navigates forward one history entry if possible. Equivalent to go(1).
-             * @param callback
+            * @param callback
              */
             forward(callback?: (success: boolean) => void): void;
 
@@ -6943,13 +7378,13 @@ declare namespace chrome {
 
             /**
              * Gets the current zoom factor.
-             * @param callback
+            * @param callback
              */
             getZoom(callback: (zoomFactor: number) => void): void;
 
             /**
              * Gets the current zoom mode.
-             * @param callback
+            * @param callback
              */
             getZoomMode(callback: (ZoomMode: any) => void): void;
 
@@ -6959,14 +7394,14 @@ declare namespace chrome {
              * @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
+            * @param callback
              */
             go(relativeIndex: number, callback?: (success: boolean) => void): void;
 
             /**
              * Injects CSS into the guest page.
              * @param details Details of the CSS to insert.
-             * @param callback
+            * @param callback
              */
             insertCSS(details: InjectDetails, callback?: () => void): void;
 
@@ -7076,7 +7511,7 @@ declare namespace chrome {
 
             /**
              * 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 + * @param callback */ dialog: chrome.events.Event; @@ -7091,7 +7526,7 @@ declare namespace chrome { * webview.src = 'data:text/plain,Goodbye, world!'; * } * }); - * @param callback + * @param callback */ exit: chrome.events.Event; @@ -7119,21 +7554,21 @@ declare namespace chrome { /** * 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 + * @param callback */ loadcommit: chrome.events.Event; /** * Fired when a top-level load request has redirected to a different URL. - * @param callback + * @param callback */ loadredirect: chrome.events.Event; /** * Fired when a load has begun. - * @param callback + * @param callback */ loadstart: chrome.events.Event; @@ -7429,7 +7864,7 @@ declare namespace chrome { /** * A function that will be called back when the menu item is clicked. - * @param callback + * @param callback */ onclick?: (info: any) => void; diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index dc8e09d5d8..7ee0b882e0 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -432,3 +432,5 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { } }) chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT; + +chrome.i18n.getMessage('click_here', ['string1', 'string2']); From 59ce1a1a90d9411b8e5070902ddfa3436a49a0fa Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 31 Jul 2018 16:37:17 +0200 Subject: [PATCH 016/289] Fixed and cleanup: idle, instanceId, mediaGalleries (+added docs) --- types/chrome-apps/index.d.ts | 241 ++++++++++++++++++++++++++++------- 1 file changed, 198 insertions(+), 43 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 5a5a6645f5..cba9ee1d4b 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -4068,30 +4068,49 @@ declare namespace chrome { */ function setDetectionInterval(intervalInSeconds: integer): void; - /*** Fired when the system changes to an active, idle or locked state. + /** + * 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. */ - var onStateChanged: chrome.events.Event<(newState: IdleState) => void>; + const onStateChanged: chrome.events.Event<(newState: IdleState) => void>; } - //////////////////// - // InstanceID - //////////////////// + //////////////// + // InstanceID // + //////////////// /** * Use chrome.instanceID to access the Instance ID service. - * Permissions: 'gcm' + * @requires Permissions: 'gcm' * @since Chrome 46 */ namespace instanceID { 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; } /** @@ -4141,8 +4160,9 @@ declare namespace chrome { //////////////////// /** * Use the chrome.mdns API to discover services over mDNS. - * This comprises a subset of the features of the NSD spec: @see[Spec link]{@link http://www.w3.org/TR/discovery-api/} - * Permissions: '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 { @@ -4190,51 +4210,83 @@ declare namespace chrome { //////////////////// // 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 { + enum 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; } + enum 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; @@ -4244,9 +4296,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[]; } @@ -4255,39 +4314,135 @@ declare namespace chrome { success: boolean; } + enum GalleryChangedType { + 'contents_changed', + 'watch_dropped' + } interface GalleryChangedEventArgs { - type: 'contents_changed' | 'watch_dropped'; + type: GalleryChangedType; galleryId: string; } + enum 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; } + /** + * 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. + */ var 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. + */ var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } From 9a8accde5860d86b1813891dfc7fd83e123bf317 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 31 Jul 2018 16:59:28 +0200 Subject: [PATCH 017/289] Transfer types to enums --- types/chrome-apps/index.d.ts | 265 ++++++++++++++++++++--------------- 1 file changed, 155 insertions(+), 110 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index cba9ee1d4b..9ad4cdf884 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -57,6 +57,10 @@ declare namespace chrome { incognito?: boolean; } + enum LevelOfControl { + 'not_controllable', 'controlled_by_other_extensions', 'controllable_by_this_extension', 'controlled_by_this_extension' + } + interface AccessibilityFeaturesCallbackArg { /** The value of the setting. */ value: any; @@ -67,11 +71,15 @@ 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'; + 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; } + enum Scope { + 'regular', 'regular_only', 'incognito_persistent', 'incognito_session_only' + } + interface AccessibilityFeaturesSetArg { /** * The value of the setting. @@ -79,26 +87,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 { @@ -292,10 +298,12 @@ declare namespace chrome { * 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'; + enum 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' + } interface EmbedRequest { /** @@ -498,6 +506,10 @@ declare namespace chrome { inactiveColor?: string; } + enum WindowState { + 'normal', 'fullscreen', 'maximized', 'minimized' + } + interface CreateWindowOptions { /** * Id to identify the window. @@ -575,7 +587,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?: WindowState; /** * 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. */ @@ -747,14 +759,19 @@ declare namespace chrome { * This API is currently only implemented for ChromeOS. */ namespace audio { - type StreamType = 'INPUT' | 'OUTPUT'; + enum StreamType { + 'INPUT', 'OUTPUT' + } + enum 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. */ @@ -786,30 +803,21 @@ declare namespace chrome { */ 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: @@ -884,6 +892,12 @@ declare namespace chrome { /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } + enum DeviceType { + 'computer', 'phone', 'modem', 'audio', 'carAudio', 'video', 'peripheral', 'joystick', 'gamepad', 'keyboard', 'mouse', 'tablet', 'keyboardMouseCombo' + } + enum DeviceVendorIdSource { + 'bluetooth', 'usb' + } interface Device { /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; @@ -892,7 +906,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; @@ -901,7 +915,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. */ @@ -939,43 +953,56 @@ declare namespace chrome { addListener(callback: (event: T) => void): void; } + enum 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. */ function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; + /** Get information about a Bluetooth device known to the system. */ 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. */ 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. */ function startDiscovery(callback: () => void): void; + /** Stop discovery. */ function stopDiscovery(callback: () => void): void; + /** Fired when the state of the Bluetooth adapter changes. */ var onAdapterStateChanged: BluetoothEvent; + /** Fired when information about a new Bluetooth device is available. */ var onDeviceAdded: BluetoothEvent; + /** Fired when information about a known Bluetooth device has changed. */ var 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. */ var onDeviceRemoved: BluetoothEvent; } @@ -2452,7 +2479,7 @@ declare namespace chrome { */ mimeTypes?: string[]; /** - * Extensions to accept, e.g. 'jpg' | 'gif' | 'crx'. + * Extensions to accept, e.g. 'jpg', 'gif', 'crx'. */ extensions?: string[]; } @@ -4214,8 +4241,8 @@ declare namespace chrome { * 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"]} + * @requires Permissions: {"mediaGalleries": ["accessType1", "accessType2", ...]} + * {"mediaGalleries": ["accessType1", "accessType2", ..., "allAutoDetected"]} * @see[More information]{@link https://developer.chrome.com/apps/mediaGalleries} */ namespace mediaGalleries { @@ -4230,7 +4257,7 @@ declare namespace chrome { * 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** @@ -4304,7 +4331,7 @@ declare namespace chrome { rawTags: RawTag[]; /** * The images embedded in the media file's metadata. - * This is most often used for album art or video thumbnails. + * This is most often used for album art or video thumbnails. */ attachedImages: Blob[]; } @@ -4329,7 +4356,7 @@ declare namespace chrome { 'finish', 'error' } - + interface ScanProgressEventArgs { /** The type of progress event, i.e. start, finish, etc. */ type: ScanProgressType; @@ -4450,127 +4477,121 @@ declare namespace chrome { // 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 enum values use UpperCamelCase to match + * the ONC specification instead of the JavaScript lowerCamelCase convention. */ namespace networking.onc { - 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'; + enum ActivationStateType { + 'Activated', 'Activating', 'NotActivated', 'PartiallyActivated' + } + enum CaptivePortalStatus { + 'Unknown', 'Offline', 'Online', 'Portal', 'ProxyAuthRequired' + } + enum ConnectionStateType { + 'Connected', 'Connecting', 'NotConnected' + } + enum IPConfigType { + 'DHCP', 'Static' + } + enum NetworkType { + 'All', 'Cellular', 'Ethernet', 'VPN', 'Wireless', 'WiFi', 'WiMAX' + } + enum ProxySettingsType { + 'Direct', 'Manual', 'PAC', 'WPAD' + } interface ManagedBoolean { /** - * The active value currently used by the network configuration manager (e.g. Shill). - * @type {boolean} - * @memberof ManagedBoolean + * The active value currently used by the network configuration manager (e.g. Shill). */ Active?: boolean, /** - * The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedBoolean + * The source from which the effective property value was determined. */ Effective?: string, /** - * The property value provided by the user policy. - * @type {boolean} - * @memberof ManagedBoolean + * The property value provided by the user policy. */ UserPolicy?: boolean, /** - * The property value provided by the device policy. - * @type {boolean} - * @memberof ManagedBoolean + * The property value provided by the device policy. */ DevicePolicy?: boolean, /** - * The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {boolean} - * @memberof ManagedBoolean + * The property value set by the logged in user. Only provided if |UserEditable| is true. */ UserSettings?: boolean, /** - * The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {boolean} - * @memberof ManagedBoolean + * The value set for all users of the device. Only provided if |DeviceEditiable| is true. */ SharedSettings?: boolean, /** - * 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 + * Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * @default false */ UserEditable?: boolean, /** - * 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 + * Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * @default false */ DeviceEditable?: boolean } interface ManagedLong { /** - * The active value currently used by the network configuration manager (e.g. Shill). - * @type {number} - * @memberof ManagedLong + * The active value currently used by the network configuration manager (e.g. Shill). */ - Active?: number, + Active?: integer, /** - * The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedLong + * The source from which the effective property value was determined. */ Effective?: string, /** - * The property value provided by the user policy. - * @type {number} - * @memberof ManagedLong + * The property value provided by the user policy. */ - UserPolicy?: number, + UserPolicy?: integer, /** - * The property value provided by the device policy. - * @type {number} - * @memberof ManagedLong + * The property value provided by the device policy. */ - DevicePolicy?: number, + DevicePolicy?: integer, /** - * The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {number} - * @memberof ManagedLong + * The property value set by the logged in user. Only provided if UserEditable is true. */ - UserSettings?: number, + UserSettings?: integer, /** - * The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {number} - * @memberof ManagedLong + * The value set for all users of the device. Only provided if DeviceEditiable is true. */ - SharedSettings?: number, + SharedSettings?: integer, /** - * 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 + * Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * @default false */ UserEditable?: boolean, /** - * 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 + * Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * @default false */ DeviceEditable?: boolean } } - //////////////////// - // 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 { @@ -6377,6 +6398,10 @@ declare namespace chrome { isSelected: boolean; } + enum DisplayPosition { + 'top', 'right', 'bottom', 'left' + } + /** * @since Chrome 53 */ @@ -6386,7 +6411,7 @@ 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; } @@ -6933,7 +6958,9 @@ declare namespace chrome { // USB //////////////////// namespace usb { - type Direction = 'in' | 'out'; + enum Direction { + 'in', 'out' + } interface Device { device: number, @@ -6950,13 +6977,23 @@ declare namespace chrome { productId: number } + enum EndpointType { + 'control', 'interrupt', 'isochronous', 'bulk' + } + enum EndpointSyncType { + 'asynchronous', 'adaptive', 'synchronous' + } + enum 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 } @@ -7004,10 +7041,18 @@ declare namespace chrome { interfaceProtocol?: number } + enum TransferRecipient { + 'device', 'interface', 'endpoint', 'other' + } + + enum 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; From 3a3005da397b90c27f2fb505c79e54e9c1e9e408 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 11:59:10 +0200 Subject: [PATCH 018/289] networking.onc -> complete api typing, Enums to types to prevent runtime errors --- types/chrome-apps/index.d.ts | 1277 +++++++++++++++++-------------- types/chrome-apps/test/index.ts | 33 +- 2 files changed, 748 insertions(+), 562 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 9ad4cdf884..589361f54a 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -57,9 +57,9 @@ declare namespace chrome { incognito?: boolean; } - enum LevelOfControl { - 'not_controllable', 'controlled_by_other_extensions', 'controllable_by_this_extension', 'controlled_by_this_extension' - } + type LevelOfControl = + 'not_controllable' | 'controlled_by_other_extensions' | + 'controllable_by_this_extension' | 'controlled_by_this_extension'; interface AccessibilityFeaturesCallbackArg { /** The value of the setting. */ @@ -76,9 +76,7 @@ declare namespace chrome { incognitoSpecific?: boolean; } - enum Scope { - 'regular', 'regular_only', 'incognito_persistent', 'incognito_session_only' - } + type Scope = 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; interface AccessibilityFeaturesSetArg { /** @@ -298,12 +296,11 @@ declare namespace chrome { * and can shut down the app at anytime. */ namespace app.runtime { - enum 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' - } + 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'; interface EmbedRequest { /** @@ -356,7 +353,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. @@ -506,9 +503,7 @@ declare namespace chrome { inactiveColor?: string; } - enum WindowState { - 'normal', 'fullscreen', 'maximized', 'minimized' - } + type WindowState = 'normal' | 'fullscreen' | 'maximized' | 'minimized'; interface CreateWindowOptions { /** @@ -759,12 +754,14 @@ declare namespace chrome { * This API is currently only implemented for ChromeOS. */ namespace audio { - enum StreamType { - 'INPUT', 'OUTPUT' - } - enum 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' - } + 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; @@ -892,12 +889,14 @@ declare namespace chrome { /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } - enum DeviceType { - 'computer', 'phone', 'modem', 'audio', 'carAudio', 'video', 'peripheral', 'joystick', 'gamepad', 'keyboard', 'mouse', 'tablet', 'keyboardMouseCombo' - } - enum DeviceVendorIdSource { - 'bluetooth', 'usb' - } + 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; @@ -953,9 +952,7 @@ declare namespace chrome { addListener(callback: (event: T) => void): void; } - enum DeviceFilterType { - 'all', 'known' - } + 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. @@ -1035,22 +1032,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; @@ -1063,14 +1059,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; @@ -1118,9 +1114,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; @@ -1558,10 +1552,9 @@ declare namespace chrome { */ clientSocketId: integer; } - enum OnAcceptErrorCode { - 'system_error', - 'not_listening' - } + type OnAcceptErrorCode = + 'system_error' | + 'not_listening'; interface OnAcceptErrorEventData { /** The server socket identifier. */ socketId: integer; @@ -1583,11 +1576,10 @@ declare namespace chrome { /** The data received, with a maxium size of bufferSize. */ data: ArrayBuffer; } - enum OnReceiveErrorCode { - 'disconnected', - 'system_error', - 'not_connected' - } + type OnReceiveErrorCode = + 'disconnected' | + 'system_error' | + 'not_connected'; interface OnReceiveErrorEventData { /** The server socket identifier. */ socketId: integer; @@ -1867,36 +1859,32 @@ declare namespace chrome { /** * 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. **/ - enum 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. **/ - enum ItemType { - 'normal', - 'checkbox', - 'radio', - 'separator' - } - - enum MediaType { - 'image', - 'video', - 'audio' - } + type ItemType = + 'normal' | + 'checkbox' | + 'radio' | + 'separator'; + type MediaType = + 'image' | + 'video' | + 'audio'; interface OnClickData { /** * The ID of the menu item that was clicked. @@ -2343,10 +2331,9 @@ declare namespace chrome { /** * The format of an image. **/ - enum ImageFormat { - 'jpeg', - 'png' - } + type ImageFormat = + 'jpeg' | + 'png'; /** * Details about the format and quality of an image. */ @@ -2365,18 +2352,16 @@ declare namespace chrome { /** * The soonest that the JavaScript or CSS will be injected into the tab. **/ - enum RunAt { - 'document_start', - 'document_end', - 'document_idle' - } + type RunAt = + 'document_start' | + 'document_end' | + 'document_idle'; /** * The origin of injected CSS. **/ - enum CSSOrigin { - 'author', - 'user' - } + type CSSOrigin = + 'author' | + 'user'; /** * Internal interfaces, not to be used directly * @private @@ -2456,17 +2441,15 @@ declare namespace chrome { * {'fileSystem': ['write', 'retainEntries', 'directory']} */ namespace fileSystem { - enum ChildChangeType { - 'created', - 'removed', - 'changed' - } - enum ChooseEntryOptionsTypes { - 'openFile', - 'openWritableFile', - 'saveFile', - 'openDirectory' - } + type ChildChangeType = + 'created' | + 'removed' | + 'changed'; + type ChooseEntryOptionsTypes = + 'openFile' | + 'openWritableFile' | + 'saveFile' | + 'openDirectory'; interface AcceptOptions { /** * This is the optional text description for this option. @@ -2618,7 +2601,7 @@ declare namespace chrome { * 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 (enum of 'file', 'device', or 'network') - required** + * **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. @@ -2635,35 +2618,32 @@ declare namespace chrome { * as well as in case of errors when calling methods of the API. * For success, 'OK' must be used. * */ - enum 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' - } + 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. */ - enum OpenFileMode { - 'READ', - 'WRITE' - } + type OpenFileMode = + 'READ' | + 'WRITE'; /** Type of a change detected on the observed directory. */ - enum ChangeType { - 'CHANGED', - 'DELETED' - } + type ChangeType = + 'CHANGED' | + 'DELETED'; /** * List of common actions. 'SHARE' is for sharing files with others. * 'SAVE_FOR_OFFLINE' for pinning (saving for offline access). @@ -2671,11 +2651,10 @@ declare namespace chrome { * need to be stored for offline access anymore. * Used by onGetActionsRequested and onExecuteActionRequested. */ - enum CommonActionId { - 'SAVE_FOR_OFFLINE', - 'OFFLINE_NOT_NECESSARY', - 'SHARE' - } + type CommonActionId = + 'SAVE_FOR_OFFLINE' | + 'OFFLINE_NOT_NECESSARY' | + 'SHARE'; interface EntryMetadata { /** True if it is a directory. Must be provided if requested in options */ @@ -3665,180 +3644,179 @@ declare namespace chrome { /** * @see[Source]{@link https://github.com/chromium/chromium/blob/master/ui/base/l10n/l10n_util.cc} */ - enum 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 + 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 + '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", - } + '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 = @@ -4073,11 +4051,10 @@ declare namespace chrome { * @since Chrome 25. */ namespace idle { - enum IdleState { - 'active', - 'idle', - 'locked' - } + 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. @@ -4241,16 +4218,15 @@ declare namespace chrome { * 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"]} + * @requires Permissions: {'mediaGalleries': ['accessType1' | 'accessType2', ...]} + * {'mediaGalleries': ['accessType1' | 'accessType2', ..., 'allAutoDetected']} * @see[More information]{@link https://developer.chrome.com/apps/mediaGalleries} */ namespace mediaGalleries { - enum Interactive { - 'no', - 'yes', - 'if_needed' - } + type Interactive = + 'no' | + 'yes' | + 'if_needed'; interface MediaFileSystemsOptions { /** * Whether to prompt the user for permission to additional media galleries before returning @@ -4282,11 +4258,10 @@ declare namespace chrome { isAvailable: boolean; } - enum MetadataOptionsType { - 'all', - 'mimeTypeAndTags', - 'mimeTypeOnly' - } + type MetadataOptionsType = + 'all' | + 'mimeTypeAndTags' | + 'mimeTypeOnly'; interface MetadataOptions { metadataType: MetadataOptionsType; @@ -4294,7 +4269,7 @@ declare namespace chrome { interface RawTag { /** - * Describes format of container or codec of stream, i.e. "mp3", "h264". + * Describes format of container or codec of stream, i.e. 'mp3' | 'h264'. */ type: string; /** @@ -4341,21 +4316,20 @@ declare namespace chrome { success: boolean; } - enum GalleryChangedType { - 'contents_changed', - 'watch_dropped' - } + type GalleryChangedType = + 'contents_changed' | + 'watch_dropped'; + interface GalleryChangedEventArgs { type: GalleryChangedType; galleryId: string; } - enum ScanProgressType { - 'start', - 'cancel', - 'finish', - 'error' - } + type ScanProgressType = + 'start' | + 'cancel' | + 'finish' | + 'error'; interface ScanProgressEventArgs { /** The type of progress event, i.e. start, finish, etc. */ @@ -4478,7 +4452,7 @@ declare namespace chrome { //////////////////////////////////// /** * @requires(CrOS kiosk mode) This API is available in Chrome OS kiosk sessions. - * @requires Permissions: "networking.onc" + * @requires Permissions: 'networking.onc' * @since Since Chrome 59 * @description * The chrome.networking.onc API is used for configuring network connections @@ -4487,100 +4461,319 @@ declare namespace chrome { * @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 enum values use UpperCamelCase to match + * Most dictionary properties and type values use UpperCamelCase to match * the ONC specification instead of the JavaScript lowerCamelCase convention. */ namespace networking.onc { - enum ActivationStateType { - 'Activated', 'Activating', 'NotActivated', 'PartiallyActivated' + 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_ { + interface NetworkConfigBase< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full'> { + Cellular?: IF extends 'partial' ? CellularBase : CellularProperties; + Ethernet?: IF extends 'partial' ? { Authentication: string; } : EthernetProperties; + GUID?: string; + IPAddressConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + Name?: M extends 'managed' ? ManagedDOMString : string; + NameServersConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + Priority?: M extends 'managed' ? ManagedLong : integer; + Type?: NetworkType; + VPN?: IF extends 'partial' ? { Type: string; } : VPNProperties; + WiFi?: IF extends 'partial' ? WiFiPropertiesBase : WiFiProperties; + WiMAX?: IF extends 'partial' ? { SignalStrength?: integer } : WiMAXProperties; + } } - enum CaptivePortalStatus { - 'Unknown', 'Offline', 'Online', 'Portal', 'ProxyAuthRequired' - } - enum ConnectionStateType { - 'Connected', 'Connecting', 'NotConnected' - } - enum IPConfigType { - 'DHCP', 'Static' - } - enum NetworkType { - 'All', 'Cellular', 'Ethernet', 'VPN', 'Wireless', 'WiFi', 'WiMAX' - } - enum ProxySettingsType { - 'Direct', 'Manual', 'PAC', 'WPAD' - } - interface ManagedBoolean { + 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; /** - * The active value currently used by the network configuration manager (e.g. Shill). - */ - Active?: boolean, - /** - * The source from which the effective property value was determined. - */ - Effective?: string, - /** - * The property value provided by the user policy. - */ - UserPolicy?: boolean, - /** - * The property value provided by the device policy. - */ - DevicePolicy?: boolean, - /** - * The property value set by the logged in user. Only provided if |UserEditable| is true. - */ - UserSettings?: boolean, - /** - * The value set for all users of the device. Only provided if |DeviceEditiable| is true. - */ - SharedSettings?: boolean, - /** - * Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * Whether a UserPolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). * @default false */ - UserEditable?: boolean, + UserEditable?: boolean; /** - * Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). + * Whether a DevicePolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). * @default false */ - DeviceEditable?: boolean + DeviceEditable?: boolean; } - interface ManagedLong { - /** - * The active value currently used by the network configuration manager (e.g. Shill). - */ - Active?: integer, - /** - * The source from which the effective property value was determined. - */ - Effective?: string, - /** - * The property value provided by the user policy. - */ - UserPolicy?: integer, - /** - * The property value provided by the device policy. - */ - DevicePolicy?: integer, - /** - * The property value set by the logged in user. Only provided if UserEditable is true. - */ - UserSettings?: integer, - /** - * The value set for all users of the device. Only provided if DeviceEditiable is true. - */ - SharedSettings?: integer, - /** - * Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). - * @default false - */ - UserEditable?: boolean, - /** - * Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). - * @default false - */ - DeviceEditable?: boolean + interface ManagedBoolean extends ManagedType { } + interface ManagedLong extends ManagedType { } + interface ManagedDOMString extends ManagedType { } + interface ManagedDOMStringList extends ManagedType { } + interface ManagedIPConfigType extends ManagedType { } + + interface CellularProviderProperties { + Name: string; + Code: string; + Country?: string; } + interface IssuerSubjectPattern { + CommonName?: string; + Locality?: string; + Organization?: string; + OrganizationalUnit?: string; + } + interface CertPattern { + EnrollmentURI?: string[]; + Issuer?: IssuerSubjectPattern; + IssuerCARef?: string[]; + 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; + Outer?: string; + Password?: string; + SaveCredentials?: boolean; + ServerCAPEMs?: string[]; + ServerCARefs?: string[]; + /** @since Chrome 60. */ + SubjectMatch?: ManagedDOMString; + UseProactiveKeyCaching?: boolean; + UseSytemCAs?: boolean; + } + interface FoundNetworkProperties { + Status: string; + NetworkId: string; + Technology: string; + ShortName?: string; + LongName?: string; + } + type IPConfigurationType = 'IPv4' | 'IPv6'; + interface IPConfigProperties { + Gateway?: S; + IPAddress?: S; + NameServers?: SL; + RoutingPrefix?: L; + Type?: M extends 'managed' ? ManagedType : IPConfigurationType; + WebProxyAutoDiscoveryUrl?: S; + } + interface PaymentPortal { + Method: string; + PostData?: string; + Url?: string; + } + interface ProxyLocation { + Host?: string; + Port?: integer; + } + interface ManagedProxyLocation { + Host?: ManagedDOMString; + Port?: ManagedLong; + } + interface ManualProxySettings { + HTTPProxy?: P; + SecureHTTPProxy?: P; + FTPProxy?: P; + SOCKS?: P; + } + interface ProxySettings { + Type: M extends 'managed' ? ManagedType : ProxySettingsType; + Manual?: ManualProxySettings; + ExcludeDomains?: SL; + PAC?: S; + } + interface SIMLockStatus { + LockType: string; + LockEnabled: boolean; + RetriesLeft?: integer; + } + interface ThirdPartyVPNProperties { + ExtensionID: string; + ProviderName?: string; + } + interface ManagedThirdPartyVPNProperties { + ExtensionID: ManagedDOMString; + ProviderName?: string; + } + interface CellularBase { + ActivationState?: ActivationStateType; + NetworkTechnology?: string; + RoamingState?: string; + SIMPresent?: boolean; + SignalStrength?: integer; + } + interface CellularProperties extends CellularBase { + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + ActivationType?: string; + AllowRoaming?: boolean; + Carrier?: M extends 'managed' ? ManagedDOMString : string; + Family?: string; + FirmwareRevision?: string; + FoundNetworks?: FoundNetworkProperties[]; + HardwareRevision?: string; + HomeProvider?: CellularProviderProperties; + MAnufacturer?: string; + ModelID?: string; + PaymentPortal?: PaymentPortal; + PRLVersion?: integer; + /** + * @since Chrome 63. + */ + Scanning?: boolean; + ServingOperator?: CellularProviderProperties; + SIMLockStatus?: SIMLockStatus; + SupportNetworkScan?: boolean; + SupportedCarriers?: string[]; + } + type EthernetAuthenticationType = 'None' | '8021X'; + interface EthernetProperties { + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + Authentication?: M extends 'managed' ? ManagedType : EthernetAuthenticationType; + EAP?: EAPProperties; + } + interface VPNProperties { + AutoConnect?: B; + Host?: S; + Type?: S; + } + interface WiFiPropertiesBase { + BSSID?: string; + Frequency?: integer; + HexSSID?: S; + Security?: S; + SSID?: S; + SignalStrength?: integer; + } + interface WiFiProperties extends WiFiPropertiesBase { + AllowGatewayARPPolling?: B; + AutoConnect?: B; + EAP?: EAPProperties; + FrequencyList?: integer[]; + HiddenSSID?: B; + /** @since Chrome 66. */ + Passphrase?: string; + RoamTreshold?: L; + + } + interface WiMAXProperties { + AutoConnect?: B; + EAP?: EAPProperties; + SignalStrength?: integer; + } + type ManagedObject = 'managed' | 'unmanaged'; + type InterfaceType = 'partial' | 'full'; + interface NetworkConfigProperties extends _internal_.NetworkConfigBase<'unmanaged', 'full'> { } + interface NetworkProperties< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full'> extends _internal_.NetworkConfigBase { + Connectable?: boolean; + ConnectionState?: ConnectionStateType; + ErrorState?: string; + IPConfigs?: IPConfigProperties[]; + MacAddress?: string; + ProxySettings?: ProxySettings<'unmanaged'>; + RestrictedConnectivity?: boolean; + StaticIPConfig?: IPConfigProperties; + SavedIPConfig?: IPConfigProperties<'unmanaged'>; + Source?: 'Device' | 'DevicePolicy' | 'User' | 'UserPolicy' | 'None'; + } + interface ManagedProperties extends NetworkProperties<'managed'> { } + interface NetworkStateProperties extends NetworkProperties<'unmanaged', 'partial'> { } + + interface Filter { + networkType: NetworkType; + /** @default false */ + visible?: boolean; + /** @default false */ + configured?: boolean; + /** + * Use 0 for no limit + * @default 1000 + * */ + limit?: integer; + } + + type DeviceState = 'Uninitialized' | 'Disabled' | 'Enabling' | 'Enabled' | 'Prohibited'; + + interface DeviceStates { + Scanning?: boolean; + SIMLockStatus?: SIMLockStatus; + SIMPresent?: boolean; + State: DeviceState; + Type: NetworkType; + } + + interface GlobalPolicy { + AllowOnlyPolicyNetworksToAutoconnect?: boolean; + AllowOnlyPolicyNetworksToConnect?: boolean; + BlacklistedHexSSIDs?: string[]; + } + + function getProperties(networkGuid: string, callback: (result: NetworkProperties) => void): void; + function getManagedProperties(networkGuid: string, callback: (result: ManagedProperties) => void): void; + function getState(networkGuid: string, callback: (result: NetworkStateProperties) => void): void; + function setProperties(networkGuid: string, properties: NetworkConfigProperties, callback?: () => void): void; + function createNetwork(shared: boolean, properties: NetworkConfigProperties, callback?: () => void): void; + function forgetNetwork(networkGuid: string, callback?: () => void): void; + function getNetworks(filter: Filter, callback: (result: NetworkStateProperties[]) => void): void; + function getDeviceStates(callback?: (result: DeviceStates[]) => void): void; + function enableNetworkType(networkType: NetworkType): void; + function disableNetworkType(networkType: NetworkType): void; + function requestNetworkScan(): void; + /** + * @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; + function startConnect(networkGuid: string, callback?: () => void): void; + function startDisconnect(networkGuid: string, callback?: () => void): void; + function getCaptivePortalStatus(networkGuid: string, callback: (result: CaptivePortalStatus) => void): void; + function getGlobalPolicy(callback: (result: GlobalPolicy) => void): void; + + // + // EVENTS + // + + const onNetworksChanged: chrome.events.Event<(changes: string[]) => void>; + const onNetworkListChanged: chrome.events.Event<(changes: string[]) => void>; + const onDeviceStateListChanged: chrome.events.Event<() => void>; + const onPortalDetectionCompleted: chrome.events.Event<(networkGuid: string, status: CaptivePortalStatus) => void>; } /////////////////// @@ -4872,26 +5065,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. */ - var onGetPrintersRequested: PrinterRequestedEvent; + var 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. */ - var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; + var onGetUsbPrinterInfoRequested: chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void>; /** Event fired when print manager requests printer capabilities. */ - var onGetCapabilityRequested: CapabilityRequestedEvent; + var onGetCapabilityRequested: chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void>; /** Event fired when print manager requests printing. */ - var onPrintRequested: PrintRequestedEvent; + var onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; } //////////////////// @@ -6152,13 +6337,12 @@ declare namespace chrome { * '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.) */ - enum ServiceStatus { - 'initializing', - 'running', - 'authentication_required', - 'temporary_unavailable', - 'disabled' - } + type ServiceStatus = + 'initializing' | + 'running' | + 'authentication_required' | + 'temporary_unavailable' | + 'disabled'; /** * 'synced' * - Not conflicting and has no pending local changes. @@ -6167,24 +6351,23 @@ declare namespace chrome { * 'conflicting' * - File conflicts with remote version and must be resolved manually. */ - enum FileStatus { - 'synced', - 'pending', - 'conflicting' - } - enum ConflictResolutionPolicy { - 'last_write_win', + type FileStatus = + 'synced' | + 'pending' | + 'conflicting'; + type ConflictResolutionPolicy = + 'last_write_win' | 'manual' - } - enum Action { - 'added', - 'updated', + + type Action = + 'added' | + 'updated' | 'deleted' - } - enum Direction { - 'local_to_remote', - 'remote_to_local' - } + + type Direction = + 'local_to_remote' | + 'remote_to_local'; + interface FileStatusInfo { /** One of the Entry's originally given to getFileStatuses. */ fileEntry: Entry; @@ -6398,9 +6581,7 @@ declare namespace chrome { isSelected: boolean; } - enum DisplayPosition { - 'top', 'right', 'bottom', 'left' - } + type DisplayPosition = 'top' | 'right' | 'bottom' | 'left'; /** * @since Chrome 53 @@ -6958,9 +7139,7 @@ declare namespace chrome { // USB //////////////////// namespace usb { - enum Direction { - 'in', 'out' - } + type Direction = 'in' | 'out'; interface Device { device: number, @@ -6977,15 +7156,10 @@ declare namespace chrome { productId: number } - enum EndpointType { - 'control', 'interrupt', 'isochronous', 'bulk' - } - enum EndpointSyncType { - 'asynchronous', 'adaptive', 'synchronous' - } - enum EndpointUsage { - 'data', 'feedback', 'explicitFeedback' - } + type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; + + type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; + type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback'; interface EndpointDescriptor { address: number, @@ -7041,13 +7215,9 @@ declare namespace chrome { interfaceProtocol?: number } - enum TransferRecipient { - 'device', 'interface', 'endpoint', 'other' - } + type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; - enum TransferRequestType { - 'standard', 'class', 'vendor', 'reserved' - } + type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; interface TransferInfo { direction: Direction; @@ -7184,11 +7354,10 @@ declare namespace chrome { * @since Chrome 43. */ namespace wallpaper { - enum WallpaperLayout { - 'STRETCH', - 'CENTER', - 'CENTER_CROPPED' - } + type WallpaperLayout = + 'STRETCH' | + 'CENTER' | + 'CENTER_CROPPED'; interface WallpaperDetails { /** The jpeg or png encoded wallpaper image. */ data?: any; @@ -7242,12 +7411,11 @@ declare namespace chrome { sourceId: string; } - enum ExitEventReason { - 'normal', - 'abnormal', - 'crash', - 'kill' - } + type ExitEventReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; interface ExitEvent extends Event { /** Chrome's internal ID of the process that exited. */ processID: number; @@ -7889,17 +8057,16 @@ declare namespace chrome { * The different contexts a menu can appear in. * Specifying 'all' is equivalent to the combination of all other contexts. **/ - enum ContextType { - 'all', - 'page', - 'frame', - 'selection', - 'link', - 'editable', - 'image', - 'video', - 'audio' - } + 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, @@ -8258,27 +8425,20 @@ declare namespace chrome { * The content will revert to the default zoom level, * and all attempted zoom changes will be ignored. **/ - enum ZoomMode { - 'per-origin', - 'per-view', - 'disabled' - } - enum ConsoleMessageLevel { - LOG_VERBOSE = -1, - LOG_INFO = 0, - LOG_WARNING = 1, - LOG_ERROR = 2 - } - enum 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' - } + 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 { /** * The severity level of the log message. @@ -8296,11 +8456,11 @@ declare namespace chrome { /** A string identifying the resource which logged the message. */ sourceId: string; } - enum DialogMessageType { - 'alert', - 'confirm', - 'prompt' - } + type DialogMessageType = + 'alert' | + 'confirm' | + 'prompt'; + interface Dialog { /** * The type of modal dialog requested by the guest. @@ -8315,12 +8475,11 @@ declare namespace chrome { */ dialog: DialogController; } - enum ExitReason { - 'normal', - 'abnormal', - 'crash', - 'kill' - } + type ExitReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; interface Exit { /** Chrome's internal ID of the process that exited. */ processID: number; @@ -8399,15 +8558,14 @@ declare namespace chrome { /** Whether the load is top-level or in a subframe. */ isTopLevel: boolean; } - enum WindowOpenDisposition { - 'ignore', - 'save_to_disk', - 'current_tab', - 'new_background_tab', - 'new_foreground_tab', - 'new_window', - 'new_popup' - } + type WindowOpenDisposition = + 'ignore' | + 'save_to_disk' | + 'current_tab' | + 'new_background_tab' | + 'new_foreground_tab' | + 'new_window' | + 'new_popup'; interface NewWindow { /** * An interface that can be used to either attach the requested @@ -8431,15 +8589,14 @@ declare namespace chrome { /** The requested disposition of the new window. */ windowOpenDisposition: WindowOpenDisposition; } - enum RequestedPermission { - 'media', - 'geolocation', - 'pointerLock', - 'download', - 'loadplugin', - 'filesystem', - 'fullscreen' - } + type RequestedPermission = + 'media' | + 'geolocation' | + 'pointerLock' | + 'download' | + 'loadplugin' | + 'filesystem' | + 'fullscreen'; interface PermissionRequest { /** The type of permission being requested. */ permission: RequestedPermission; diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 7ee0b882e0..975a247542 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -394,7 +394,7 @@ chrome.bluetooth.getDevices((devices) => { if (chrome.runtime.lastError) { console.log("Connection failed: " + chrome.runtime.lastError.message); } else { - chrome.bluetoothSocket.send(createInfo.socketId, new ArrayBuffer(4096), function (bytes_sent) { + chrome.bluetoothSocket.send(createInfo.socketId, new ArrayBuffer(4096), (bytes_sent) => { if (chrome.runtime.lastError) { console.log("Send failed: " + chrome.runtime.lastError.message); } else { @@ -423,7 +423,7 @@ chrome.hid.getDevices({ }); chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { - if (policy === chrome.syncFileSystem.ConflictResolutionPolicy.manual) { + if (policy === 'manual') { chrome.syncFileSystem.requestFileSystem((fs) => { if (fs.root.isFile) { throw new Error('It was a file!'); @@ -434,3 +434,32 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { 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" + } + } +} From 90a0ac46153c51db542bff1871867a90f746fc8f Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 13:44:06 +0200 Subject: [PATCH 019/289] Restored enums that are present (after checking) --- types/chrome-apps/index.d.ts | 425 ++++++++++++++++++++------------ types/chrome-apps/test/index.ts | 131 +++++++--- 2 files changed, 356 insertions(+), 200 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 589361f54a..07a97dbec6 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,6 +1,6 @@ // 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 @@ -134,61 +134,61 @@ 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - 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. */ - var switchAccess: AccessibilityFeaturesSetting; + const switchAccess: AccessibilityFeaturesSetting; /** * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 42. */ - var animationPolicy: AccessibilityFeaturesSetting; + const animationPolicy: AccessibilityFeaturesSetting; } //////////// @@ -282,7 +282,7 @@ declare namespace chrome { function get(name: string, callback: (alarm: Alarm) => void): void; /** Fired when an alarm has elapsed. Useful for event pages. */ - var onAlarm: AlarmEvent; + const onAlarm: AlarmEvent; } ///////////////// @@ -296,11 +296,37 @@ declare namespace chrome { * 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 { /** @@ -319,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. @@ -382,18 +412,18 @@ declare namespace chrome { * 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. */ - var onEmbedRequest: EmbedRequestedEvent; + const onEmbedRequest: EmbedRequestedEvent; /** * Fired when an app is launched from the launcher. */ - var onLaunched: LaunchedEvent; + const onLaunched: LaunchedEvent; /** * 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. */ - var onRestarted: RestartedEvent; + const onRestarted: RestartedEvent; } //////////////////// @@ -503,7 +533,12 @@ declare namespace chrome { inactiveColor?: string; } - type WindowState = 'normal' | 'fullscreen' | 'maximized' | 'minimized'; + enum State { + NORMAL = 'normal', + FULLSCREEN = 'fullscreen', + MAXIMIZED = 'maximized', + MINIMIZED = 'minimized' + } interface CreateWindowOptions { /** @@ -582,7 +617,7 @@ declare namespace chrome { /** * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. */ - state?: WindowState; + 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. */ @@ -859,11 +894,11 @@ declare namespace chrome { */ function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; /** Fired when sound level changes for an active audio device. */ - 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. */ - var onMuteChanged: OnMuteChangedEvent; + const onMuteChanged: OnMuteChangedEvent; /** Fired when audio devices change, either new devices being added, or existing devices being removed. */ - var onDeviceListChanged: OnDeviceListChangedEvent; + const onDeviceListChanged: OnDeviceListChangedEvent; } /////////////// @@ -992,16 +1027,16 @@ declare namespace chrome { function stopDiscovery(callback: () => void): void; /** Fired when the state of the Bluetooth adapter changes. */ - var onAdapterStateChanged: BluetoothEvent; + const onAdapterStateChanged: BluetoothEvent; /** Fired when information about a new Bluetooth device is available. */ - var onDeviceAdded: BluetoothEvent; + const onDeviceAdded: BluetoothEvent; /** Fired when information about a known Bluetooth device has changed. */ - 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. */ - var onDeviceRemoved: BluetoothEvent; + const onDeviceRemoved: BluetoothEvent; } /** @@ -1289,7 +1324,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. @@ -1300,7 +1335,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. @@ -1349,7 +1384,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. @@ -1365,16 +1400,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. */ - 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, @@ -1382,14 +1417,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. @@ -1399,7 +1434,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. @@ -1409,7 +1444,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. @@ -1419,7 +1454,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. @@ -1428,7 +1463,7 @@ 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>; + const onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; } /** @@ -1734,7 +1769,7 @@ declare namespace chrome { * Event raised when a connection has been established * for a given socket. */ - var onAccept: OnAcceptEvent; + const onAccept: OnAcceptEvent; /** * Event raised when a network error occurred while the * runtime was waiting for new connections on the given @@ -1742,18 +1777,18 @@ declare namespace chrome { * to paused and no more onAccept events are raised for * this socket. */ - var onAcceptError: OnAcceptErrorEvent; + const onAcceptError: OnAcceptErrorEvent; /** * Event raised when data has been received for a given socket. */ - var onReceive: OnReceiveEvent; + 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. */ - var onReceiveError: OnReceiveErrorEvent; + const onReceiveError: OnReceiveErrorEvent; } ///////////// @@ -1823,7 +1858,7 @@ declare namespace chrome { function getAll(callback: (commands: Command[]) => void): void; /** Fired when a registered command is activated using a keyboard shortcut. */ - var onCommand: CommandEvent; + const onCommand: CommandEvent; } /////////////////// @@ -2091,7 +2126,7 @@ declare namespace chrome { function removeAll(callback?: () => void): void; /** Fired when a context menu item is clicked. */ - var onClicked: MenuClickedEvent; + const onClicked: MenuClickedEvent; } @@ -2132,8 +2167,6 @@ 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) {...}; */ function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; } @@ -2163,7 +2196,7 @@ declare namespace chrome { * @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 { /** * Matches if the host name of the URL contains a specified string. @@ -2256,9 +2289,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. @@ -2270,26 +2305,23 @@ 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; } @@ -2579,7 +2611,7 @@ declare namespace chrome { * Called when a list of available volumes is changed. * @since Chrome 44. */ - var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; + const onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; } @@ -3089,7 +3121,7 @@ declare namespace chrome { * 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. */ - var onUnmountRequested: chrome.events.Event<( + const onUnmountRequested: chrome.events.Event<( options: UnmountRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3100,7 +3132,7 @@ declare namespace chrome { * The metadata must be returned with the successCallback call. * In case of an error, errorCallback must be called. */ - var onGetMetadataRequested: chrome.events.Event<( + const onGetMetadataRequested: chrome.events.Event<( options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: ProviderError) => void @@ -3114,7 +3146,7 @@ declare namespace chrome { * In case of an error, errorCallback must be called. * @since Since Chrome 48. **/ - var onGetActionsRequested: chrome.events.Event<( + const onGetActionsRequested: chrome.events.Event<( options: GetActionsRequestedEventOptions, successCallback: (actions: Action[]) => void, errorCallback: (error: ProviderError) => void @@ -3125,7 +3157,7 @@ declare namespace chrome { * The results must be returned in chunks by calling the successCallback several times. * In case of an error, errorCallback must be called. */ - var onReadDirectoryRequested: chrome.events.Event<( + const onReadDirectoryRequested: chrome.events.Event<( options: ReadDirectoryRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: ProviderError) => void @@ -3136,7 +3168,7 @@ declare namespace chrome { * If the file does not exist, then the operation must fail. * Maximum number of files opened at once can be specified with MountOptions. */ - var onOpenFileRequested: chrome.events.Event<( + const onOpenFileRequested: chrome.events.Event<( options: OpenFileRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3146,7 +3178,7 @@ declare namespace chrome { * Raised when opening a file previously opened * with openRequestId is requested to be closed. */ - var onCloseFileRequested: chrome.events.Event<( + const onCloseFileRequested: chrome.events.Event<( options: CloseFileRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3157,7 +3189,7 @@ declare namespace chrome { * The results must be returned in chunks by calling successCallback several times. * In case of an error, errorCallback must be called. */ - var onReadFileRequested: chrome.events.Event<( + const onReadFileRequested: chrome.events.Event<( options: ReadFileRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: ProviderError) => void @@ -3168,7 +3200,7 @@ declare namespace chrome { * 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. */ - var onCreateDirectoryRequested: chrome.events.Event<( + const onCreateDirectoryRequested: chrome.events.Event<( options: CreateDirectoryRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3179,7 +3211,7 @@ declare namespace chrome { * If recursive is true, and the entry is a directory, * then all of the entries inside must be recursively deleted as well. */ - var onDeleteEntryRequested: chrome.events.Event<( + const onDeleteEntryRequested: chrome.events.Event<( options: DeleteEntryRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3189,7 +3221,7 @@ declare namespace chrome { * Raised when creating a file is requested. * If the file already exists, then errorCallback must be called with the 'EXISTS' error code. */ - var onCreateFileRequested: chrome.events.Event<( + const onCreateFileRequested: chrome.events.Event<( options: CreateFileRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3199,7 +3231,7 @@ declare namespace chrome { * Raised when copying an entry (recursively if a directory) is requested. * If an error occurs, then errorCallback must be called. */ - var onCopyEntryRequested: chrome.events.Event<( + const onCopyEntryRequested: chrome.events.Event<( options: CopyEntryRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3209,7 +3241,7 @@ declare namespace chrome { * Raised when moving an entry (recursively if a directory) is requested. * If an error occurs, then errorCallback must be called. */ - var onMoveEntryRequested: chrome.events.Event<( + const onMoveEntryRequested: chrome.events.Event<( options: MoveEntryRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3219,14 +3251,14 @@ declare namespace chrome { * Raised when truncating a file to a desired length is requested. * If an error occurs, then errorCallback must be called. */ - var onTruncateRequested: chrome.events.Event<( + const onTruncateRequested: chrome.events.Event<( options: TruncateRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void ) => void>; /** Raised when writing contents to a file opened previously with openRequestId is requested. */ - var onWriteFileRequested: chrome.events.Event<( + const onWriteFileRequested: chrome.events.Event<( options: WriteFileRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3240,7 +3272,7 @@ declare namespace chrome { * operation must not be called, as they will be ignored. Despite calling * errorCallback, the request may be forcibly aborted. */ - var onAbortRequested: chrome.events.Event<( + const onAbortRequested: chrome.events.Event<( options: AbortRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3251,7 +3283,7 @@ declare namespace chrome { * If it's handled, the file_system_provider.configurable manfiest option must be set to true. * @since Since Chrome 44. */ - var onConfigureRequested: chrome.events.Event<( + const onConfigureRequested: chrome.events.Event<( options: ConfigureRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3264,7 +3296,7 @@ declare namespace chrome { * For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. * @since Since Chrome 44. */ - var onMountRequested: chrome.events.Event<( + const onMountRequested: chrome.events.Event<( successCallback: () => void, errorCallback: (error: ProviderError) => void ) => void>; @@ -3274,7 +3306,7 @@ declare namespace chrome { * If an error occurs, then errorCallback must be called. * @since Since Chrome 45. */ - var onAddWatcherRequested: chrome.events.Event<( + const onAddWatcherRequested: chrome.events.Event<( options: WatcherRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3285,7 +3317,7 @@ declare namespace chrome { * If an error occurs, then errorCallback must be called. * @since Since Chrome 45. */ - var onRemoveWatcherRequested: chrome.events.Event<( + const onRemoveWatcherRequested: chrome.events.Event<( options: WatcherRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3297,7 +3329,7 @@ declare namespace chrome { * On error, errorCallback must be called. * @since Since Chrome 48. */ - var onExecuteActionRequested: chrome.events.Event<( + const onExecuteActionRequested: chrome.events.Event<( options: ExecuteActionRequestedEventOptions, successCallback: () => void, errorCallback: (error: ProviderError) => void @@ -3410,11 +3442,11 @@ declare namespace chrome { function send(message: OutgoingMessage, callback: (messageId: string) => void): void; /** Fired when a message is received through GCM. */ - var onMessage: chrome.events.Event<(message: IncomingMessage) => void>; + 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. */ - var onMessagesDeleted: chrome.events.Event<() => void>; + const onMessagesDeleted: chrome.events.Event<() => void>; /** Fired when it was not possible to send a message to the GCM server. */ - var onSendError: chrome.events.Event<(error: GcmError) => void>; + const onSendError: chrome.events.Event<(error: GcmError) => void>; } ///////// @@ -3612,7 +3644,7 @@ declare namespace chrome { * @since Chrome 41. * @see[permissions.request]{@link https://developer.chrome.com/apps/permissions#method-request} */ - var onDeviceAdded: chrome.events.Event<(device: HidDeviceInfo) => void>; + const onDeviceAdded: chrome.events.Event<(device: HidDeviceInfo) => void>; /** * Event generated when a device is removed from the system. @@ -3620,7 +3652,7 @@ declare namespace chrome { * @since Chrome 41. * @see[See onDeviceAdded for which events are delivered]{@link https://developer.chrome.com/apps/hid#event-onDeviceAdded}. */ - var onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; + const onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; } ///////////////////////////////// @@ -4039,7 +4071,7 @@ declare namespace chrome { * Fired when signin state changes for an account on the user's profile. * @since Chrome 33. */ - var onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; + const onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; } ////////// @@ -4156,7 +4188,7 @@ declare namespace chrome { */ function deleteID(callback: () => void): void; /** Fired when all the granted tokens need to be refreshed. */ - var onTokenRefresh: chrome.events.Event<() => void>; + const onTokenRefresh: chrome.events.Event<() => void>; } //////////////////// @@ -4207,7 +4239,7 @@ declare namespace chrome { * with the 'serviceType' key. Not specifying an event * filter will not start any discovery listeners. */ - var onServiceList: chrome.events.Event<(services: Service[]) => void>; + const onServiceList: chrome.events.Event<(services: Service[]) => void>; } @@ -4439,12 +4471,12 @@ declare namespace chrome { * Fired when a media gallery is changed or a gallery watch is dropped * @since Since Chrome 38. */ - var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; + 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. */ - var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; + const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } //////////////////////////////////// @@ -4865,21 +4897,21 @@ declare namespace chrome { interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> { } /** The notification closed, either by the system or by user action. */ - var onClosed: NotificationClosedEvent; + const onClosed: NotificationClosedEvent; /** The user clicked in a non-button area of the notification. */ - var onClicked: NotificationClickedEvent; + const onClicked: NotificationClickedEvent; /** The user pressed a button in the notification. */ - var onButtonClicked: NotificationButtonClickedEvent; + const onButtonClicked: NotificationButtonClickedEvent; /** * The user changes the permission level. * @since Chrome 32. */ - var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; + const onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; /** * The user clicked on a link for the app's notification settings. * @since Chrome 32. */ - var onShowSettings: NotificationShowSettingsEvent; + const onShowSettings: NotificationShowSettingsEvent; /** * Creates and displays a notification. @@ -5009,9 +5041,9 @@ declare namespace chrome { function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; /** Fired when access to permissions has been removed from the extension. */ - var onRemoved: PermissionsRemovedEvent; + const onRemoved: PermissionsRemovedEvent; /** Fired when the extension acquires new permissions. */ - var onAdded: PermissionsAddedEvent; + const onAdded: PermissionsAddedEvent; } //////////////////// @@ -5066,17 +5098,17 @@ declare namespace chrome { } /** Event fired when print manager requests printers provided by extensions. */ - var onGetPrintersRequested: chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void>; + 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. */ - var onGetUsbPrinterInfoRequested: chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void>; + const onGetUsbPrinterInfoRequested: chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void>; /** Event fired when print manager requests printer capabilities. */ - var onGetCapabilityRequested: chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void>; + const onGetCapabilityRequested: chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void>; /** Event fired when print manager requests printing. */ - var onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; + const onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; } //////////////////// @@ -5088,9 +5120,9 @@ declare namespace chrome { */ namespace runtime { /** This will be defined during an API method callback if there was an error */ - var lastError: LastError | undefined; + const lastError: LastError | undefined; /** The ID of the extension/app. */ - var id: string; + const id: string; interface LastError { /** Details about the error which occurred. */ @@ -5184,9 +5216,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; } @@ -5200,22 +5232,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; } @@ -5244,6 +5260,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: { @@ -5426,34 +5499,46 @@ declare namespace chrome { * @param application The name of the registered application to connect to. */ 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. */ - 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. + * 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. */ function getManifest(): Manifest; + /** * Returns a DirectoryEntry for the package directory. * @since Chrome 29. */ function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; + /** * Returns information about the current platform. * @since Chrome 29. * @param callback Called with results */ 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. */ function getURL(path: string): string; + /** * Reloads the app or extension. * @since Chrome 25. */ function reload(): void; + /** * Requests an update check for this app/extension. * @since Chrome 25. @@ -5462,11 +5547,13 @@ declare namespace chrome { * Optional parameter details: If an update is available, this contains more information about the available update. */ 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. */ 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. @@ -5474,6 +5561,7 @@ declare namespace chrome { * 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. */ 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. @@ -5481,6 +5569,7 @@ declare namespace chrome { * 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. */ 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. @@ -5489,6 +5578,7 @@ declare namespace chrome { * 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. */ 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. @@ -5497,6 +5587,7 @@ declare namespace chrome { * 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. */ function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + /** * Send a single message to a native application. * @since Chrome 28. @@ -5506,6 +5597,7 @@ declare namespace chrome { * 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. */ 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. @@ -5514,6 +5606,7 @@ declare namespace chrome { * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set. */ 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. @@ -5522,52 +5615,59 @@ declare namespace chrome { */ 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. */ - var onConnect: ExtensionConnectEvent; + const onConnect: ExtensionConnectEvent; /** * Fired when a connection is made from another extension. * @since Chrome 26. */ - 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. */ - 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. */ - 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. */ - 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. */ - var onSuspendCanceled: RuntimeEvent; + const onSuspendCanceled: RuntimeEvent; /** * Fired when a message is sent from either an extension process or a content script. * @since Chrome 26. */ - 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. */ - 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. */ - 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. */ - 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. */ - var onBrowserUpdateAvailable: RuntimeEvent; + const onBrowserUpdateAvailable: RuntimeEvent; } //////////////////// @@ -5701,8 +5801,8 @@ declare namespace chrome { function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; - var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; - var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } /** @@ -5892,7 +5992,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAccept */ - 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 @@ -5902,7 +6002,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError */ - var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; + const onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; } /** @@ -6186,7 +6286,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive */ - 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 @@ -6196,7 +6296,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError */ - var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } //////////////////// @@ -6296,18 +6396,18 @@ 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. */ - var local: LocalStorageArea; + const local: LocalStorageArea; /** Items in the sync storage area are synced using Chrome Sync. */ - 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. */ - var managed: StorageArea; + const managed: StorageArea; /** Fired when one or more items change. */ - var onChanged: StorageChangedEvent; + const onChanged: StorageChangedEvent; } //////////////////// @@ -6450,9 +6550,9 @@ declare namespace chrome { */ 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). */ - var onServiceStatusChanged: chrome.events.Event<(detail: { state: ServiceStatus, description: string }) => void>; + const onServiceStatusChanged: chrome.events.Event<(detail: { state: ServiceStatus, description: string }) => void>; /** Fired when a file has been updated by the background sync service. */ - var onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; + const onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } @@ -6836,7 +6936,7 @@ declare namespace chrome { * Fired when anything changes to the display configuration. * @export */ - var onDisplayChanged: DisplayChangedEvent; + const onDisplayChanged: DisplayChangedEvent; } //////////////////// @@ -6923,9 +7023,9 @@ declare namespace chrome { function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; /** Fired when a new removable storage is attached to the system. */ - var onAttached: SystemStorageAttachedEvent; + const onAttached: SystemStorageAttachedEvent; /** Fired when a removable storage is detached from the system. */ - var onDetached: SystemStorageDetachedEvent; + const onDetached: SystemStorageDetachedEvent; } //////////////////// @@ -7157,7 +7257,6 @@ declare namespace chrome { } type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; - type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback'; @@ -7233,8 +7332,8 @@ declare namespace chrome { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> { } - var onDeviceAdded: DeviceEvent; - var onDeviceRemoved: DeviceEvent; + const onDeviceAdded: DeviceEvent; + const onDeviceRemoved: DeviceEvent; 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; @@ -7333,15 +7432,15 @@ declare namespace chrome { function notifyConnectionStateChanged(state: string, callback?: Function): void; /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - var onPlatformMessage: VpnPlatformMessageEvent; + const onPlatformMessage: VpnPlatformMessageEvent; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - var onPacketReceived: VpnPacketReceptionEvent; + const onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ - var onConfigRemoved: VpnConfigRemovalEvent; + const onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ - 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. */ - var onUIEvent: VpnUiEvent; + const onUIEvent: VpnUiEvent; } /////////////// @@ -7578,7 +7677,7 @@ 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); * }); @@ -7962,7 +8061,7 @@ declare namespace chrome { * 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); * }); @@ -8398,7 +8497,7 @@ declare namespace chrome { * 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]); + * @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 */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 975a247542..bd9245e2bd 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -2,7 +2,7 @@ import runtime = chrome.app.runtime; import cwindow = chrome.app.window; const createOptions: cwindow.CreateWindowOptions = { - id: "My Window", + id: 'My Window', bounds: { left: 0, top: 0, @@ -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; } }); @@ -361,7 +361,7 @@ wve.addEventListener('loadredirect', (ev) => { }); chrome.bluetooth.getAdapterState((adapter) => { - console.log("Adapter " + adapter.address + ": " + adapter.name); + console.log('Adapter ' + adapter.address + ': ' + adapter.name); }); chrome.bluetooth.getDevices((devices) => { @@ -392,13 +392,13 @@ chrome.bluetooth.getDevices((devices) => { chrome.bluetoothSocket.connect(createInfo.socketId, devices[0].address, uuid, () => { if (chrome.runtime.lastError) { - console.log("Connection failed: " + chrome.runtime.lastError.message); + 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); + console.log('Send failed: ' + chrome.runtime.lastError.message); } else { - console.log("Sent " + bytes_sent + " bytes") + console.log('Sent ' + bytes_sent + ' bytes') } }); } @@ -438,28 +438,85 @@ chrome.i18n.getMessage('click_here', ['string1', 'string2']); const TLSFormatExample = { NetworkConfigurations: { - GUID: "{00f79111-51e0-e6e0-76b3b55450d80a1b}", - Name: "MyTTLSNetwork", + GUID: '{00f79111-51e0-e6e0-76b3b55450d80a1b}', + Name: 'MyTTLSNetwork', Type: 'WiFi', WiFi: { AutoConnect: false, EAP: { ClientCertPattern: { EnrollmentURI: [ - "http://fetch-my-certificate.com" + 'http://fetch-my-certificate.com' ], IssuerCARef: [ - "{6ed8dce9-64c8-d568-d225d7e467e37828}" + '{6ed8dce9-64c8-d568-d225d7e467e37828}' ] }, - "ClientCertType": "Pattern", - "Outer": "EAP-TLS", - "ServerCARef": "{6ed8dce9-64c8-d568-d225d7e467e37828}", - "UseSystemCAs": true + 'ClientCertType': 'Pattern', + 'Outer': 'EAP-TLS', + 'ServerCARef': '{6ed8dce9-64c8-d568-d225d7e467e37828}', + 'UseSystemCAs': true }, - "HiddenSSID": false, - "SSID": "MyTTLSNetwork", - "Security": "WPA-EAP" + '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); + } + } +}); + +//// 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); + } +}); From 87bec2e81bd62f918425932945555cc286aa0b18 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 15:01:45 +0200 Subject: [PATCH 020/289] Implemented desktopCapture --- types/chrome-apps/index.d.ts | 126 ++++++++++++++++++++++---------- types/chrome-apps/test/index.ts | 18 +++-- types/chrome-apps/tsconfig.json | 3 +- 3 files changed, 100 insertions(+), 47 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 07a97dbec6..29fe5494f5 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2,9 +2,10 @@ // Project: http://developer.chrome.com/apps/ // 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.6 /// +/// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WebView ref // @@ -402,28 +403,22 @@ 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. */ - const onEmbedRequest: EmbedRequestedEvent; + const onEmbedRequest: chrome.events.Event<(request: EmbedRequest) => void>; /** * Fired when an app is launched from the launcher. */ - const 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. */ - const onRestarted: RestartedEvent; + const onRestarted: chrome.events.Event<() => void>; } //////////////////// @@ -437,7 +432,7 @@ declare namespace chrome { * They are not associated with any Chrome browser windows. * See the Window State Sample for a demonstration of these options. */ - namespace app.window { + namespace app { interface ContentBounds { left?: number; top?: number; @@ -650,7 +645,6 @@ declare namespace chrome { */ visibleOnAllWorkspaces?: boolean; } - interface AppWindow { /** Focus the window. */ focus: () => void; @@ -748,34 +742,53 @@ 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) {...}; - */ - 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(). - */ - 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. - */ - function get(id: string): AppWindow; - /** - * Gets an array of all currently created app windows. This method is new in Chrome 33. - */ - function getAll(): AppWindow[]; - /** - * Whether the current platform supports windows being visible on all workspaces. - */ - 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 @@ -2131,8 +2144,41 @@ declare namespace chrome { } //////////////////// - // Document Scan + // DesktopCapture // //////////////////// + /** + * 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. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index bd9245e2bd..1449b0414c 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,7 +1,8 @@ +/// import runtime = chrome.app.runtime; -import cwindow = chrome.app.window; +let cwindow = chrome.app.window; -const createOptions: cwindow.CreateWindowOptions = { +const createOptions: chrome.app.CreateWindowOptions = { id: 'My Window', bounds: { left: 0, @@ -14,7 +15,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 +23,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; }); @@ -520,3 +521,8 @@ chrome.audio.getDevices({}, (audioDeviceInfoList) => { console.log('Audio Device Name: ' + audioObj.deviceName); } }); + + +chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); +chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); + diff --git a/types/chrome-apps/tsconfig.json b/types/chrome-apps/tsconfig.json index 50a50c3193..36945d52ea 100644 --- a/types/chrome-apps/tsconfig.json +++ b/types/chrome-apps/tsconfig.json @@ -15,7 +15,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "preserveConstEnums": true }, "files": [ "index.d.ts", From 232d3f8c768111d51e5b876b3a3fcf67c0d2e34e Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 15:15:31 +0200 Subject: [PATCH 021/289] Added management --- types/chrome-apps/index.d.ts | 283 ++++++++++++++++++++++++++++++++++- 1 file changed, 278 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 29fe5494f5..1a23aa684c 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -251,20 +251,20 @@ declare namespace chrome { 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) {...}; */ 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) {...}; */ 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) {...}; */ function clear(callback: (wasCleared: boolean) => void): void; @@ -4237,6 +4237,255 @@ declare namespace chrome { 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: 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. + * @since Chrome 9. + * @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. + * @since Chrome 15. + * @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 //////////////////// @@ -5073,14 +5322,14 @@ declare namespace chrome { 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. */ 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. */ @@ -8773,6 +9022,30 @@ declare namespace chrome { 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; } ///////////////////// From 6374ecdeea617413465af8c20c66072246f2fd56 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 15:40:51 +0200 Subject: [PATCH 022/289] Typings for experimental clipboard api --- types/chrome-apps/index.d.ts | 57 ++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 1a23aa684c..e589e8abcb 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1839,6 +1839,54 @@ declare namespace chrome { function openTab(options: Options): void; } + /////////////// + // Clipboard // + /////////////// + /** + * @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 // ////////////// @@ -4314,7 +4362,7 @@ declare namespace chrome { * The type of this extension, app, or theme. * @since Chrome 23. */ - type: string; + 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. */ @@ -4384,7 +4432,6 @@ declare namespace chrome { function getPermissionWarningsById(id: string, callback?: (permissionWarnings: string[]) => void): void; /** * Returns information about the installed extension, app, or theme that has the given ID. - * @since Chrome 9. * @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) {...}; @@ -4397,13 +4444,13 @@ declare namespace chrome { */ 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. - * @since Chrome 15. + * 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; + function getPermissionWarningsByManifest(manifestStr: string, callback?: (permissionWarnings: string[]) => void): void; /** * Launches an application. * @param id The extension id of the application. From 5b29771af9334492e4028b34fd777f0f96854227 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 16:44:43 +0200 Subject: [PATCH 023/289] chrome.networking.onc: Documentation + fixes --- types/chrome-apps/index.d.ts | 371 ++++++++++++++++++++++++++++++-- types/chrome-apps/test/index.ts | 9 + 2 files changed, 358 insertions(+), 22 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index e589e8abcb..84e0255a6b 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -4845,26 +4845,38 @@ declare namespace chrome { 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'> { + 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; - WiFi?: IF extends 'partial' ? WiFiPropertiesBase : WiFiProperties; + /** 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; } } @@ -4901,20 +4913,47 @@ declare namespace chrome { 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'; @@ -4927,6 +4966,7 @@ declare namespace chrome { 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; @@ -4938,10 +4978,15 @@ declare namespace chrome { 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'; @@ -4950,203 +4995,476 @@ declare namespace chrome { S = M extends 'managed' ? ManagedDOMString : string, SL = M extends 'managed' ? ManagedDOMStringList : string[], L = M extends 'managed' ? ManagedLong : integer> { + /** 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 PaymentPortal { - Method: string; + 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 { - LockType: string; + /** 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; - Family?: 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; - PaymentPortal?: PaymentPortal; + /** 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 { + 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 { + L = M extends 'managed' ? ManagedLong : integer> + 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; - /** @since Chrome 66. */ - Passphrase?: string; + /** 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'> { } + + interface NetworkConfigProperties + extends _internal_.NetworkConfigBase<'unmanaged', 'full', OF> { } + interface NetworkProperties< M extends ManagedObject = 'unmanaged', - IF extends InterfaceType = 'full'> extends _internal_.NetworkConfigBase { + 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<'unmanaged'>; + /** + * 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<'unmanaged'>; + /** + * 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; - /** @default false */ + /** + * If true, only include visible (physically connected or in-range) networks. + * @default false + */ visible?: boolean; - /** @default false */ + /** + * If true, only include configured (saved) networks. + * @default false + */ configured?: boolean; /** + * Maximum number of networks to return. * Use 0 for no limit - * @default 1000 + * @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; - function setProperties(networkGuid: string, properties: NetworkConfigProperties, callback?: () => void): void; - function createNetwork(shared: boolean, properties: NetworkConfigProperties, callback?: () => 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; - function getDeviceStates(callback?: (result: DeviceStates[]) => 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>; } @@ -5783,6 +6101,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?: { @@ -5797,7 +6124,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[]; diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 1449b0414c..8ca8374017 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -509,6 +509,15 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { // 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; + }); } }); From d0c413c2ecb6b8edca79a93c3454c555f290ef24 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 16:53:09 +0200 Subject: [PATCH 024/289] Removed unnecessary imports and compiler options. --- types/chrome-apps/index.d.ts | 1 - types/chrome-apps/test/index.ts | 3 +-- types/chrome-apps/tsconfig.json | 3 +-- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 84e0255a6b..b4428016cd 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5,7 +5,6 @@ // TypeScript Version: 2.6 /// -/// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WebView ref // diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 8ca8374017..3babb0b80e 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,6 +1,5 @@ -/// import runtime = chrome.app.runtime; -let cwindow = chrome.app.window; +const cwindow = chrome.app.window; const createOptions: chrome.app.CreateWindowOptions = { id: 'My Window', diff --git a/types/chrome-apps/tsconfig.json b/types/chrome-apps/tsconfig.json index 36945d52ea..50a50c3193 100644 --- a/types/chrome-apps/tsconfig.json +++ b/types/chrome-apps/tsconfig.json @@ -15,8 +15,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "preserveConstEnums": true + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", From 4c8b1f9c081ca3b56efa49780ba839bbed248321 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 17:01:12 +0200 Subject: [PATCH 025/289] Bumped typescript version to support new language features. --- types/chrome-apps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index b4428016cd..bbca4fddcf 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2,7 +2,7 @@ // Project: http://developer.chrome.com/apps/ // 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.6 +// TypeScript Version: 2.8 /// From 18cba3eedd612ee2b53c488928f6fa35c38193d8 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 3 Aug 2018 17:06:25 +0200 Subject: [PATCH 026/289] Cleanup: No need to specify defaults --- types/chrome-apps/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index bbca4fddcf..07437c787a 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5044,7 +5044,7 @@ declare namespace chrome { /** Settings for SOCKS proxy. */ SOCKS?: P; } - interface ProxySettings { /** The type of proxy settings. */ @@ -5229,7 +5229,7 @@ declare namespace chrome { /** The network's MAC address. */ MacAddress?: string; /** The network's proxy settings. */ - ProxySettings?: ProxySettings<'unmanaged'>; + 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. @@ -5238,7 +5238,7 @@ declare namespace chrome { /** The network's static IP configuration. */ StaticIPConfig?: IPConfigProperties; /** IP configuration that was received from the DHCP server before applying static IP configuration. */ - SavedIPConfig?: IPConfigProperties<'unmanaged'>; + SavedIPConfig?: IPConfigProperties; /** * Indicates whether and how the network is configured. * 'None' conflicts with extension code generation, From 07ccbe42b105c4e8f6d6e3a2432ffc3b4f460f9d Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 09:38:24 +0200 Subject: [PATCH 027/289] Deprecation cleanup + better tests --- types/chrome-apps/index.d.ts | 83 +++------- types/chrome-apps/test/index.ts | 280 ++++++++++++++++++++++++-------- 2 files changed, 231 insertions(+), 132 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 07437c787a..d1e8f98e54 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -922,6 +922,7 @@ declare namespace chrome { * @description * Use the chrome.bluetooth API to connect to a Bluetooth device. * All functions report failures via chrome.runtime.lastError. + * **Important: This API works only on OS X, Windows and Chrome OS.** */ namespace bluetooth { interface AdapterState { @@ -6338,9 +6339,9 @@ declare namespace chrome { const onBrowserUpdateAvailable: RuntimeEvent; } - //////////////////// - // Serial - //////////////////// + //////////// + // Serial // + //////////// /** * Use the chrome.socket API to send and receive data over the network using TCP and UDP connections. * @deprecated Note: Starting with Chrome 33, @@ -6350,66 +6351,24 @@ declare namespace chrome { */ const serial: chrome.deprecated; - //////////////////// - // Socket - //////////////////// - namespace socket { - interface CreateInfo { - socketId: number; - } - - interface AcceptInfo { - resultCode: number; - socketId?: number; - } - - interface ReadInfo { - resultCode: number; - data: ArrayBuffer; - } - - interface WriteInfo { - bytesWritten: number; - } - - interface RecvFromInfo { - resultCode: number; - data: ArrayBuffer; - port: number; - address: string; - } - - interface SocketInfo { - socketType: string; - localPort?: number; - peerAddress?: string; - peerPort?: number; - localAddress?: string; - connected: boolean; - } - - interface NetworkInterface { - name: string; - address: string; - } - - 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; - } + //////////// + // Socket // + //////////// + /* + * @deprecated Since Chrome 33 + * @description + * Use the chrome.socket API to send and receive data over the network using TCP and UDP connections. + * Note: Starting with Chrome 33, this API is deprecated in favor of the sockets.udp, sockets.tcp + * and sockets.tcpServer APIs. + */ + // const socket: chrome.deprecated; // Removed to not be confused with chrome.sockets.* + /** + * Use the chrome.sockets.tcp API to send and receive data over the network using TCP connections. + * This API supersedes the TCP functionality previously found in the chrome.socket API. + * @since Chrome 33. + * @requires Manifest: "Sockets": {...} + */ namespace sockets.tcp { interface CreateInfo { socketId: number; diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 3babb0b80e..f746962b91 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -13,13 +13,13 @@ const createOptions: chrome.app.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: chrome.app.AppWindow) { +chrome.app.runtime.onLaunched.addListener((launchData: runtime.LaunchData) => { + chrome.app.window.create('app/url', createOptions, (created_window: chrome.app.AppWindow) => { return; }); }); -chrome.app.runtime.onRestarted.addListener(function () { return; }); +chrome.app.runtime.onRestarted.addListener(() => { return; }); // retrieving windows var currentWindow: chrome.app.AppWindow = chrome.app.window.current(); @@ -27,12 +27,12 @@ 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; }); -currentWindow.onClosed.addListener(function () { return; }); -currentWindow.onFullscreened.addListener(function () { return; }); -currentWindow.onMaximized.addListener(function () { return; }); -currentWindow.onMinimized.addListener(function () { return; }); -currentWindow.onRestored.addListener(function () { return; }); +currentWindow.onBoundsChanged.addListener(() => { return; }); +currentWindow.onClosed.addListener(() => { return; }); +currentWindow.onFullscreened.addListener(() => { return; }); +currentWindow.onMaximized.addListener(() => { return; }); +currentWindow.onMinimized.addListener(() => { return; }); +currentWindow.onRestored.addListener(() => { return; }); // check platform capabilities var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(); @@ -360,67 +360,6 @@ wve.addEventListener('loadredirect', (ev) => { return ev.newUrl || ev.oldUrl; }); -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') { @@ -530,7 +469,208 @@ chrome.audio.getDevices({}, (audioDeviceInfoList) => { } }); +chrome.app.runtime.onEmbedRequested.addListener((request) => { + if (!request.data.message) { + request.allow('default.html'); + } else if (request.data.message == 'camera') { + request.allow('camera.html'); + } else { + request.deny(); + } +}); + +chrome.app.runtime.onLaunched.addListener(() => { + chrome.app.window.create('index.html', { + id: "test", + innerBounds: { + width: 900, + height: 1280 + } + } +}); + + + +const ManifestJSONTest1: chrome.runtime.Manifest = { + "manifest_version": 2, + "name": "Sample Appview Embedded", + "description": "This sample shows how to allow your app to be embedded into another app", + "version": "2", + "minimum_chrome_version": "43", + "permissions": ["videoCapture"], + "app": { + "background": { + "scripts": ["main.js"] + } + } +} + +// BLUETOOTH +// BLUETOOTH SOCKET +// BLUETOOTH LE +// Based on https://github.com/GoogleChrome/chrome-app-samples/blob/master/samples/ioio/main.js + +var kUUID = '00001101-0000-1000-8000-00805f9b34fb'; +var level = 1; +var pin = 0; +var buffer = new ArrayBuffer(4); +var view = new Uint8Array(buffer); + +// Set the level of pin0 to level +// constants taken from here: +// https://github.com/ytai/ioio/wiki/ +view[2] = 4; +view[3] = pin << 2 | level; +level = (level == 0) ? 1 : 0; + +var connectToDevice = (result: chrome.bluetooth.Device[]) => { + if (chrome.runtime.lastError) { + console.log('Error searching for a device to connect to.'); + return; + } + if (result.length == 0) { + console.log('No devices found to connect to.'); + return; + } + for (const device of result) { + console.log('Connecting to device: ' + device.name + ' @ ' + device.address); + chrome.bluetoothSocket.create((socket) => { + chrome.bluetoothSocket.connect( + socket.socketId, + device.address, kUUID, + () => connectCallback(socket) + }); + } +}; + +var connectCallback = (socket: chrome.sockets.CreateInfo) => { + if (socket) { + console.log('Connected! Socket ID is: ' + socket.socketId + ' on service '); + // Set pin0 as output. + var buffer = new ArrayBuffer(2); + var view = new Uint8Array(buffer); + // constants taken from here: + // https://github.com/ytai/ioio/wiki/ + view[0] = 3; + view[1] = pin << 2 | 2; + chrome.bluetoothSocket.send(socket.socketId, buffer, + (bytes) => { + if (chrome.runtime.lastError) { + console.log('Write error: ' + chrome.runtime.lastError.message); + } else { + console.log('wrote ' + bytes + ' bytes'); + } + }); + } else { + console.log('Failed to connect.'); + } +}; + + +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. + }); + }); +}); + +// CONTEXT MENU + +chrome.contextMenus.onClicked.addListener((info) => { + const isChecked = info.checked; + if (!document.hasFocus() && isChecked) { + return; + } +}); + + +// DESKTOP CAPTURE + chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); + +// HID + +chrome.hid.getDevices({}, () => { }); +chrome.hid.onDeviceAdded.addListener(() => { }); +chrome.hid.onDeviceRemoved.addListener(() => { }); + +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.hid.connect(devices[0].deviceId, (connectInfo) => { + if (!connectInfo) { + console.warn("Unable to connect to device."); + } + const connection = connectInfo.connectionId; + }); + chrome.hid.getUserSelectedDevices({ 'multiple': false }, + (devices) => { + if (chrome.runtime.lastError != undefined) { + console.warn('chrome.hid.getUserSelectedDevices error: ' + + chrome.runtime.lastError.message); + return; + } + }); +}); + +// IDENTITY + +chrome.identity.getAuthToken({ interactive: true }, (token) => { + if (chrome.runtime.lastError) { + return; + } + chrome.identity.removeCachedAuthToken({ token: token }, () => { }); +}); From a0f3afcb5b18aa11889d5253bfde187909d9bb2b Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 10:00:43 +0200 Subject: [PATCH 028/289] chrome.sockets.tcp: Docs added --- types/chrome-apps/index.d.ts | 269 +++++++++++++++++++++++++++-------- 1 file changed, 210 insertions(+), 59 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index d1e8f98e54..56512d26bc 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -6371,64 +6371,215 @@ declare namespace chrome { */ namespace sockets.tcp { interface CreateInfo { - socketId: number; + /** + * 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 deprecated socket API. + */ + socketId: integer; } interface SendInfo { + /** The result code returned from the underlying network call. A negative value indicates an error. */ resultCode: number; + /** The number of bytes sent (if result == 0) */ bytesSent?: number; } interface ReceiveEventArgs { - socketId: number; + /** The socket identifier. */ + socketId: integer; + /** The data received, with a maxium size of *bufferSize*. */ data: ArrayBuffer; } interface ReceiveErrorEventArgs { - socketId: number; + /** The socket identifier. */ + socketId: integer; + /** The result code returned from the underlying network call. */ resultCode: number; } interface SocketProperties { + /** + * Flag indicating if the socket is left open when the event page of the + * application is unloaded. When the application is loaded, any sockets + * previously opened with persistent=true can be fetched with *getSockets*. + * @default false + */ persistent?: boolean; + /** An application-defined string associated with the socket. */ name?: string; - bufferSize?: number; + /** + * The size of the buffer used to receive data. + * @default: 4096 + */ + bufferSize?: integer; } interface SocketInfo { - socketId: number; + /** The socket identifier. */ + socketId: integer; + /** Flag indicating whether the socket is left open when the application is suspended (see SocketProperties.persistent). */ persistent: boolean; + /** Application-defined string associated with the socket. */ name?: string; - bufferSize?: number; + /** 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 (see setPaused). */ paused: boolean; + /** Flag indicating whether the socket is connected to a remote peer. */ connected: boolean; + /** If the underlying socket is connected, contains its local IPv4/6 address. */ localAddress?: string; - localPort?: number; + /** If the underlying socket is connected, contains its local port. */ + localPort?: integer; + /** If the underlying socket is connected, contains the peer/ IPv4/6 address. */ peerAddress?: string; - peerPort?: number; + /** If the underlying socket is connected, contains the peer port. */ + peerPort?: integer; } - + interface SecureOptions { + /** + * The minimum and maximum acceptable versions of TLS. + * These will be tls1, tls1.1, or tls1.2. + * *Note* + * tls1.3 should be supported from Chrome 67. + * @see[TLS Info and support table]{@link https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_1.3} + */ + tlsVersion?: { + min?: 'tls1' | 'tls1.1' | 'tls1.2' | 'tls1.3', + max?: 'tls1' | 'tls1.1' | 'tls1.2' | 'tls1.3', + }, + } + /** Creates a TCP socket. */ function create(callback: (createInfo: CreateInfo) => void): void; + /** + * Creates a TCP socket. + * @param properties The socket properties (optional). + */ function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; - function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + /** Updates the socket properties. */ + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; - function setKeepAlive(socketId: number, - enable: boolean, callback: (result: number) => void): void; - function setKeepAlive(socketId: number, - enable: boolean, delay: number, callback: (result: number) => void): void; + /** + * Enables or disables the application from receiving messages from its peer. + * The default value is "false". Pausing a socket is typically used by an + * application to throttle data sent by its peer. When a socket is paused, + * no onReceive event is raised. When a socket is connected and un-paused, + * onReceive events are raised again when messages are received. + */ + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; - function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; - function connect(socketId: number, - peerAddress: string, peerPort: number, callback: (result: number) => 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; + /** + * @description Enables or disables the keep-alive functionality for a TCP connection. + * @param socketId The socket identifier. + * @param enable If true, enable keep-alive functionality. + * @param callback Provides the result code returned from the underlying network call. A negative value indicates an error. + */ + function setKeepAlive(socketId: integer, + enable: boolean, callback: (result: integer) => void): void; + /** + * @description Enables or disables the keep-alive functionality for a TCP connection. + * @param socketId The socket identifier. + * @param enable If true, enable keep-alive functionality. + * @param [delay] Set the delay seconds between the last data packet received and the first keepalive probe. Default is 0. + * @param callback Provides the result code returned from the underlying network call. A negative value indicates an error. + */ + function setKeepAlive(socketId: integer, + enable: boolean, delay: integer, callback: (result: integer) => void): void; + + /** + * Sets or clears TCP_NODELAY for a TCP connection. + * Nagle's algorithm will be disabled when TCP_NODELAY is set. + * @param socketId The socket identifier. + * @param noDelay If true, disables Nagle's algorithm. + * @param callback Called when the setNoDelay attempt is complete. Provides the result code returned + * from the underlying network call. A negative value indicates an error. + */ + function setNoDelay(socketId: integer, noDelay: boolean, callback: (result: integer) => void): void; + + /** + * Connects the socket to a remote machine. + * When the connect operation completes successfully, + * onReceive events are raised when data is received from the peer. + * If a network error occurs 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 resume method is called. + * @param socketId The socket identifier. + * @param peerAddress The address of the remote machine. DNS name, IPv4 and IPv6 formats are supported. + * @param peerPort The port of the remote machine. + * @param callback Called when the connect attempt is complete. + * The result code returned from the underlying network call. + * A negative value indicates an error. + */ + function connect(socketId: integer, + peerAddress: string, peerPort: integer, callback: (result: integer) => void): void; + + /** + * @description Disconnects the socket. + * @param socketId The socket identifier. + * @param [callback] Called when the disconnect attempt is complete. + */ + function disconnect(socketId: integer, callback?: () => void): void; + + /** + * Start a TLS client connection over the connected TCP client socket. + * @since Chrome 38. + * @param socketId The existing, connected socket to use. + * @param callback Called when the connection attempt is complete. + */ + function secure(socketId: integer, callback: (result: integer) => void): void; + /** + * Start a TLS client connection over the connected TCP client socket. + * @since Chrome 38. + * @param socketId The existing, connected socket to use. + * @param [options] Constraints and parameters for the TLS connection. + * @param callback Called when the connection attempt is complete. + */ + function secure(socketId: integer, options: SecureOptions, callback: (result: integer) => void): void; + + /** + * @description Sends data on the given TCP socket. + * @param socketId The socket identifier. + * @param data The data to send. + * @param callback Called when the send operation completes. + */ + function send(socketId: integer, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + + /** + * Closes the socket and releases the address/port the socket is bound to. + * 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; + + /** + * Retrieves the state of the given socket. + * @param socketId The socket identifier. + * @param callback Called when the socket state is available. Provides an object containing the socket information. + */ + function getInfo(socketId: integer, callback: (socketInfo: SocketInfo) => void): void; + + /** + * @description Retrieves the list of currently opened sockets owned by the application. + * @param callback Called when the list of sockets is available. Provides an array of socket info. + */ function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + /** Event raised when data has been received for a given socket. */ const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + /** + * Event raised when a network error occured while the runtime was + * waiting for data on the socket address and port. Once this event + * is raised, the socket is set to paused and no more onReceive + * events are raised for this socket. + */ const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } @@ -6442,17 +6593,17 @@ declare namespace chrome { */ namespace sockets.tcpServer { interface CreateInfo { - socketId: number; + socketId: integer; } interface AcceptEventArgs { - socketId: number; - clientSocketId: number; + socketId: integer; + clientSocketId: integer; } interface AcceptErrorEventArgs { - socketId: number; - resultCode: number; + socketId: integer; + resultCode: integer; } /** @@ -6478,7 +6629,7 @@ declare namespace chrome { */ interface SocketInfo { /** The socket identifier. */ - socketId: number; + socketId: integer; /** * Flag indicating if the socket remains open when the event page of the @@ -6501,7 +6652,7 @@ declare namespace chrome { localAddress?: string; /** If the socket is listening, contains its local port. */ - localPort?: number; + localPort?: integer; } /** @@ -6529,7 +6680,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; /** * Enables or disables a listening socket from accepting new connections. @@ -6540,7 +6691,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused * @param callback Callback from the setPaused method. */ - function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; /** * Listens for connections on the specified port and address. If the @@ -6557,7 +6708,7 @@ declare namespace chrome { * ensures a reasonable queue length for most applications. * @param callback Called when listen operation completes. */ - function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; + function listen(socketId: integer, address: string, port: integer, backlog: integer, callback: (result: integer) => void): void; /** * Listens for connections on the specified port and address. If the @@ -6571,7 +6722,7 @@ declare namespace chrome { * be found by calling getInfo. * @param callback Called when listen operation completes. */ - function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function listen(socketId: integer, address: string, port: integer, callback: (result: integer) => void): void; /** * Disconnects the listening socket, i.e. stops accepting new connections @@ -6583,7 +6734,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the disconnect attempt is complete. */ - function disconnect(socketId: number, callback?: () => void): void; + function disconnect(socketId: integer, callback?: () => void): void; /** * Disconnects and destroys the socket. Each socket created should be closed @@ -6595,7 +6746,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the close operation completes. */ - function close(socketId: number, callback?: () => void): void; + function close(socketId: integer, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -6604,7 +6755,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the socket state is available. */ - function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: integer, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -6642,24 +6793,24 @@ declare namespace chrome { */ namespace sockets.udp { interface CreateInfo { - socketId: number; + socketId: integer; } interface SendInfo { - resultCode: number; - bytesSent?: number; + resultCode: integer; + bytesSent?: integer; } interface ReceiveEventArgs { - socketId: number; + socketId: integer; data: ArrayBuffer; remoteAddress: string; - remotePort: number; + remotePort: integer; } interface ReceiveErrorEventArgs { - socketId: number; - resultCode: number; + socketId: integer; + resultCode: integer; } /** @@ -6683,7 +6834,7 @@ declare namespace chrome { * small to receive the UDP packet, data is lost. The default value is * 4096. */ - bufferSize?: number; + bufferSize?: integer; } /** @@ -6691,7 +6842,7 @@ declare namespace chrome { */ interface SocketInfo { /** The socket identifier. */ - socketId: number; + socketId: integer; /** * Flag indicating whether the socket is left open when the application @@ -6706,7 +6857,7 @@ declare namespace chrome { * The size of the buffer used to receive data. If no buffer size ha * been specified explictly, the value is not provided. */ - bufferSize?: number; + bufferSize?: integer; /** * Flag indicating whether the socket is blocked from firing onReceive @@ -6722,7 +6873,7 @@ declare namespace chrome { /** * If the underlying socket is bound, contains its local port. */ - localPort?: number; + localPort?: integer; } /** @@ -6750,7 +6901,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; /** * Pauses or unpauses a socket. A paused socket is blocked from firing @@ -6762,7 +6913,7 @@ declare namespace chrome { * @param callback Called when the socket has been successfully paused or * unpaused. */ - function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; /** * Binds the local address and port for the socket. For a client socket, it @@ -6781,7 +6932,7 @@ declare namespace chrome { * port. * @param callback Called when the bind operation completes. */ - function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function bind(socketId: integer, address: string, port: integer, callback: (result: integer) => void): void; /** * Sends data on the given socket to the given address and port. The socket @@ -6794,7 +6945,7 @@ declare namespace chrome { * @param port The port of the remote machine. * @param callback Called when the send operation completes. */ - function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + function send(socketId: integer, data: ArrayBuffer, address: string, port: integer, callback: (sendInfo: SendInfo) => void): void; /** * Closes the socket and releases the address/port the socket is bound to. @@ -6806,7 +6957,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the close operation completes. */ - function close(socketId: number, callback?: () => void): void; + function close(socketId: integer, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -6815,7 +6966,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the socket state is available. */ - function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: integer, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -6834,7 +6985,7 @@ declare namespace chrome { * @param address The group address to join. Domain names are not supported. * @param callback Called when the joinGroup operation completes. */ - function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + function joinGroup(socketId: integer, address: string, callback: (result: integer) => void): void; /** * Leaves the multicast group previously joined using joinGroup. This is @@ -6851,7 +7002,7 @@ declare namespace chrome { * supported. * @param callback Called when the leaveGroup operation completes. */ - function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + function leaveGroup(socketId: integer, address: string, callback: (result: integer) => void): void; /** * Sets the time-to-live of multicast packets sent to the multicast group. @@ -6863,7 +7014,7 @@ declare namespace chrome { * @param ttl The time-to-live value. * @param callback Called when the configuration operation completes. */ - function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + function setMulticastTimeToLive(socketId: integer, ttl: integer, callback: (result: integer) => void): void; /** * Sets whether multicast packets sent from the host to the multicast group @@ -6886,7 +7037,7 @@ declare namespace chrome { * @param enabled Indicate whether to enable loopback mode. * @param callback Called when the configuration operation completes. */ - function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + function setMulticastLoopbackMode(socketId: integer, enabled: boolean, callback: (result: integer) => void): void; /** * Gets the multicast group addresses the socket is currently joined to. @@ -6895,7 +7046,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called with an array of strings of the result. */ - function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + function getJoinedGroups(socketId: integer, callback: (groups: string[]) => void): void; /** * Enables or disables broadcast packets on this socket. @@ -6906,7 +7057,7 @@ declare namespace chrome { * @param enabled true to enable broadcast packets, false to disable them. * @param callback Callback from the setBroadcast method. */ - function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; + function setBroadcast(socketId: integer, enabled: boolean, callback?: (result: integer) => void): void; /** * Event raised when a UDP packet has been received for the given socket. From b4ea6002720aedaec0a51931696301004e6e5623 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 10:16:26 +0200 Subject: [PATCH 029/289] Better docs and merged chrome.sockets interfaces --- types/chrome-apps/index.d.ts | 127 +++++------------------------------ 1 file changed, 16 insertions(+), 111 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 56512d26bc..d34b619b94 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -6363,13 +6363,8 @@ declare namespace chrome { */ // const socket: chrome.deprecated; // Removed to not be confused with chrome.sockets.* - /** - * Use the chrome.sockets.tcp API to send and receive data over the network using TCP connections. - * This API supersedes the TCP functionality previously found in the chrome.socket API. - * @since Chrome 33. - * @requires Manifest: "Sockets": {...} - */ - namespace sockets.tcp { + /** chrome.sockets.tcp API */ + namespace sockets { interface CreateInfo { /** * The ID of the newly created socket. @@ -6400,7 +6395,6 @@ declare namespace chrome { /** The result code returned from the underlying network call. */ resultCode: number; } - interface SocketProperties { /** * Flag indicating if the socket is left open when the event page of the @@ -6440,6 +6434,15 @@ declare namespace chrome { /** If the underlying socket is connected, contains the peer port. */ peerPort?: integer; } + } + + /** + * Use the chrome.sockets.tcp API to send and receive data over the network using TCP connections. + * This API supersedes the TCP functionality previously found in the chrome.socket API. + * @since Chrome 33. + * @requires Manifest: "Sockets": {...} + */ + namespace sockets.tcp { interface SecureOptions { /** * The minimum and maximum acceptable versions of TLS. @@ -6592,20 +6595,6 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer */ namespace sockets.tcpServer { - interface CreateInfo { - socketId: integer; - } - - interface AcceptEventArgs { - socketId: integer; - clientSocketId: integer; - } - - interface AcceptErrorEventArgs { - socketId: integer; - resultCode: integer; - } - /** * @see https://developer.chrome.com/apps/sockets_tcpServer#type-SocketProperties */ @@ -6787,95 +6776,11 @@ declare namespace chrome { * Use the chrome.sockets.udp API to send and receive data over the network * using UDP connections. This API supersedes the UDP functionality previously * found in the 'socket' API. - * + * @requires Manifest: "sockets": {...} * @since Chrome 33 * @see https://developer.chrome.com/apps/sockets_udp */ namespace sockets.udp { - interface CreateInfo { - socketId: integer; - } - - interface SendInfo { - resultCode: integer; - bytesSent?: integer; - } - - interface ReceiveEventArgs { - socketId: integer; - data: ArrayBuffer; - remoteAddress: string; - remotePort: integer; - } - - interface ReceiveErrorEventArgs { - socketId: integer; - resultCode: integer; - } - - /** - * @see https://developer.chrome.com/apps/sockets_udp#type-SocketProperties - */ - interface SocketProperties { - /** - * Flag indicating if the socket is left open when the event page of the - * application is unloaded. The default value is 'false.' When the - * application is loaded, any sockets previously opened with - * persistent=true can be fetched with getSockets. - * @see http://developer.chrome.com/apps/app_lifecycle.html - */ - persistent?: boolean; - - /** An application-defined string associated with the socket. */ - name?: string; - - /** - * 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. - */ - bufferSize?: integer; - } - - /** - * @see https://developer.chrome.com/apps/sockets_udp#type-SocketInfo - */ - interface SocketInfo { - /** The socket identifier. */ - socketId: integer; - - /** - * Flag indicating whether the socket is left open when the application - * is suspended (see SocketProperties.persistent). - */ - persistent: boolean; - - /** Application-defined string associated with the socket. */ - name?: string; - - /** - * The size of the buffer used to receive data. If no buffer size ha - * been specified explictly, the value is not provided. - */ - bufferSize?: integer; - - /** - * Flag indicating whether the socket is blocked from firing onReceive - * events. - */ - paused: boolean; - - /** - * If the underlying socket is bound, contains its local IPv4/6 address. - */ - localAddress?: string; - - /** - * If the underlying socket is bound, contains its local port. - */ - localPort?: integer; - } - /** * Creates a UDP socket with default properties. * @@ -7028,7 +6933,7 @@ declare namespace chrome { * 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 + * @see[MSDN]{@link http://goo.gl/6vqbj} * * Calling this method does not require multicast permissions. * @@ -7077,9 +6982,9 @@ declare namespace chrome { const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } - //////////////////// - // Storage - //////////////////// + ///////////// + // Storage // + ///////////// /** * Use the chrome.storage API to store, retrieve, and track changes to user data. * Permissions: 'storage' From ef371f068da06cde2233c9060a00805790b4247c Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 10:40:14 +0200 Subject: [PATCH 030/289] Sorted tests plus better coverage --- types/chrome-apps/index.d.ts | 5 +- types/chrome-apps/test/index.ts | 670 +++++++++++++++++--------------- 2 files changed, 363 insertions(+), 312 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index d34b619b94..80e8e60435 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -6388,6 +6388,7 @@ declare namespace chrome { /** The data received, with a maxium size of *bufferSize*. */ data: ArrayBuffer; } + interface AcceptEventArgs extends ReceiveEventArgs { } interface ReceiveErrorEventArgs { /** The socket identifier. */ @@ -6395,6 +6396,8 @@ declare namespace chrome { /** The result code returned from the underlying network call. */ resultCode: number; } + interface AcceptErrorEventArgs extends ReceiveErrorEventArgs { } + interface SocketProperties { /** * Flag indicating if the socket is left open when the event page of the @@ -7056,7 +7059,7 @@ declare namespace chrome { interface SyncStorageArea extends StorageArea { /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; + MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: chrome.deprecated; /** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ QUOTA_BYTES: number; /** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index f746962b91..cb01fe487f 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -37,283 +37,10 @@ currentWindow.onRestored.addListener(() => { return; }); // check platform capabilities var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(); -// FileSystem -// https://developer.chrome.com/apps/fileSystem -function test_fileSystem(): void { - var accepts: chrome.fileSystem.AcceptOptions[] = [ - { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] } - ]; - var chooseOption: chrome.fileSystem.ChooseEntryOptions = { - type: 'openFile', - suggestedName: 'foo.txt', - accepts: accepts, - acceptsAllTypes: false, - acceptsMultiple: false - }; - chrome.fileSystem.chooseEntry(chooseOption, (entry: Entry) => { - chrome.fileSystem.getDisplayPath(entry, (displayPath: string) => { }); - - var retainedId = chrome.fileSystem.retainEntry(entry); - chrome.fileSystem.isRestorable(retainedId, (isRestorable: boolean) => { - if (isRestorable) { - chrome.fileSystem.restoreEntry(retainedId, (restoredEntry: Entry) => { }); - } - }); - - chrome.fileSystem.getWritableEntry(entry, (writableEntry: Entry) => { }); - chrome.fileSystem.isWritableEntry(entry, (isWritable: boolean) => { }); - }); -} // Sockets -// https://developer.chrome.com/apps/sockets_tcp -function test_socketsTcp(): void { - var socketId: number = 0; - var properties: chrome.sockets.tcp.SocketProperties = {}; - var buffer: ArrayBuffer = new ArrayBuffer(256); - // create - chrome.sockets.tcp.create((info) => { - socketId = info.socketId; - }); - - chrome.sockets.tcp.create(properties, (info) => { - socketId = info.socketId; - }); - - // update - chrome.sockets.tcp.update(socketId, properties); - chrome.sockets.tcp.update(socketId, properties, () => { }); - - // setPaused - chrome.sockets.tcp.setPaused(socketId, true); - chrome.sockets.tcp.setPaused(socketId, true, () => { }); - - // setKeepAlive - chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); - chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); - - // setNoDelay - chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); - - // connect - chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { }); - - // disconnect - chrome.sockets.tcp.disconnect(socketId); - chrome.sockets.tcp.disconnect(socketId, () => { }); - - // send - chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { }); - - // close - chrome.sockets.tcp.close(socketId); - chrome.sockets.tcp.close(socketId, () => { }); - - // getInfo - chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); - - // getSockets - chrome.sockets.tcp.getSockets((infos: chrome.sockets.tcp.SocketInfo[]) => { }); -} - -function test_socketsTcpEvents(): void { - chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { }); - chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { }); -} - -function testSocketsTcpTypes(): void { - // SocketProperties - var properties: chrome.sockets.tcp.SocketProperties; - - properties = { - }; - - properties = { - persistent: true, - name: 'test', - bufferSize: 1024 - }; - - // SocketInfo - var socketInfo: chrome.sockets.tcp.SocketInfo; - - socketInfo = { - socketId: 1, - persistent: true, - paused: true, - connected: false - }; - - socketInfo.name = 'test'; - socketInfo.bufferSize = 1024; - socketInfo.localAddress = '192.168.0.2'; - socketInfo.localPort = 8000; - socketInfo.peerAddress = '192.168.0.3'; - socketInfo.peerPort = 1000; -} - -// https://developer.chrome.com/apps/sockets_udp -function test_socketsUdp(): void { - var socketId: number = 0 - var properties: chrome.sockets.udp.SocketProperties = {}; - var buffer: ArrayBuffer = new ArrayBuffer(256); - - // create - chrome.sockets.udp.create((info) => { - socketId = info.socketId; - }); - - chrome.sockets.udp.create(properties, (info) => { - socketId = info.socketId; - }); - - // update - chrome.sockets.udp.update(socketId, properties); - chrome.sockets.udp.update(socketId, properties, () => { }); - - // setPaused - chrome.sockets.udp.setPaused(socketId, true); - chrome.sockets.udp.setPaused(socketId, true, () => { }); - - // bind - 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) => { }); - - // close - chrome.sockets.udp.close(socketId); - chrome.sockets.udp.close(socketId, () => { }); - - // getInfo - chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); - - // getSockets - chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { }); - - // joinGroup - chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { }); - - // leaveGroup - chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { }); - - // setMulticastTimeToLive - chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); - - // setMulticastLoopbackMode - chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); - - // getJoinedGroups - chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); -} - -function test_socketsUdpEvents(): void { - chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { }); - chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { }); -} - -function testSocketsUdpTypes(): void { - // SocketProperties - var properties: chrome.sockets.udp.SocketProperties; - - properties = { - }; - - properties = { - persistent: true, - name: 'test', - bufferSize: 1024 - }; - - // SocketInfo - var socketInfo: chrome.sockets.udp.SocketInfo; - - socketInfo = { - socketId: 1, - persistent: true, - paused: true - }; - - socketInfo.name = 'test'; - socketInfo.bufferSize = 1024; - socketInfo.localAddress = '192.168.0.2'; - socketInfo.localPort = 8000; -} - -// https://developer.chrome.com/apps/sockets_tcpServer -function test_socketsTcpServer(): void { - var socketId: number = 0; - var properties: chrome.sockets.tcpServer.SocketProperties = {}; - var buffer: ArrayBuffer = new ArrayBuffer(256); - - // create - chrome.sockets.tcpServer.create((info) => { - socketId = info.socketId; - }); - - chrome.sockets.tcpServer.create(properties, (info) => { - socketId = info.socketId; - }); - - // update - chrome.sockets.tcpServer.update(socketId, properties); - chrome.sockets.tcpServer.update(socketId, properties, () => { }); - - // setPaused - chrome.sockets.tcpServer.setPaused(socketId, true); - 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) => { }); - - // disconnect - chrome.sockets.tcp.disconnect(socketId); - chrome.sockets.tcp.disconnect(socketId, () => { }); - - // close - chrome.sockets.udp.close(socketId); - chrome.sockets.udp.close(socketId, () => { }); - - // getInfo - chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); - - // getSockets - chrome.sockets.tcp.getSockets((infos: chrome.sockets.tcp.SocketInfo[]) => { }); -} - -function test_socketsTcpServerEvents(): void { - chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { }); - chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { }); -} - -function testSocketsTcpServerTypes(): void { - // SocketProperties - var properties: chrome.sockets.tcpServer.SocketProperties; - - properties = { - }; - - properties = { - persistent: true, - name: 'test' - }; - - // SocketInfo - var socketInfo: chrome.sockets.tcpServer.SocketInfo; - - socketInfo = { - socketId: 1, - persistent: true, - paused: true - }; - - socketInfo.name = 'test'; - socketInfo.localAddress = '192.168.0.2'; - socketInfo.localPort = 8000; -} function testSystemNetwork() { chrome.system.network.getNetworkInterfaces((networkInterfaces) => { @@ -330,46 +57,8 @@ gcmMessage.data = { test: true }; -let wve: chrome.webview.HTMLWebViewElement = (document.getElementById('webview')); -wve.name = 'test'; -wve.src = 'https://github.com/DefinitelyTyped'; -wve.allowtransparency = true; -wve.autosize = 'on'; -wve.partition = 'persist:githubwebview'; -wve.addEventListener('close', () => { - return; -}); -wve.addEventListener('consolemessage', (ev) => { - if (ev.level === 2) { - const msg = ev.message; - } -}); -wve.addEventListener('dialog', (ev) => { - ev.dialog.ok('Hello World!'); -}); -wve.addEventListener('loadstart', (ev) => { - if (ev.isTopLevel) { - return ev.url; - } - return; -}); -wve.addEventListener('zoomchange', (ev) => { - return ev.newZoomFactor || ev.oldZoomFactor; -}); -wve.addEventListener('loadredirect', (ev) => { - return ev.newUrl || ev.oldUrl; -}); -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']); @@ -666,6 +355,35 @@ chrome.hid.getDevices({ }); }); +// FILE SYSTEM +// https://developer.chrome.com/apps/fileSystem + +function test_fileSystem(): void { + var accepts: chrome.fileSystem.AcceptOptions[] = [ + { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] } + ]; + var chooseOption: chrome.fileSystem.ChooseEntryOptions = { + type: 'openFile', + suggestedName: 'foo.txt', + accepts: accepts, + acceptsAllTypes: false, + acceptsMultiple: false + }; + chrome.fileSystem.chooseEntry(chooseOption, (entry: Entry) => { + chrome.fileSystem.getDisplayPath(entry, (displayPath: string) => { }); + + var retainedId = chrome.fileSystem.retainEntry(entry); + chrome.fileSystem.isRestorable(retainedId, (isRestorable: boolean) => { + if (isRestorable) { + chrome.fileSystem.restoreEntry(retainedId, (restoredEntry: Entry) => { }); + } + }); + + chrome.fileSystem.getWritableEntry(entry, (writableEntry: Entry) => { }); + chrome.fileSystem.isWritableEntry(entry, (isWritable: boolean) => { }); + }); +} + // IDENTITY chrome.identity.getAuthToken({ interactive: true }, (token) => { @@ -674,3 +392,333 @@ chrome.identity.getAuthToken({ interactive: true }, (token) => { } chrome.identity.removeCachedAuthToken({ token: token }, () => { }); }); + +// MEDIA GALLERIES +chrome.fileSystem.getVolumeList((volumes) => { + chrome.fileSystem.requestFileSystem({ + volumeId: volumes[0].volumeId + }, (fs) => { + const mData = chrome.mediaGalleries.getMediaFileSystemMetadata(fs); + chrome.mediaGalleries.addGalleryWatch(mData.galleryId, (result) => { + if (result.success) { + console.log('Media gallery id', result.galleryId); + } + }); + }); +}); + +// MESSAGING + +chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => { + sendResponse({ "result": "Ops, I don't understand this message" }); +}); +chrome.runtime.sendMessage( + chrome.runtime.id, + { myCustomMessage: 'tra laa la' }, + (response) => { + console.log("Response: " + JSON.stringify(response)); + } +); + + +// SOCKETS +// https://developer.chrome.com/apps/sockets_tcp +function test_socketsTcp(): void { + var socketId: number = 0; + var properties: chrome.sockets.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcp.update(socketId, properties); + chrome.sockets.tcp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcp.setPaused(socketId, true); + chrome.sockets.tcp.setPaused(socketId, true, () => { }); + + // setKeepAlive + chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + + // setNoDelay + chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + + // connect + chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // send + chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.SendInfo) => { }); + + // close + chrome.sockets.tcp.close(socketId); + chrome.sockets.tcp.close(socketId, () => { }); + + // getInfo + chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets((infos: chrome.sockets.SocketInfo[]) => { }); +} + +function test_socketsTcpEvents(): void { + chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.ReceiveEventArgs) => { }); + chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.ReceiveErrorEventArgs) => { }); +} + +function testSocketsTcpTypes(): void { + // SocketProperties + var properties: chrome.sockets.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: 'test', + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: false + }; + + socketInfo.name = 'test'; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = '192.168.0.2'; + socketInfo.localPort = 8000; + socketInfo.peerAddress = '192.168.0.3'; + socketInfo.peerPort = 1000; +} + +// https://developer.chrome.com/apps/sockets_udp +function test_socketsUdp(): void { + var socketId: number = 0 + var properties: chrome.sockets.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.udp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.udp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.udp.update(socketId, properties); + chrome.sockets.udp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.udp.setPaused(socketId, true); + chrome.sockets.udp.setPaused(socketId, true, () => { }); + + // bind + 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.SendInfo) => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.SocketInfo) => { }); + + // getSockets + chrome.sockets.udp.getSockets((infos: chrome.sockets.SocketInfo[]) => { }); + + // joinGroup + chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { }); + + // leaveGroup + chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { }); + + // setMulticastTimeToLive + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + + // setMulticastLoopbackMode + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + + // getJoinedGroups + chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); +} + +function test_socketsUdpEvents(): void { + chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.ReceiveEventArgs) => { }); + chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.ReceiveErrorEventArgs) => { }); +} + +function testSocketsUdpTypes(): void { + // SocketProperties + var properties: chrome.sockets.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: 'test', + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: true, + }; + + socketInfo.name = 'test'; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = '192.168.0.2'; + socketInfo.localPort = 8000; +} + +// https://developer.chrome.com/apps/sockets_tcpServer +function test_socketsTcpServer(): void { + var socketId: number = 0; + var properties: chrome.sockets.tcpServer.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcpServer.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcpServer.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcpServer.update(socketId, properties); + chrome.sockets.tcpServer.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcpServer.setPaused(socketId, true); + 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) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets((infos: chrome.sockets.SocketInfo[]) => { }); +} + +function test_socketsTcpServerEvents(): void { + chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.AcceptEventArgs) => { }); + chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.AcceptErrorEventArgs) => { }); +} + +function testSocketsTcpServerTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcpServer.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: 'test' + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcpServer.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = 'test'; + socketInfo.localAddress = '192.168.0.2'; + socketInfo.localPort = 8000; +} + +chrome.sockets.udp.create({}, (createInfo) => { + chrome.sockets.udp.bind(createInfo['socketId'], '192.168.1.22', 0, + (result) => { + ((result >= 0) ? createInfo['socketId'] : null); + }); +}); + +// SYNC FILE SYSTEM + + +chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { + if (policy === 'manual') { + chrome.syncFileSystem.requestFileSystem((fs) => { + if (fs.root.isFile) { + throw new Error('It was a file!'); + } + }); + } +}); + +// WEBVIEW + +let wve: chrome.webview.HTMLWebViewElement = (document.getElementById('webview')); +wve.name = 'test'; +wve.src = 'https://github.com/DefinitelyTyped'; +wve.allowtransparency = true; +wve.autosize = 'on'; +wve.partition = 'persist:githubwebview'; +wve.addEventListener('close', () => { + return; +}); +wve.addEventListener('consolemessage', (ev) => { + if (ev.level === 2) { + const msg = ev.message; + } +}); +wve.addEventListener('dialog', (ev) => { + ev.dialog.ok('Hello World!'); +}); +wve.addEventListener('loadstart', (ev) => { + if (ev.isTopLevel) { + return ev.url; + } + return; +}); +wve.addEventListener('zoomchange', (ev) => { + return ev.newZoomFactor || ev.oldZoomFactor; +}); +wve.addEventListener('loadredirect', (ev) => { + return ev.newUrl || ev.oldUrl; +}); From c2ee28e95dabd5903e7d319684558e98c7b2c7a6 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 10:41:49 +0200 Subject: [PATCH 031/289] app.runtime: Fixed typo + added dev warning --- types/chrome-apps/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 80e8e60435..9c21f04bce 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -403,10 +403,11 @@ declare namespace chrome { } /** - * Fired when an embedding app requests to embed this app. This event is only available on dev channel with the flag --enable-app-view. + * Fired when an embedding app requests to embed this app. + * @requires(dev) This event is only available on dev channel with the flag --enable-app-view. * @since Since Chrome 38. */ - const onEmbedRequest: chrome.events.Event<(request: EmbedRequest) => void>; + const onEmbedRequested: chrome.events.Event<(request: EmbedRequested) => void>; /** * Fired when an app is launched from the launcher. */ From 65c84493dbb091732a0e436ba39df0a262edefc1 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 10:55:04 +0200 Subject: [PATCH 032/289] TTS test --- types/chrome-apps/test/index.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index cb01fe487f..0954eb4028 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -691,6 +691,35 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { } }); +// TTS + +chrome.tts.isSpeaking((isSpeaking) => { + if (!isSpeaking) { + chrome.tts.speak('This is the typings calling!', + { + volume: 10, + }); + } +}); + +// USB +const devices: { [key: string]: chrome.usb.Device } = {}; +chrome.usb.onDeviceAdded.addListener((device) => { + devices[device.device] = device; +}); +chrome.usb.onDeviceRemoved.addListener((device) => { + // tslint:disable-next-line:no-dynamic-delete + delete devices[device.device]; +}); +chrome.usb.getUserSelectedDevices({ + 'multiple': false +}, (selected_devices) => { + if (chrome.runtime.lastError != undefined) { + console.warn('chrome.usb.getUserSelectedDevices error: ' + chrome.runtime.lastError.message); + return; + } +}); + // WEBVIEW let wve: chrome.webview.HTMLWebViewElement = (document.getElementById('webview')); From 1c266c94060d3ea8bbb1857d4673dd885e2c0cbe Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 14:41:00 +0200 Subject: [PATCH 033/289] chrome.usb Documentation, Manifest WIP --- types/chrome-apps/index.d.ts | 1166 +++++++++++++++++++++++-------- types/chrome-apps/test/index.ts | 385 +++++++++- 2 files changed, 1244 insertions(+), 307 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 9c21f04bce..fec718c3e6 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -204,18 +204,18 @@ declare namespace chrome { namespace alarms { interface AlarmCreateInfo { /** Length of time in minutes after which the onAlarm event should fire. */ - delayInMinutes?: number; + delayInMinutes?: integer; /** 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; + periodInMinutes?: integer; /** Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ - when?: number; + when?: integer; } interface Alarm { /** If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ - periodInMinutes?: number; + periodInMinutes?: integer; /** 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; + scheduledTime: integer; /** Name of this alarm. */ name: string; } @@ -305,27 +305,27 @@ declare namespace chrome { 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" + 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 { @@ -343,10 +343,10 @@ declare namespace chrome { deny: () => void; } - type actionType = 'new_note'; + type ActionType = 'new_note'; const ActionType: { - NEW_NOTE: actionType + NEW_NOTE: ActionType } interface LaunchData { @@ -388,7 +388,7 @@ declare namespace chrome { * |____________________|____________|____________________________________________| * @since Since Chrome 54. */ - actionData?: actionType; + actionData?: ActionType; } interface LaunchDataItem { @@ -434,63 +434,63 @@ declare namespace chrome { */ namespace app { interface ContentBounds { - left?: number; - top?: number; - width?: number; - height?: number; + left?: integer; + top?: integer; + width?: integer; + height?: integer; } interface BoundsSpecification { /** The X coordinate of the content or window. */ - left?: number; + left?: integer; /** The Y coordinate of the content or window. */ - top?: number; + top?: integer; /** The width of the content or window. */ - width?: number; + width?: integer; /** The height of the content or window. */ - height?: number; + height?: integer; /** The minimum width of the content or window. */ - minWidth?: number; + minWidth?: integer; /** The minimum height of the content or window. */ - minHeight?: number; + minHeight?: integer; /** The maximum width of the content or window. */ - maxWidth?: number; + maxWidth?: integer; /** The maximum height of the content or window. */ - maxHeight?: number; + maxHeight?: integer; } interface Bounds { /** This property can be used to read or write the current X coordinate of the content or window. */ - left: number; + left: integer; /** This property can be used to read or write the current Y coordinate of the content or window. */ - top: number; + top: integer; /** This property can be used to read or write the current width of the content or window. */ - width: number; + width: integer; /** This property can be used to read or write the current height of the content or window. */ - height: number; + height: integer; /** This property can be used to read or write the current minimum width of the content or window. A value of null indicates 'unspecified'. */ - minWidth?: number | null; + minWidth?: integer | null; /** This property can be used to read or write the current minimum height of the content or window. A value of null indicates 'unspecified'. */ - minHeight?: number | null; + minHeight?: integer | null; /** This property can be used to read or write the current maximum width of the content or window. A value of null indicates 'unspecified'. */ - maxWidth?: number | null; + maxWidth?: integer | null; /** This property can be used to read or write the current maximum height of the content or window. A value of null indicates 'unspecified'. */ - maxHeight?: number | null; + maxHeight?: integer | null; /** Set the left and top position of the content or window. */ - setPosition(left: number, top: number): void; + setPosition(left: integer, top: integer): void; /** Set the width and height of the content or window. */ - setSize(width: number, height: number): void; + setSize(width: integer, height: integer): void; /** Set the minimum size constraints of the content or window. * The minimum width or height can be set to null to remove the constraint. * A value of undefined will leave a constraint unchanged. **/ - setMinimumSize(minWidth: number | null | undefined, minHeight: number | null | undefined): void; + setMinimumSize(minWidth: integer | null | undefined, minHeight: integer | null | undefined): void; /** * Set the maximum size constraints of the content or window. * The maximum width or height can be set to null to remove the constraint. * A value of undefined will leave a constraint unchanged. */ - setMaximumSize(maxWidth: number | null | undefined, maxHeight: number | null | undefined): void; + setMaximumSize(maxWidth: integer | null | undefined, maxHeight: integer | null | undefined): void; } interface FrameOptions { /** @@ -564,22 +564,22 @@ declare namespace chrome { * Minimum width of the window. * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - minWidth?: number; + minWidth?: integer; /** * Minimum height of the window. * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - minHeight?: number; + minHeight?: integer; /** * Maximum width of the window. * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - maxWidth?: number; + maxWidth?: integer; /** * Maximum height of the window. * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - maxHeight?: number; + maxHeight?: integer; /** Type of window to create */ type?: 'shell'; /** @@ -675,12 +675,12 @@ declare namespace chrome { * Move the window to the position (|left|, |top|). * @deprecated Deprecated since Chrome 43. Use outerBounds. */ - moveTo: (left: number, top: number) => void; + moveTo: (left: integer, top: integer) => void; /** * Resize the window to |width|x|height| pixels in size. * @deprecated Deprecated since Chrome 43. Use outerBounds. */ - resizeTo: (width: number, height: number) => void; + resizeTo: (width: integer, height: integer) => void; /** Draw attention to the window. */ drawAttention: () => void; /** Clear attention to the window. */ @@ -824,7 +824,7 @@ declare namespace chrome { /** True if this is the current active device. */ isActive: boolean; /** The sound level of the device, volume for output, gain for input. */ - level: number; + level: integer; /** The stable/persisted device id string when available. */ stableDeviceId?: string; } @@ -852,7 +852,7 @@ declare namespace chrome { interface OnLevelChangedEvent { addListener(callback: (event: { deviceId: string, - level: number + level: integer }) => void): void; } /** @todo TODO INTEGRATE */ @@ -952,12 +952,12 @@ declare namespace chrome { /** The human-readable name of the device. */ name?: string; /** The class of the device, a bit-field defined by http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband. */ - deviceClass?: number; + deviceClass?: integer; /** The Device ID record of the device, where available. */ vendorIdSource?: DeviceVendorIdSource; - vendorId?: number; - productId?: number; - deviceId?: number; + vendorId?: integer; + productId?: integer; + deviceId?: integer; /** * The type of the device, if recognized by Chrome. * This is obtained from the |deviceClass| field and only represents a small fraction of the possible device types. @@ -989,12 +989,12 @@ declare namespace chrome { * The received signal strength, in dBm. This field is avaliable and valid only during discovery. Outside of discovery it's value is not specified. * @since Chrome 44 */ - inquiryRssi: number; + inquiryRssi: integer; /** * The transmitted power level. This field is avaliable only for LE devices that include this field in AD. It is avaliable and valid only during discovery. * @since Chrome 44 */ - inquiryTxPower: number; + inquiryTxPower: integer; } interface BluetoothEvent { @@ -1010,7 +1010,7 @@ declare namespace chrome { /** Type of filter to apply to the device list. Default is all. */ filterType?: DeviceFilterType; /** Maximum number of bluetoth devices to return. Default is 0 (no limit) if unspecified. */ - limit?: number; + limit?: integer; } /** Get information about the Bluetooth adapter. */ function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; @@ -1139,11 +1139,11 @@ declare namespace chrome { /** The class of the device, a bit - field defined by: * @see [Specs]{@link http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband} **/ - deviceClass?: number; + deviceClass?: integer; } interface Request { /** Unique ID for this request. Use this ID when responding to this request. */ - requestId: number; + requestId: integer; /** Device that send this request. */ device: RequestDevice; /** Value to write (if this is a write request). */ @@ -1170,15 +1170,15 @@ declare namespace chrome { /** List of UUIDs to include in the 'Service UUIDs' field of the Advertising Data. These UUIDs can be of the 16bit, 32bit or 128 formats. */ serviceUuids?: string[]; /** List of manufacturer specific data to be included in 'Manufacturer Specific Data' fields of the advertising data. */ - manufacturerData?: { id: number, data: number[] }; + manufacturerData?: { id: integer, data: integer[] }; /** List of UUIDs to include in the 'Solicit UUIDs' field of the Advertising Data. These UUIDs can be of the 16bit, 32bit or 128 formats. */ solicitUuids?: string[]; /** List of service data to be included in 'Service Data' fields of the advertising data. */ - serviceData: { uuid: string, data: number[] }; + serviceData: { uuid: string, data: integer[] }; } interface IResponse { /** Id of the request this is a response to. */ - requestId: number; + requestId: integer; /** If this is an error response, this should be true. */ isError: boolean; /** Response value. Write requests and error responses will ignore this parameter. */ @@ -1379,7 +1379,7 @@ declare namespace chrome { * @param advertisement The advertisement to advertise. * @param callback Called once the registeration is done and we've started advertising. Returns the id of the created advertisement. */ - function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: number) => void): void; + function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: integer) => void): void; /** * Unregisters an advertisement and stops its advertising. * If the advertisement fails to unregister the only way @@ -1388,7 +1388,7 @@ declare namespace chrome { * @param advertisementId Id of the advertisement to unregister. * @param callback Called once the advertisement is unregistered and is no longer being advertised. */ - function unregisterAdvertisement(advertisementId: number, callback: () => void): void; + function unregisterAdvertisement(advertisementId: integer, callback: () => void): void; /** * Resets advertising on the current device. It will unregister and stop all existing advertisements. * @since Since Chrome 61. @@ -1406,7 +1406,7 @@ declare namespace chrome { * @param maxInterval Maximum interval between advertisments (in milliseconds). This cannot be more than 10240ms (as per the spec). * @param callback Called once the interval has been set. */ - function setAdvertisingInterval(minInterval: number, maxInterval: number, callback: () => void): void; + function setAdvertisingInterval(minInterval: integer, maxInterval: integer, callback: () => void): void; /** * Sends a response for a characteristic or descriptor read/write request. 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. @@ -1524,7 +1524,7 @@ declare namespace chrome { * Length of the socket's listen queue. * The default value depends on the operating system's host subsystem. * */ - backlog?: number; + backlog?: integer; } interface SocketInfo { /** @@ -1765,7 +1765,7 @@ declare namespace chrome { * @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; + function send(socketId: integer, data: ArrayBuffer, callback?: (bytesSent: integer) => void): void; /** * Retrieves the state of the given socket. * @param socketId The socket identifier. @@ -1845,7 +1845,7 @@ declare namespace chrome { /////////////// /** * @requires(dev) **Dev** channel only. - * @requires Permissions: "clipboard" + * @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. @@ -1859,8 +1859,8 @@ declare namespace chrome { 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". + * Either the plain text string if *type* is 'textPlain' or + * markup string if *type* is 'textHtml'. * The data can not exceed 2MB. */ data: string; @@ -1952,7 +1952,7 @@ declare namespace chrome { * can be added to an extension action context menu. * Any items beyond this limit will be ignored. */ - const ACTION_MENU_TOP_LEVEL_LIMIT: number; + const ACTION_MENU_TOP_LEVEL_LIMIT: integer; /** * 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. **/ @@ -2199,14 +2199,14 @@ declare namespace chrome { * Desktop Capture API that can be used to capture content of screen, * individual windows or tabs. * @since Availability: Since Chrome 34. - * @requires Permissions: "desktopCapture" + * @requires Permissions: 'desktopCapture' */ namespace desktopCapture { const DesktopCaptureSourceType: { - SCREEN: "screen", - WINDOW: "window", - TAB: "tab", - AUDIO: "audio" + SCREEN: 'screen', + WINDOW: 'window', + TAB: 'tab', + AUDIO: 'audio' } /** @@ -2217,12 +2217,12 @@ declare namespace chrome { * 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; + (sources: Array, callback: (streamId: string) => void): integer; /** * Hides desktop media picker dialog shown by chooseDesktopMedia(). * @param desktopMediaRequestId Id returned by chooseDesktopMedia() */ - function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; + function cancelChooseDesktopMedia(desktopMediaRequestId: integer): void; } /////////////////// @@ -2248,7 +2248,7 @@ declare namespace chrome { /** The MIME types that are accepted by the caller. */ mimeTypes?: string[]; /** The number of scanned images allowed (defaults to 1). */ - maxImages?: number; + maxImages?: integer; } interface DocumentScanCallbackArg { @@ -2474,7 +2474,7 @@ declare namespace chrome { * the resulting image will have more visual artifacts, * and the number of bytes needed to store it will decrease. */ - quality?: number; + quality?: integer; } /** * The soonest that the JavaScript or CSS will be injected into the tab. @@ -2513,7 +2513,7 @@ declare namespace chrome { * @see[frame ref]{@link https://developer.chrome.com/apps/webNavigation#frame_ids} * @since Since Chrome 50. */ - frameId?: number; + frameId?: integer; /** * 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. @@ -2873,7 +2873,7 @@ declare namespace chrome { /** The identifier of the file system related to this operation. */ fileSystemId: string; /** The unique identifier of this request. */ - requestId: number; + requestId: integer; /** The path of the entry to return the list of actions for. */ entryPath: string; } @@ -2890,7 +2890,7 @@ declare namespace chrome { /** The identifier of the file system related to this operation. */ fileSystemId: string; /** The unique identifier of this request. */ - requestId: number; + requestId: integer; /** The path of the entry to be used for the action. */ entryPath: string; /** The identifier of the action to be executed. */ @@ -3109,7 +3109,7 @@ declare namespace chrome { /** A request ID used to open the file. */ openRequestId: integer; /** Position in the file (in bytes) to start operating from. */ - offset: number; + offset: integer; /** Buffer of bytes to be operated on the file. */ data: ArrayBuffer; } @@ -3683,7 +3683,7 @@ declare namespace chrome { * @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; + function connect(deviceId: integer, callback: (connection: { connectionId: integer }) => void): void; /** * Disconnect from a device. @@ -4262,7 +4262,7 @@ declare namespace chrome { * 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; + function getCreationTime(callback: (creationTime: integer) => void): void; /** * Return a token that allows the authorized entity to access the service defined by scope. * @param getTokenParams Parameters for getToken. @@ -4293,7 +4293,7 @@ declare namespace chrome { * 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" + * @requires Permissions: 'management' */ namespace management { /** Information about an installed extension, app, or theme. */ @@ -4397,7 +4397,7 @@ declare namespace chrome { /** 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; + size: integer; } interface UninstallOptions { @@ -4517,7 +4517,7 @@ declare namespace chrome { /** * 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 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) {...}; @@ -4563,7 +4563,7 @@ declare namespace chrome { * @default 2048 * @since Chrome 44. */ - const MAX_SERVICE_INSTANCES_PER_EVENT: number; + const MAX_SERVICE_INSTANCES_PER_EVENT: integer; /** * Immediately issues a multicast DNS query for all service types. * |callback| is invoked immediately. @@ -4668,11 +4668,11 @@ declare namespace chrome { artist?: string; comment?: string; copyright?: string; - disc?: number; + disc?: integer; genre?: string; language?: string; title?: string; - track?: number; + track?: integer; /** * All the metadata in the media file. * For formats with multiple streams, stream order will be preserved. @@ -5512,9 +5512,9 @@ declare namespace chrome { */ contextMessage?: string; /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ - priority?: number; + priority?: integer; /** A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ - eventTime?: number; + eventTime?: integer; /** Text and icons for up to two notification action buttons. */ buttons?: ButtonOptions[]; /** Items for multi-item notifications. */ @@ -5524,7 +5524,7 @@ declare namespace chrome { * Current progress ranges from 0 to 100. * @since Chrome 30. */ - progress?: number; + progress?: integer; /** * Optional. * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. @@ -5551,7 +5551,7 @@ declare namespace chrome { interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> { } - interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: number) => void> { } + interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: integer) => void> { } interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> { } @@ -5829,7 +5829,7 @@ declare namespace chrome { * The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set. * @since Chrome 41. */ - frameId?: number; + frameId?: integer; /** * The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it. * @since Chrome 28. @@ -5894,7 +5894,15 @@ declare namespace chrome { } interface ManifestIcons { - [size: number]: string; + /** + * @example + * { + * '16': 'icon16.png', + * '48': 'icon48.png', + * '128': 'icon128.png' + * } + */ + [size: integer]: string; } interface ManifestAction { @@ -5917,15 +5925,26 @@ declare namespace chrome { instant_url_post_params?: string; image_url_post_params?: string; alternate_urls?: string[]; - prepopulated_id?: number; + prepopulated_id?: integer; is_default?: boolean; } - type Permissions = + type UrlPermission = + "https://www.google-analytics.com/*" + | "https://www.googleapis.com/*" + | '' + | 'http://*/*' + | 'https://*/*' + | 'file:///*/*'; + + type Permission = 'alarms' | + "app.window.fullscreen" | + "app.window.fullscreen.overrideEsc" | 'audio' | 'audioCapture' | 'background' | + 'bluetooth' | 'browser' | 'certificateProvider' | 'clipboard' | @@ -5947,6 +5966,7 @@ declare namespace chrome { 'hid' | 'identity' | 'idle' | + 'management' | 'mdns' | 'mediaGalleries' | 'nativeMessaging' | @@ -5958,7 +5978,7 @@ declare namespace chrome { 'power' | 'printerProvider' | 'proxy' | - 'serial' | + // 'serial' | // Deprecated 'signedInDevices' | 'socket' | 'storage' | @@ -5976,28 +5996,224 @@ declare namespace chrome { 'virtualKeyboard' | 'vpnProvider' | 'wallpaper' | - 'webview'; + 'webview' | + MediaGalleriesPermission | + SocketPermission | + PrivatePermissions | + USBDevicesPermission | + FileSystemPermission | + UrlPermission; + + interface MediaGalleriesPermission { + mediaGalleries: Array<'read' | 'allAutoDetected'>; + } + interface USBDevicesPermission { + usbDevices: { vendorId: integer, productId: integer }[] + } + interface FileSystemPermission { + fileSystem: Array<'write' | 'retainEntries' | 'directory'>; + } + interface SocketPermission { + /** + * **Possible values includes:** + * 'tcp-connect', + * 'udp-send-to', + * 'udp-send-to::*' + * 'udp-bind', + * 'udp-multicast-membership', + * 'resolve-host', + * 'network-state' + */ + socket: string[]; + } + + /** + * Only for whitelisted internal apps and extensions + * @private + * @internal + */ + type PrivatePermissions = 'Private' + | 'metricsPrivate' + | 'developerPrivate' + | 'activityLogPrivate' + | 'networkingPrivate' + | 'terminalPrivate'; + + + /// For chrome managed storage + + type JSONBasicTypes = 'integer' | 'string' | 'number'; + + interface JSONSchemaBasicType { + type: JSONBasicTypes; + } + interface JSONSchemaRefType { + '$ref': string; + } + interface JSONSchemaObjectType { + /** + * An "object" can have known properties listed as "properties", and can + * optionally have "additionalProperties" indicating a schema to apply to + * keys that aren't found in "properties". + */ + type: 'object'; + properties?: { + [key: string]: JSONSchemaBasicType | JSONSchemaRefType; + } + additionalProperties?: JSONSchemaObjectType; + } + interface JSONSchemaArrayType { + type: 'array', + id?: string; + items: JSONSchemaBasicType | JSONSchemaObjectType | JSONSchemaRefType; + } + + + /// For chrome.sockets /// + + type SocketPermissionOptions = '*:*' | '' | '*'; + interface SocketTcpPermission { + /** The host:port pattern for connect operations. */ + connect?: SocketPermissionOptions | string; + } + interface SocketTcpServerPermission { + /** The host:port pattern for listen operations. */ + listen?: SocketPermissionOptions | string; + } + interface SocketUdpPermission { + /** The host:port pattern for bind operations. */ + bind?: SocketPermissionOptions | string; + /** The host:port pattern for joinGroup operations. */ + multicastMembership?: SocketPermissionOptions | string; + /** The host:port pattern for send operations. */ + send?: SocketPermissionOptions | string; + } + + + /** + * The top-level object can't have additionalProperties. + * The properties declared are the policies for this app. + */ + interface ManagedSchema { + /** Each schema must have either a $ref value or exactly one type. */ + "$ref"?: string; + /** The top-level schema must have type object. */ + type: 'object'; + /** + * "properties" maps an optional key of this object to its schema. At the + * top-level object, these keys are the policy names supported. + */ + properties?: { + [key: string]: JSONSchemaBasicType | JSONSchemaArrayType | JSONSchemaObjectType | JSONSchemaRefType; + }; + } interface Manifest { - /** Required */ + ////////////// + // REQUIRED // + ////////////// + + /** + * Used by packaged apps to specify the app's background scripts. + * Also used by hosted apps to specify the URLs that the app uses. + * @required + */ app: { background: { scripts?: string[]; } } - /** Should be set to 2 */ - manifest_version: number; + /** + * One integer specifying the version of the manifest file format your package requires. + * As of Chrome 18, developers should specify 2 (without quotes). + * @see[Manifest Version Info]{@link https://developer.chrome.com/apps/manifest/manifest_version} + * @required + */ + manifest_version: 2; + /** + * The *name* (maximum of 45 characters) is the primary identifier + * of the app and is a required field. + * It is displayed in the following locations: + * - Install dialog + * - Extension management UI + * - Chrome Web Store + * + * You can specify locale-specific strings, see Internationalization docs: + * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} + * @required + */ name: string; + /** + * One to four dot-separated integers identifying the version of this extension. + * A couple of rules apply to the integers: they must be between 0 and 65535, inclusive, + * and non-zero integers can't start with 0. For example, 99999 and 032 are both invalid. + * A missing integer is equal to zero. For example, 1.1.9.9999 is newer than 1.1. + * @see[Manifest- Version Docs]{@link https://developer.chrome.com/apps/manifest/version} + * @required + */ version: string; - // Recommended + ///////////////// + // RECOMMENDED // + ///////////////// + + /** + * Specifies the subdirectory of _locales that contains the default strings for this extension. + * This field is required in extensions that have a _locales directory; it must be absent in + * extensions that have no _locales directory. For details, see Internationalization: + * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} + */ default_locale?: string; + /** + * A plain text string (no HTML or other formatting; no more than 132 characters) + * that describes the extension. The description should be suitable for both the + * browser's extension management UI and the Chrome Web Store. You can specify + * locale-specific strings for this field; see Internationalization for details. + * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} + */ description?: string; + /** + * One or more icons that represent the extension, app, or theme. + * You should always provide a 128x128 icon; it's used during + * installation and by the Chrome Web Store. Extensions should + * also provide a 48x48 icon, which is used in the extensions + * management page (chrome://extensions). You can also specify + * a 16x16 icon to be used as the favicon for an extension's pages. + * + * Icons should generally be in PNG format, because PNG has the best support for transparency. + * They can, however, be in any format supported by WebKit, including BMP, GIF, ICO, and JPEG. + * + * You may provide icons of any other size you wish, and Chrome will attempt to use the best size + * where appropriate. For example, Windows often requires 32-pixel icons, and if the app includes + * a 32-pixel icon, Chrome will choose that instead of shrinking a 48-pixel icon down. However, + * you should ensure that all of your icons are square, or unexpected behavior may result. + * + * @example + * 'icons': { '16': 'icon16.png', + * '48': 'icon48.png', + * '128': 'icon128.png' }, + */ icons?: ManifestIcons; - // Optional - action_handlers?: string[]; + + ////////////// + // OPTIONAL // + ////////////// + + /** + * @requires(CrOS) **This API is only available on ChromeOS.** + * @description + * The action_handlers manifest property declares which user actions or intents the + * application supports; these can serve as alternate launch points for your application. + * This list contains one or more of the ActionType values specified + * in the ActionType entry of app.runtime.onLaunched. + * @example + * 'action_handlers': ['new_note'] + */ + action_handlers?: app.runtime.ActionType[]; author?: any; - automation?: any; + automation?: boolean | { + [key: string]: string + }; bluetooth?: { uuids?: string[]; socket?: boolean; @@ -6037,7 +6253,7 @@ declare namespace chrome { file_system_provider_capabilities?: { configurable?: boolean; multiple_mounts?: boolean; - source?: string; + source?: 'network' | string; }; import?: { id: string; @@ -6049,7 +6265,11 @@ declare namespace chrome { }; kiosk_enabled?: boolean, kiosk_only?: boolean, - kiosk_secondary_apps: any; + kiosk_secondary_apps?: any; + /** + * @example + * "minimum_chrome_version": "33.0.1715.0" + */ minimum_chrome_version?: string; nacl_modules?: { path: string; @@ -6060,10 +6280,10 @@ declare namespace chrome { scopes?: string[]; }; offline_enabled?: boolean; - optional_permissions?: string[]; - permissions?: string[]; + optional_permissions?: Permission[] | Array; + permissions?: Permission[] | Array; platforms?: { - nacl_arch?: string; + nacl_arch?: 'x86-64' | 'x86-32' | 'arm' | string; sub_package_path: string; }[]; /** @@ -6110,36 +6330,88 @@ declare namespace chrome { * there is insufficient space to display the full name, such as: * - App launcher * - New Tab page + * + * You can specify locale-specific strings, see Internationalization docs: + * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ short_name?: string; signature?: any; + /** + * The sockets manifest property declares which permissions are available + * for the sockets.udp, sockets.tcp and sockets.tcpServer APIs. + */ sockets?: { - tcp?: { - connect: string | '*'; - }; - udp?: { - send: string | '*'; - } + /** The tcp manifest property declares which sockets.tcp operations an app can issue. */ + tcp?: SocketTcpPermission; + /** The tcpServer manifest property declares which sockets.tcpServer operations an app can issue. */ + tcpServer?: SocketTcpServerPermission; + /** The udp manifest property declares which sockets.udp operations an app can issue. */ + udp?: SocketUdpPermission; }; + /** + * Unlike the local and sync storage areas, + * the managed storage area requires its structure + * to be declared as JSON Schema and is strictly validated by Chrome. + * This schema must be stored in a file indicated by the "managed_schema" + * property of the "storage" manifest key and declares the enterprise + * policies supported by the app. Policies are analogous to options + * but are configured by a system administrator instead of the user, + * allowing the app to be preconfigured for all users of an organization. + * + * After declaring the policies they can be read from the storage.managed API. + * It's up to the app to enforce the policies configured by the administrator. + */ storage?: { - managed_schema: string + /** + * The storage.managed_schema property indicates a file within the app that contains the policy schema. + * @see[Docs and Schema Format]{@link https://developer.chrome.com/apps/manifest/storage} + */ + managed_schema: ManagedSchema; }; system_indicator?: any; - // update_url?: string; // Listed but deprecated since Chrome 33 - leaving it here so it's not added again + /** + * Autoupdating + * Only set this if you want to host somewhere other than the store. + * **Warning** + * As of M33, Windows stable / beta channel users can only + * download extensions hosted in the Chrome Web Store + * (@see[Protecting Windows users from malicious extensions]{@link http://blog.chromium.org/2013/11/protecting-windows-users-from-malicious.html}). + * @see[Documentation]{@link https://developer.chrome.com/apps/autoupdate} + */ + update_url?: string; + /** + * Used by packaged apps to specify URL patterns the app wants to intercept and handle. + * An app can define multiple URL handlers under this manifest entry, + * each having an identifier, a URL pattern, and a title. + * Here's an example of how to specify url_handlers: + * @example + * "view_foobar_presentation": { + * "matches": [ + * "https://www.foobar.com/presentation/view/*" + * ], + * "title": "View FooBar presentation" + * } + * @see[Documentation]{@link https://developer.chrome.com/apps/manifest/url_handlers} + */ url_handlers?: { [name: string]: { + /** URLs to match and handle */ matches: string[]; + /** + * The title field is reserved for future use in all relevant UI elements. + * It should describe the action that the app performs when launched with this type of URL handler. + */ title?: string; } }; + /** The usbPrinters manifest property declares which USB printers are supported by an app using the printerProvider API. */ usb_printers?: { - filters: { - vendorId?: number; - productId?: number; - interfaceClass?: number; - interfaceSubclass?: number; - interfaceProtocol?: number; - }[] + /** + * A list of USB device filters matching supported devices. + * A device only needs to match one of the provided filters. + * A vendorId is required and only one of productId or interfaceClass may be provided. + */ + filters: Require[]; }; version_name?: string; webview?: { @@ -6378,9 +6650,9 @@ declare namespace chrome { interface SendInfo { /** The result code returned from the underlying network call. A negative value indicates an error. */ - resultCode: number; + resultCode: integer; /** The number of bytes sent (if result == 0) */ - bytesSent?: number; + bytesSent?: integer; } interface ReceiveEventArgs { @@ -6395,7 +6667,7 @@ declare namespace chrome { /** The socket identifier. */ socketId: integer; /** The result code returned from the underlying network call. */ - resultCode: number; + resultCode: integer; } interface AcceptErrorEventArgs extends ReceiveErrorEventArgs { } @@ -6444,7 +6716,7 @@ declare namespace chrome { * Use the chrome.sockets.tcp API to send and receive data over the network using TCP connections. * This API supersedes the TCP functionality previously found in the chrome.socket API. * @since Chrome 33. - * @requires Manifest: "Sockets": {...} + * @requires Manifest: 'Sockets': {...} */ namespace sockets.tcp { interface SecureOptions { @@ -6473,7 +6745,7 @@ declare namespace chrome { /** * Enables or disables the application from receiving messages from its peer. - * The default value is "false". Pausing a socket is typically used by an + * The default value is 'false'. Pausing a socket is typically used by an * application to throttle data sent by its peer. When a socket is paused, * no onReceive event is raised. When a socket is connected and un-paused, * onReceive events are raised again when messages are received. @@ -6780,7 +7052,7 @@ declare namespace chrome { * Use the chrome.sockets.udp API to send and receive data over the network * using UDP connections. This API supersedes the UDP functionality previously * found in the 'socket' API. - * @requires Manifest: "sockets": {...} + * @requires Manifest: 'sockets': {...} * @since Chrome 33 * @see https://developer.chrome.com/apps/sockets_udp */ @@ -7001,14 +7273,14 @@ declare namespace chrome { * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ - getBytesInUse(callback: (bytesInUse: number) => void): void; + getBytesInUse(callback: (bytesInUse: integer) => void): void; /** * Gets the amount of space (in bytes) being used by one or more items. * @param keys A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ - getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: number) => void): void; + getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: integer) => void): void; /** * Removes all items from storage. * @param callback Optional. @@ -7055,29 +7327,29 @@ declare namespace chrome { interface LocalStorageArea extends StorageArea { /** The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; + QUOTA_BYTES: integer; } interface SyncStorageArea extends StorageArea { /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: chrome.deprecated; /** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; + QUOTA_BYTES: integer; /** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */ - QUOTA_BYTES_PER_ITEM: number; + QUOTA_BYTES_PER_ITEM: integer; /** The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set runtime.lastError. */ - MAX_ITEMS: number; + MAX_ITEMS: integer; /** * The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - MAX_WRITE_OPERATIONS_PER_HOUR: number; + MAX_WRITE_OPERATIONS_PER_HOUR: integer; /** * The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. * @since Chrome 40. */ - MAX_WRITE_OPERATIONS_PER_MINUTE: number; + MAX_WRITE_OPERATIONS_PER_MINUTE: integer; } interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> { } @@ -7221,7 +7493,7 @@ declare namespace chrome { * @param fileSystem * @param callback */ - function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: number, quotaBytes: number }) => void): void; + function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: integer, quotaBytes: integer }) => void): void; /** * Returns the FileStatus for the given fileEntry. * Note that 'conflicting' state only happens when @@ -7254,13 +7526,13 @@ declare namespace chrome { namespace system.cpu { interface ProcessorUsage { /** The cumulative time used by userspace programs on this processor. */ - user: number; + user: integer; /** The cumulative time used by kernel programs on this processor. */ - kernel: number; + kernel: integer; /** The cumulative time spent idle by this processor. */ - idle: number; + idle: integer; /** The total cumulative time for this processor. This value is equal to user + kernel + idle. */ - total: number; + total: integer; } interface ProcessorInfo { @@ -7270,7 +7542,7 @@ declare namespace chrome { interface CpuInfo { /** The number of logical processors. */ - numOfProcessors: number; + numOfProcessors: integer; /** The architecture name of the processors. */ archName: string; /** The model name of the processors. */ @@ -7299,24 +7571,24 @@ declare namespace chrome { namespace system.display { interface Bounds { /** The x-coordinate of the upper-left corner. */ - left: number; + left: integer; /** The y-coordinate of the upper-left corner. */ - top: number; + top: integer; /** The width of the display in pixels. */ - width: number; + width: integer; /** The height of the display in pixels. */ - height: number; + height: integer; } interface Insets { /** The x-axis distance from the left bound. */ - left: number; + left: integer; /** The y-axis distance from the top bound. */ - top: number; + top: integer; /** The x-axis distance from the right bound. */ - right: number; + right: integer; /** The y-axis distance from the bottom bound. */ - bottom: number; + bottom: integer; } /** @@ -7324,9 +7596,9 @@ declare namespace chrome { */ interface Point { /** The x-coordinate of the point. */ - x: number; + x: integer; /** The y-coordinate of the point. */ - y: number; + y: integer; } /** @@ -7344,22 +7616,22 @@ declare namespace chrome { */ interface DisplayMode { /** The display mode width in device independent (user visible) pixels. */ - width: number; + width: integer; /** The display mode height in device independent (user visible) pixels. */ - height: number; + height: integer; /** The display mode width in native pixels. */ - widthInNativePixels: number; + widthInNativePixels: integer; /** The display mode height in native pixels. */ - heightInNativePixels: number; + heightInNativePixels: integer; /** The display mode UI scale factor. */ - uiScale: number; + uiScale: integer; /** The display mode device scale factor. */ - deviceScaleFactor: number; + deviceScaleFactor: integer; /** True if the mode is the display's native mode. */ isNative: boolean; @@ -7381,7 +7653,7 @@ declare namespace chrome { /** The layout position of this display relative to the parent. This will be ignored for the root. */ position: DisplayPosition; /** The offset of the display along the connected edge. 0 indicates that the topmost or leftmost corners are aligned. */ - offset: number; + offset: integer; } /** @@ -7427,10 +7699,10 @@ declare namespace chrome { rotation?: 0 | 90 | 180 | 270; /** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */ - boundsOriginX?: number; + boundsOriginX?: integer; /** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */ - boundsOriginY: number; + boundsOriginY: integer; /** * @since Chrome 52 @@ -7469,11 +7741,11 @@ declare namespace chrome { /** True if this display is enabled. */ isEnabled: boolean; /** The number of pixels per inch along the x-axis. */ - dpiX: number; + dpiX: integer; /** The number of pixels per inch along the y-axis. */ - dpiY: number; + dpiY: integer; /** The display's clockwise rotation in degrees relative to the vertical position. Currently exposed only on ChromeOS. Will be set to 0 on other platforms. */ - rotation: number; + rotation: integer; /** The display's logical bounds. */ bounds: Bounds; /** The display's insets within its screen's bounds. Currently exposed only on ChromeOS. Will be set to empty insets on other platforms. */ @@ -7491,11 +7763,11 @@ declare namespace chrome { /** If set, sets the display's overscan insets to the provided values. Note that overscan values may not be negative or larger than a half of the screen's size. Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. */ overscan?: Insets; /** If set, updates the display's rotation. Legal values are [0, 90, 180, 270]. The rotation is set clockwise, relative to the display's vertical position. It's applied after overscan paramter. */ - rotation?: number; + rotation?: integer; /** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */ - boundsOriginX?: number; + boundsOriginX?: integer; /** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */ - boundsOriginY?: number; + boundsOriginY?: integer; } /** @@ -7637,9 +7909,9 @@ declare namespace chrome { namespace system.memory { interface MemoryInfo { /** The total amount of physical memory capacity, in bytes. */ - capacity: number; + capacity: integer; /** The amount of available capacity, in bytes. */ - availableCapacity: number; + availableCapacity: integer; } /** Get physical memory information. */ @@ -7653,7 +7925,7 @@ declare namespace chrome { interface NetworkInterface { name: string; address: string; - prefixLength: number; + prefixLength: integer; } function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; @@ -7681,14 +7953,14 @@ declare namespace chrome { */ type: string; /** The total amount of the storage space, in bytes. */ - capacity: number; + capacity: integer; } interface StorageCapacityInfo { /** A copied |id| of getAvailableCapacity function parameter |id|. */ id: string; /** The available capacity of the storage device, in bytes. */ - availableCapacity: number; + availableCapacity: integer; } interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> { } @@ -7727,7 +7999,7 @@ declare namespace chrome { /** An event from the TTS engine to communicate the status of an utterance. */ interface TtsEvent { /** The index of the current character in the utterance. */ - charIndex?: number; + charIndex?: integer; /** The error description, if the event type is 'error'. */ errorMessage?: string; /** @@ -7761,7 +8033,7 @@ declare namespace chrome { interface SpeakOptions { /** Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ - volume?: number; + volume?: integer; /** * Optional. * If true, enqueues this utterance if TTS is already in progress. If false (the default), interrupts any current speech and flushes the speech queue before speaking this new utterance. @@ -7771,7 +8043,7 @@ declare namespace chrome { * Optional. * Speaking rate relative to the default rate for this voice. 1.0 is the default rate, normally around 180 to 220 words per minute. 2.0 is twice as fast, and 0.5 is half as fast. Values below 0.1 or above 10.0 are strictly disallowed, but many voices will constrain the minimum and maximum rates further—for example a particular voice may not actually speak faster than 3 times normal even if you specify a value larger than 3.0. */ - rate?: number; + rate?: integer; /** * 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. @@ -7781,7 +8053,7 @@ declare namespace chrome { * Optional. * 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; + pitch?: integer; /** The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; /** The name of the voice to use for synthesis. If empty, uses any available voice. */ @@ -7922,83 +8194,183 @@ declare namespace chrome { } } - //////////////////// - // USB - //////////////////// + ///////// + // USB // + ///////// + /** + * @requires Permissions: "usb" + * @since Available since Chrome 26. + * Use the chrome.usb API to interact with connected USB devices. + * This API provides access to USB 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. + * @see[Accessing Hardware Devices]{@link https://developer.chrome.com/apps/app_usb} + */ namespace usb { + /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ type Direction = 'in' | 'out'; interface Device { - device: number, - vendorId: number, - productId: number, + /** + * An opaque ID for the USB device. It remains unchanged until the device is unplugged. + * @since Chrome 31. + */ + device: integer, + /** The vendor ID. */ + vendorId: integer, + /** The product ID. */ + productId: integer; + /** + * The device version (bcdDevice field). + * @since Chrome 46. + */ + version: integer; + /** + * The iProduct string read from the device, if available. + * @since Chrome 46. + */ productName: string, + /** + * The iManufacturer string read from the device, if available. + * @since Chrome 46. + */ manufacturerName: string, + /** + * The iSerialNumber string read from the device, if available. + * @since Chrome 46. + */ serialNumber: string } + /** Since Chrome 31. */ interface ConnectionHandle { - handle: number, - vendorId: number, - productId: number + /** + * An opaque handle representing this connection to the USB device + * and all associated claimed interfaces and pending transfers. + * A new handle is created each time the device is opened. + * The connection handle is different from Device.device. + */ + handle: integer; + /** The device vendor ID. */ + vendorId: integer; + /** The product ID. */ + productId: integer; } type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; - type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback'; + type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback' | 'periodic' | 'notification'; + /** Since Chrome 29. */ interface EndpointDescriptor { - address: number, - type: EndpointType, - direction: Direction, - maximumPacketSize: number, - synchronization?: EndpointSyncType, - usage?: EndpointUsage, - pollingInterval?: number, - extra_data: ArrayBuffer + /** Transfer type. */ + address: integer; + /** Transfer type. */ + type: EndpointType; + /** Transfer direction. */ + direction: Direction; + /** Maximum packet size. */ + maximumPacketSize: integer; + /** Transfer synchronization mode (isochronous only). */ + synchronization?: EndpointSyncType; + /** Endpoint usage hint */ + usage?: EndpointUsage; + /** Polling interval (interrupt and isochronous only). */ + pollingInterval?: integer; + /** + * Extra descriptor data associated with this endpoint. + * @since Chrome 39. + */ + extra_data: ArrayBuffer; } + /** @since Chrome 29. */ interface InterfaceDescriptor { - interfaceNumber: number, - alternateSetting: number, - interfaceClass: number, - interfaceSubclass: number, - interfaceProtocol: number, - description?: string, - endpoints: EndpointDescriptor[], - extra_data: ArrayBuffer + /** The interface number */ + interfaceNumber: integer; + /** + * The interface alternate setting number. + * @default 0 + */ + alternateSetting: integer; + /** The USB interface class. */ + interfaceClass: integer; + /** The USB interface sub-class. */ + interfaceSubclass: integer; + /** The USB interface protocol. */ + interfaceProtocol: integer; + /** Description of the interface */ + description?: string; + /** Available endpoints. */ + endpoints: EndpointDescriptor[]; + /** + * Extra descriptor data associated with this interface. + * @since Chrome 39. + */ + extra_data: ArrayBuffer; } + /** @since Chrome 39. */ interface ConfigDescriptor { - active: boolean, - configurationValue: number, - description?: string, - selfPowered: boolean, - remoteWakeup: boolean, - maxPower: number, - interfaces: InterfaceDescriptor[], - extra_data: ArrayBuffer + /** + * Is this the active configuration? + * @since Chrome 47. + */ + active: boolean; + /** The configuration number. */ + configurationValue: integer; + /** Description of the configuration. */ + description?: string; + /** The device is self-powered. */ + selfPowered: boolean; + /** The device supports remote wakeup. */ + remoteWakeup: boolean; + /** The maximum power needed by this device in milliamps (mA). */ + maxPower: integer; + /** Available interfaces. */ + interfaces: InterfaceDescriptor[]; + /** Extra descriptor data associated with this configuration. */ + extra_data: ArrayBuffer; } interface GenericTransferInfo { - direction: Direction, - endpoint: number, - length?: number, - data?: ArrayBuffer, - timeout?: number + /** The transfer direction ("in" or "out"). */ + direction: Direction; + /** The target endpoint address. The interface containing this endpoint must be claimed. */ + endpoint: integer; + /** The maximum number of bytes to receive (required only by input transfers). */ + length?: integer; + /** The data to transmit (required only by output transfers). */ + data?: ArrayBuffer; + /** + * Request timeout (in milliseconds). + * The default value 0 indicates no timeout. + * @default 0 + */ + timeout?: integer; } interface TransferResultInfo { - resultCode: number, - data?: ArrayBuffer + /** A value of 0 indicates that the transfer was a success. Other values indicate failure. */ + resultCode?: integer; + /** The data returned by an input transfer. undefined for output transfers. */ + data?: ArrayBuffer; } + /** @since Since Chrome 39. */ interface DeviceFilter { - vendorId?: number, - productId?: number, - interfaceClass?: number, - interfaceSubclass?: number, - interfaceProtocol?: number + /** Device vendor ID. */ + vendorId?: integer; + /** Device product ID, checked only if the vendor ID matches. */ + productId?: integer; + /** USB interface class, matches any interface on the device. */ + interfaceClass?: integer; + /** USB interface sub-class, checked only if the interface class matches. */ + interfaceSubclass?: integer; + /** USB interface protocol, checked only if the interface sub-class matches. */ + interfaceProtocol?: integer; } type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; @@ -8006,40 +8378,238 @@ declare namespace chrome { type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; interface TransferInfo { + /** The transfer direction ("in" or "out"). */ direction: Direction; + /** The transfer target. The target given by index must be claimed if "interface" or "endpoint". */ recipient: TransferRecipient; + /** The request type. */ requestType: TransferRequestType; - request: number; - value: number; - index: number; - length?: number; + /** The bRequest field, see *Universal Serial Bus Specification Revision 1.1 § 9.3.* */ + request: integer; + /** The wValue field, see *Ibid*. */ + value: integer; + /** The wIndex field, see *Ibid*. */ + index: integer; + /** The maximum number of bytes to receive(required only by input transfers). */ + length?: integer; + /** The data to transmit (required only by output transfers). */ data?: ArrayBuffer; - timeout?: number; + /** + * @since Chrome 43. + * Request timeout (in milliseconds). + * The default value 0 indicates no timeout. + * @default 0 + */ + timeout?: integer; } + interface IsochronousTransferInfo { + /** + * Transfer parameters. + * The transfer length or data buffer specified in this parameter block is split + * along packetLength boundaries to form the individual packets of the transfer. + */ + transferInfo: GenericTransferInfo; + /** The total number of packets in this transfer. */ + packets: integer; + /** The length of each of the packets in this transfer. */ + packetLength: integer; + } + + /** + * @description Enumerates connected USB devices. + * @since Chrome 39. + * @param options The properties to search for on target devices. + * @param callback + */ + function getDevices(options: { filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + + /** + * Presents a device picker to the user and returns 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. + * @since Chrome 40. + * @param options Configuration of the device picker dialog box. + * - multiple: Allow the user to select multiple devices. + * - filters: Filter the list of devices presented to the user. + * If multiple filters are provided, devices matching any filter will be displayed. + * @param callback Invoked with a list of chosen Devices. + */ + function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + + /** + * Returns the full set of device configuration descriptors. + * @since Chrome 47. + * @param device The Device to fetch descriptors from. + * @param callback + */ + function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void; + + /** + * @deprecated Since Chrome 40. + * @requires(CrOS) Chrome OS specific. This operation is now implicitly performed as a part of *openDevice*. + */ + function requestAccess(device: Device, interfaceId: integer, callback: (success: boolean) => void): void; + + /** + * Opens a USB device returned by *getDevices* + * @since Chrome 31. + * @param device The device to open. + * @param callback + */ + function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void; + + /** + * Finds USB devices specified by the vendor, product and (optionally) interface IDs and if permissions allow opens them for use. + * If the access request is rejected or the device fails to be opened a connection handle will not be created or returned. + * Calling this method is equivalent to calling *getDevices* followed by *openDevice* for each device. + * @param options The properties to search for on target devices. + * - vendorId: The device vendor ID. + * - productId: The product ID. + * @param callback + */ + function findDevices(options: { vendorId: integer, productId: integer }, callback: (handles: ConnectionHandle[]) => void): void; + /** + * Finds USB devices specified by the vendor, product and (optionally) interface IDs and if permissions allow opens them for use. + * If the access request is rejected or the device fails to be opened a connection handle will not be created or returned. + * Calling this method is equivalent to calling *getDevices* followed by *openDevice* for each device. + * @param options The properties to search for on target devices. + * - vendorId: The device vendor ID. + * - productId: The product ID. + * - The interface ID to request access to. Only available on Chrome OS. It has no effect on other platforms. + * @requires(CrOS) Chrome OS if you specify *interfaceId* + * @param callback + */ + function findDevices(options: { vendorId: integer, productId: integer, interfaceId?: integer }, callback: (handles: ConnectionHandle[]) => void): void; + + /** + * Closes a connection handle. + * Invoking operations on a handle after it has been closed is a safe operation but causes no action to be taken. + * @param handle The ConnectionHandle to close. + * @param [callback] + */ + function closeDevice(handle: ConnectionHandle, callback?: () => void): void; + + /** + * Select a device configuration. + * This function effectively resets the device by selecting one of the + * device's available configurations. Only configuration values greater + * than 0 are valid however some buggy devices have a working + * configuration 0 and so this value is allowed. + * @since Chrome 42. + * @param handle An open connection to the device. + * @param configurationValue + * @param callback + */ + function setConfiguration(handle: ConnectionHandle, configurationValue: integer, callback: () => void): void; + + /** + * Gets the configuration descriptor for the currently selected configuration. + * @since Chrome 39. + * @param handle An open connection to the device. + * @param callback + */ + function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void; + + /** + * @description Lists all interfaces on a USB device. + * @param handle An open connection to the device. + * @param callback + */ + function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void; + + /** + * Claims an interface on a USB device. + * Before data can be transfered to an interface or associated endpoints the interface must be claimed. + * Only one connection handle can claim an interface at any given time. + * If the interface is already claimed, this call will fail. + * + * **releaseInterface** should be called when the interface is no longer needed. + * @param handle An open connection to the device. + * @param interfaceNumber The interface to be claimed. + * @param callback + */ + function claimInterface(handle: ConnectionHandle, interfaceNumber: integer, callback: () => void): void; + + /** + * @description Releases a claimed interface. + * @param handle An open connection to the device. + * @param interfaceNumber The interface to be released. + * @param callback + */ + function releaseInterface(handle: ConnectionHandle, interfaceNumber: integer, callback: () => void): void; + + /** + * @description Selects an alternate setting on a previously claimed interface. + * @param handle An open connection to the device where this interface has been claimed. + * @param interfaceNumber The interface to configure. + * @param alternateSetting The alternate setting to configure. + * @param callback + */ + function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: integer, alternateSetting: integer, callback: () => void): void; + + /** + * Performs a control transfer on the specified device. + * Control transfers refer to either the device, an interface or an endpoint. + * Transfers to an interface or endpoint require the interface to be claimed. + * @param handle An open connection to the device. + * @param transferInfo Transfer info + * @param callback + */ + function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void; + + /** + * @description Performs a bulk transfer on the specified device. + * @param handle An open connection to the device. + * @param transferInfo The transfer parameters. + * @param callback + */ + function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + + /** + * @description Performs an interrupt transfer on the specified device. + * @param handle An open connection to the device. + * @param transferInfo The transfer parameters. + * @param callback + */ + function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + + /** + * @description Performs an isochronous transfer on the specific device. + * @param handle An open connection to the device. + * @param transferInfo + * @param callback + */ + function isochronousTransfer(handle: ConnectionHandle, transferInfo: IsochronousTransferInfo, callback: (info: TransferResultInfo) => void): void; + + /** + * Tries to reset the USB device. If the reset fails, the given connection handle will be closed + * and the USB device will appear to be disconnected then reconnected. + * In this case **getDevices** or **findDevices** must be called again to acquire the device. + * @param handle A connection handle to reset. + * @param callback + */ + function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void; + interface DeviceEvent extends chrome.events.Event<(device: Device) => 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, when the user accepted an optional permission + * (@see[permissions.request]{https://developer.chrome.com/apps/permissions#method-request}), + * or through **getUserSelectedDevices**. + * @since Chrome 42. + */ const onDeviceAdded: DeviceEvent; - const onDeviceRemoved: DeviceEvent; - 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; + /** + * Event generated when a device is removed from the system. + * See **onDeviceAdded** for which events are delivered. + * @since Chrome 42. + */ + const onDeviceRemoved: DeviceEvent; } @@ -8182,17 +8752,17 @@ declare namespace chrome { * (accessible via the getTime method of the JavaScript *Date* object). * If absent, defaults to *0* (which would remove all browsing data). **/ - since?: number; + since?: integer; } interface WindowEvent extends chrome.events.Event<() => void> { } interface ConsoleEvent extends Event { /** The severity level of the log message. Ranges from 0 to 4. */ - level: number; + level: integer; /** The logged message contents.*/ message: string; /** The line number of the message source.*/ - line: number; + line: integer; /** A string identifying the resource which logged the message. */ sourceId: string; } @@ -8204,7 +8774,7 @@ declare namespace chrome { 'kill'; interface ExitEvent extends Event { /** Chrome's internal ID of the process that exited. */ - processID: number; + processID: integer; /** String indicating the reason for the exit. */ reason: ExitEventReason; } @@ -8212,7 +8782,7 @@ declare namespace chrome { /** Description of a declarative rule for handling events. */ interface Rule { /** Optional priority of this rule. Defaults to 100. */ - priority?: number; + priority?: integer; /** List of conditions that can trigger the actions. */ conditions: any[]; /** Optional identifier that allows referencing this rule. */ @@ -8534,7 +9104,7 @@ declare namespace chrome { * Gets the current zoom factor. * @param callback */ - getZoom(callback: (zoomFactor: number) => void): void; + getZoom(callback: (zoomFactor: integer) => void): void; /** * Gets the current zoom mode. @@ -8550,7 +9120,7 @@ declare namespace chrome { * a value of -3 will navigate backward 3 entries. * @param callback */ - go(relativeIndex: number, callback?: (success: boolean) => void): void; + go(relativeIndex: integer, callback?: (success: boolean) => void): void; /** * Injects CSS into the guest page. @@ -8592,7 +9162,7 @@ declare namespace chrome { * @param zoomFactor The new zoom factor. * @param [callback] */ - setZoom(zoomFactor: number, callback?: () => void): void; + setZoom(zoomFactor: integer, callback?: () => void): void; /** * Sets the zoom mode of the webview. @@ -8979,7 +9549,7 @@ declare namespace chrome { /** * The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: number | string; + parentId?: integer | 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. @@ -9024,7 +9594,7 @@ declare namespace chrome { /** * 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?: integer | string; /** * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. @@ -9114,9 +9684,9 @@ declare namespace chrome { /** Contains all of the results of the find request. */ interface FindCallbackResults { /** The number of times searchText was matched on the page. */ - numberOfMatches: number; + numberOfMatches: integer; /** The ordinal number of the current match. */ - activeMatchOrdinal: number; + activeMatchOrdinal: integer; /** Describes a rectangle around the active match in screen coordinates. */ selectionRect: SelectionRect; /** Indicates whether this find request was canceled. */ @@ -9158,13 +9728,13 @@ declare namespace chrome { **/ interface SelectionRect { /** Distance from the left edge of the screen to the left edge of the rectangle. */ - left: number; + left: integer; /** Distance from the top edge of the screen to the top edge of the rectangle. */ - top: number; + top: integer; /** Width of the rectangle. */ - width: number; + width: integer; /** Height of the rectangle. */ - height: number; + height: integer; } /** * Interface which provides access to webRequest events on the guest page. @@ -9238,7 +9808,7 @@ declare namespace chrome { /** The logged message contents. */ message: string; /** The line number of the message source. */ - line: number; + line: integer; /** A string identifying the resource which logged the message. */ sourceId: string; } @@ -9268,7 +9838,7 @@ declare namespace chrome { 'kill'; interface Exit { /** Chrome's internal ID of the process that exited. */ - processID: number; + processID: integer; /** String indicating the reason for the exit. */ reason: ExitReason; } @@ -9280,12 +9850,12 @@ declare namespace chrome { /** * The number of matches found for searchText on the page so far. */ - numberOfMatches: number; + numberOfMatches: integer; /** * The ordinal number of the current active match, * if it has been found. This will be 0 until then. */ - activeMatchOrdinal: number; + activeMatchOrdinal: integer; /** * Describes a rectangle around the active match, * if it has been found, in screen coordinates. @@ -9364,10 +9934,10 @@ declare namespace chrome { targetUrl: string; /** The initial width requested for the new window. */ - initialWidth: number; + initialWidth: integer; /** The initial height requested for the new window. */ - initialHeight: number; + initialHeight: integer; /** The requested name of the new window. */ name: string; @@ -9391,27 +9961,27 @@ declare namespace chrome { } interface ProcessResponsive { /** Chrome's internal ID of the process that became responsive. */ - processID: number; + processID: integer; } interface SizeChanged { /** Old width of embedded web content. */ - oldWidth: number; + oldWidth: integer; /** Old height of embedded web content. */ - oldHeight: number; + oldHeight: integer; /** New width of embedded web content. */ - newWidth: number; + newWidth: integer; /** New height of embedded web content. */ - newHeight: number; + newHeight: integer; } interface ProcessUnresponsive { /** Chrome's internal ID of the process that has become unresponsive. */ - processID: number; + processID: integer; } interface ZoomChange { /** The page's previous zoom factor. */ - oldZoomFactor: number; + oldZoomFactor: integer; /** The new zoom factor that the page was zoomed to. */ - newZoomFactor: number; + newZoomFactor: integer; } } @@ -9423,10 +9993,10 @@ declare namespace chrome { * Different page speed and load metrics */ function csi(): { - onloadT: number; - pageT: number; - startE: number; - tran: number; + onloadT: integer; + pageT: integer; + startE: integer; + tran: integer; } /** diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 0954eb4028..1b4c03f64d 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -173,23 +173,390 @@ chrome.app.runtime.onLaunched.addListener(() => { id: "test", innerBounds: { width: 900, - height: 1280 - } - } + height: 1280, + }, + }); }); +// FORBIDDEN APIs +document.write('forbidden'); +Document.prototype.write.call(document, 'Hello, world'); +window.addEventListener('beforeunload', () => { }); +// MANIFEST const ManifestJSONTest1: chrome.runtime.Manifest = { + "container": "GOOGLE_DRIVE", + "api_console_project_id": "619683526622", "manifest_version": 2, - "name": "Sample Appview Embedded", - "description": "This sample shows how to allow your app to be embedded into another app", - "version": "2", - "minimum_chrome_version": "43", - "permissions": ["videoCapture"], + "name": "Sample Appview Embedded - modified for manifest test", + "description": "__MSG_appDescription__", + "version": "2.1", + "minimum_chrome_version": "33.0.1715.0", + "default_locale": "en", + "options_page": "options.html", + "chrome_url_overrides": { + "newtab": "app.html" + }, + "options_ui": { + "chrome_style": true, + "page": "options.html" + }, + "launch": { + "web_url": "https://developer.mbed.org/compiler/#nav:/;" + }, + "file_system_provider_capabilities": { + "configurable": false, + "multiple_mounts": true, + "source": "network" + }, + "platforms": [{ + "nacl_arch": "x86-64", + "sub_package_path": "_platform_specific/x86-64/" + }, { + "nacl_arch": "x86-32", + "sub_package_path": "_platform_specific/x86-32/" + }, { + "nacl_arch": "arm", + "sub_package_path": "_platform_specific/arm/" + }], + "web_accessible_resources": ["html/crosh.html", "html/nassh.html", "html/nassh_google_relay.html", "html/nassh_connect_dialog.html"], + "permissions": [ + "https://www.google-analytics.com/*", + "http://localhost:8080/*", + "https://www.googleapis.com/*", + "identity", + "terminalPrivate", + "app.window.alpha", "app.window.shape", + "experimental", + "webview", + "alarms", + "storage", + "videoCapture", + "browser", + "clipboardWrite", + "usb", + "metricsPrivate", "networkingPrivate", + "bluetooth", + "tabCapture", + "unlimitedStorage", + { "fileSystem": ["write", "retainEntries", "directory"] }, + "clipboardRead", + "desktopCapture", + "clipboardWrite", + "pointerLock", + "", + "mdns", + "gcm", + "power", + "clipboardRead", + "clipboardWrite", + "cookies", "tabs", + "http://*/*", + "https://*/*", + "file:///*/*", + "idle", + "app.window.fullscreen", + "app.window.fullscreen.overrideEsc", + "contextMenus", + "browser", + "system.cpu", "system.memory", "system.storage", "system.display", + "notifications", + "*://*/*", + "accessibilityFeatures.read", "accessibilityFeatures.modify", + "tts", + "fullscreen", "alwaysOnTopWindows", + "geolocation", + "audioCapture", + "hid", + "metricsPrivate", "nativeMessaging", + "management", "developerPrivate", "activityLogPrivate", + { + "mediaGalleries": ["read", "allAutoDetected"] + }, + { "socket": ["udp-send-to::*", "tcp-connect", "udp-send-to", "udp-bind", "udp-multicast-membership", "resolve-host", "network-state", "tcp-connect", "resolve-host", "network-state"] }, + "tts", + "syncFileSystem", + { + "usbDevices": [ + { "vendorId": 10168, "productId": 493 } + ] + } + ], + "storage": { + "managed_schema": "schema.json" + }, + "browser_action": { + "default_icon": { + "128": "img/icon.png" + }, + "default_title": "AnimAlerts", + "default_popup": "html/popup.html" + }, + "author": { + "name": "Your name here", + "email": "Email@yourmail.com" + }, + "author": "hei", + "update_url": "https://clients2.google.com/service/update2/crx", + "version_name": "10.0.12-stable", + "kiosk_enabled": true, + "offline_enabled": true, + "bluetooth": { + "low_energy": true, + "uuids": ["180f"] + }, + "url_handlers": { + "wiki_article": { + "title": "View Wikipedia article", + "matches": [ + "*://en.wikipedia.org/wiki/*" + ] + }, + "mobile_wiki_article": { + "title": "View Wikipedia article", + "matches": [ + "*://en.m.wikipedia.org/wiki/*" + ] + }, + "google_drive_open": { + "matches": ["https://api.chromerestclient.com/GDrive.html*"], + "title": "Open from Google Drive" + } + }, + "sockets": { + "udp": { "bind": "*", "send": "*" }, + "tcpServer": { "listen": "" }, + "tcp": { + "connect": "*:*" + }, + "tcp": { "connect": ["*:5555", "*:5559"] }, + "udp": { "bind": ["*:5554", "*:5556"], "multicastMembership": "", "send": ["*:5554", "*:5556"] } + }, + "optional_permissions": [ + "audioCapture", + "serial", + { "usbDevices": [{ "vendorId": 2338, "productId": 32 }] } + ], + "webview": { + "partitions": [ + { + "name": "blockable", + "accessible_resources": ["browser.css", "blocked.css", "blocked.html"] + }, + { + "accessible_resources": ["player.*", "migrate.*"], + "name": "player" + } + ] + }, + "externally_connectable": { + "matches": ["https://gauth.fusionlabs.net/*"] + }, + "commands": { + "cmdNew": { + "suggested_key": { + "default": "Ctrl+Shift+1" + }, + "global": true, + "description": "Create new window" + }, + "new-team-login": { + "suggested_key": { + "default": "Ctrl+Shift+Y", + "mac": "Command+Shift+Y" + }, + "description": "New team login" + }, + "reload": { + "suggested_key": { + "default": "Ctrl+R" + }, + "description": "Reload webview" + } + }, + "automation": { + "desktop": true + }, + "automation": true, + "sandbox": { + "content_security_policy": "sandbox allow-scripts allow-popups; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com/ga.js;", + "pages": ["sandbox.html"] + }, + "content_security_policy": "script-src 'self' https://www.gstatic.com/; object-src 'self'" + "file_handlers": { + "image": { + "types": [ + "image/png", + "image/jpeg" + ] + }, + "text": { + "types": [ + "text/*" + ], + "extensions": ["abap", "as", "ada", "adb", "ads", "conf", "asciidoc", "asm", "ahk", "bat", "c", "cpp", "h", "hpp", "cc", "cirru", "clj", "cob", "cbl", "ccp", "cb2", "cof", "coffee", "cfm", "cfc", "cfml", "cs", "css", "curly", "dart", "diff", "djt", "djhtml", "dt", "d", "dot", "ejs", "erl", "frt", "ftl", "feature", "glsl", "go", "groovy", "haml", "hbs", "handlebars", "hs", "hx", "htm", "html", "erb", "ini", "jk", "jack", "jade", "java", "class", "js", "gs", "javascript", "jsoniq", "json", "jsp", "jsx", "jl", "latex", "less", "liquid", "lisp", "ls", "logic", "logiql", "lsl", "lua", "lp", "lucene", "make", "makefile", "mak", "md", "mat", "mel", "mc", "mush", "mysql", "nix", "m", "mm", "ml", "mli", "mll", "pas", "pl", "pm", "pgsql", "php", "inc", "text", "txt", "readme", "log", "ps1", "psm1", "pro", "p", "plg", "properties", "proto", "py", "rdoc", "rd", "rhtml", "r", "rb", "rbx", "rs", "sass", "scad", "scala", "scm", "ss", "scss", "sh", "sjs", "smarty", "snippets", "soy", "space", "sql", "styl", "stylus", "svg", "tcl", "tex", "textile", "tmsnippet", "toml", "twig", "ts", "vbs", "vbe", "vm", "v", "vhd", "vhdl", "xml", "rss", "atom", "xhtml", "xquery", "xq", "yaml", "yml", "mcc"] + }, + "any": { + "extensions": [ + "skrifa", + "skrup" + ] + }, + "7zip": { + "extensions": ["7z"], + "types": ["application/x-7z", "application/x-7z-compressed"] + }, + "Z": { + "extensions": ["Z"], + "types": ["application/x-compress"] + }, + "ar": { + "extensions": ["a"], + "types": ["application/x-archive"] + }, + "bzip2": { + "extensions": ["bz", "bz2"], + "types": ["application/x-bzip", "application/x-bzip2"] + }, + "cab": { + "extensions": ["cab"], + "types": ["application/x-cab"] + }, + "cpio": { + "extensions": ["cpio", "cpio.gz", "cpio.bz2", "cpio.xz"], + "types": ["application/x-cpio"] + }, + "deb": { + "extensions": ["deb"], + "types": ["application/vnd.debian.binary-package"] + }, + "gzip": { + "extensions": ["gz"], + "types": ["application/x-gzip"] + }, + "iso": { + "extensions": ["iso"], + "types": ["application/x-iso9660-image"] + }, + "lha": { + "extensions": ["lha", "lzh"], + "types": ["application/x-lha", "application/x-lzh", "application/x-lzh-compressed"] + }, + "lz4": { + "extensions": ["lz4"], + "types": ["application/x-lz4"] + }, + "lzip": { + "extensions": ["lzip"], + "types": ["application/x-lzip"] + }, + "lzop": { + "extensions": ["lzop"], + "types": ["application/x-lzop"] + }, + "pax": { + "extensions": ["pax", "pax.gz", "pax.bz2", "pax.xz"], + "types": ["application/x-pax"] + }, + "rpm": { + "extensions": ["rpm"], + "types": ["application/x-rpm", "application/x-redhat-package-manager"] + }, + "tar": { + "extensions": ["gtar", "tar", "tgz", "tbz2", "txz", "tz"], + "types": ["application/x-tar", "application/x-gtar", "application/x-gtar-compressed"] + }, + "xz": { + "extensions": ["lzma", "xz"], + "types": ["application/x-lzma", "application/x-xz"] + }, + "zip": { + "extensions": ["apk", "crx", "jar"], + "types": ["application/java-archive", "application/x-chrome-extension"] + } + }, + "file_system_provider_capabilities": { + "multipleMounts": true, + "source": "file" + }, + "requirements": { + "3D": { + "features": ["webgl"] + } + }, + "display_in_launcher": false, + "display_in_new_tab_page": false, + "key": "FIMaMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDJB6ZGcGxtlr/34s+TKgi84QiP7DMekqOjSUS2ubmbhchlM6CN9gYdGQ1aBI3TBXG3YaAu+XyutFA8M8NLLWc4OOGByW123aaa1DP6p67g8a+Ids/gX6cNSRnRHiDZXAd44ATxoN4OZjZJk9iQ26RIUjwX07bzntlI+frwwKCk4WQIDAQAB", + "oauth2": { + // client_id below is specifc to the application key. Follow the + // documentation to obtain one for your app. + "auto_approve": true, + "client_id": "1111111222333.apps.googleusercontent.com", + "scopes": ["https://www.googleapis.com/auth/plus.login"] + }, "app": { + "icon_color": "#00FDFD", + "urls": ["http://walkerrandolphsmith.com/"], "background": { - "scripts": ["main.js"] + "scripts": ["angular.js", "lodash.js", "background.js"], + "persistent": false, + "transient": true + }, + "linked_icons": [{ + "size": 16, + "url": "https://test.bi:8080/assets/icon_16.png" + }, { + "size": 32, + "url": "https://test.bi:8080/favicon.ico" + }, { + "size": 48, + "url": "https://test.bi:8080/favicon.ico" + }, { + "size": 64, + "url": "https://test.bi:8080/favicon.ico" + }, { + "size": 72, + "url": "https://test.bi:8080/assets/icon_72.png" + }, { + "size": 96, + "url": "https://test.bi:8080/assets/icon_96.webp" + }, { + "size": 128, + "url": "https://test.bi:8080/assets/icon_128.webp" + }, { + "size": 144, + "url": "https://test.bi:8080/assets/icon_144.png" + }, { + "size": 168, + "url": "https://test.bi:8080/assets/icon_168.png" + }, { + "size": 192, + "url": "https://test.bi:8080/assets/icon_192.png" + }, { + "size": 256, + "url": "https://test.bi:8080/assets/exposer_splash_512.webp" + }, { + "size": 512, + "url": "https://test.bi:8080/assets/exposer_splash_512.png" + }], + "theme_color": "rgba(77,208,192,1)", + "launch": { + "web_url": "https://hyjk2000.github.io/party-lottery/?source=chrome-app", + "container": "panel" + } + }, + "icons": { + "16": "icon16.png", + "48": "icon48.png", + "64": "assets/icon-64x64.png", + "128": "icon128.png" + }, + "action_handlers": ["new_note"], + "offline_enabled": true, + "sockets": { + "tcp": { + "connect": "*:*" } } } From 2061cb994377d37047664e2976f7c225ce01204b Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 15:07:21 +0200 Subject: [PATCH 034/289] Small fixes --- types/chrome-apps/index.d.ts | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index fec718c3e6..0d0ae8ff83 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5902,7 +5902,7 @@ declare namespace chrome { * '128': 'icon128.png' * } */ - [size: integer]: string; + [size: number]: string; } interface ManifestAction { @@ -6411,12 +6411,35 @@ declare namespace chrome { * A device only needs to match one of the provided filters. * A vendorId is required and only one of productId or interfaceClass may be provided. */ - filters: Require[]; + filters: chrome.usb.DeviceFilterStrict[]; }; + /** + * version_name can be set to a descriptive version string and will be used for display purposes if present. + * If no version_name is present, the version field will be used for display purposes as well. + * @example + * "version_name": "0.8 beta" + * "version_name": "build rc3" + * "version_name": "Gold Edition" + */ version_name?: string; + /** + * By default, webviews are prevented from loading any resources packaged with the app. + * However, webview partitions may be granted access to these resources via a webview.partitions + * section in the app manifest. Partitions may be granted access to a set of files by + * matching partition name patterns with file name patterns. Both sorts of patterns may + * contain the * wildcard. + * @see[Accessing packaged resources]{@link https://developer.chrome.com/apps/tags/webview#local_resources} + */ webview?: { partitions?: { name: string; + /** + * Path to files, relative, absolute or pattern + * @example + * ["local_*.html", "*.png", "*.js"] + * ["img/epic.html"] + * + */ accessible_resources: string[]; }[] } @@ -8359,10 +8382,9 @@ declare namespace chrome { data?: ArrayBuffer; } - /** @since Since Chrome 39. */ - interface DeviceFilter { + interface DeviceFilterStrict { /** Device vendor ID. */ - vendorId?: integer; + vendorId: integer; /** Device product ID, checked only if the vendor ID matches. */ productId?: integer; /** USB interface class, matches any interface on the device. */ @@ -8373,6 +8395,9 @@ declare namespace chrome { interfaceProtocol?: integer; } + /** @since Since Chrome 39. */ + interface DeviceFilter extends Partial { } + type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; From 1e16bd61d3391aa62013bd58083061a85ade8bdb Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 15:55:21 +0200 Subject: [PATCH 035/289] Cleanup and fixes --- types/chrome-apps/index.d.ts | 406 +++++++++++++---------------------- 1 file changed, 149 insertions(+), 257 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 253b17e7dd..f22cee4024 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -328,7 +328,7 @@ declare namespace chrome { URL_HANDLER = 'url_handler' } - interface EmbedRequest { + interface EmbedRequested { /** * Optional developer specified data that the app to be embedded can use when making an embedding decision. */ @@ -343,11 +343,7 @@ declare namespace chrome { deny: () => void; } - type ActionType = 'new_note'; - - const ActionType: { - NEW_NOTE: ActionType - } + type actionType = 'new_note'; const ActionType: { NEW_NOTE: actionType @@ -2459,27 +2455,32 @@ declare namespace chrome { * @since Chrome 39. **/ namespace extensionTypes { - /** - * The format of an image. - **/ - type ImageFormat = - 'jpeg' | - 'png'; - /** - * Details about the format and quality of an image. - */ - interface ImageDetails { - /** The format of the resulting image. Default is 'jpeg'. */ - format?: ImageFormat; + interface ImageDetailsPng { + /** + * The format of the resulting image. + * @default 'jpeg' + */ + format?: 'jpeg'; /** - * 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. + * Controls the quality of the resulting image. + * As quality is decreased, the resulting image + * will have more visual artifacts, and the number + * of bytes needed to store it will decrease. */ quality?: integer; } + + interface ImageDetailsJpeg { + /** + * The format of the resulting image. + */ + format?: 'png'; + } + /** + * Details about the format and quality of an image. + */ + type ImageDetails = ImageDetailsJpeg | ImageDetailsPng; /** * The soonest that the JavaScript or CSS will be injected into the tab. **/ @@ -6213,17 +6214,21 @@ declare namespace chrome { * @example * 'action_handlers': ['new_note'] */ - action_handlers?: app.runtime.ActionType[]; + action_handlers?: app.runtime.actionType[]; + /** @todo TODO */ author?: any; + /** @todo TODO */ automation?: boolean | { [key: string]: string }; + /** @todo TODO */ bluetooth?: { uuids?: string[]; socket?: boolean; low_energy?: boolean; peripheral?: boolean; }; + /** @todo TODO */ commands?: { [name: string]: { suggested_key?: { @@ -6237,7 +6242,9 @@ declare namespace chrome { global?: boolean } }; + /** @todo TODO */ current_locale?: string; + /** @todo TODO */ event_rules?: { event?: string; actions?: { @@ -6248,44 +6255,58 @@ declare namespace chrome { css?: string[] }[]; }[]; + /** @todo TODO */ file_handlers?: { [key: string]: { extensions?: Array<'*' | string | { include_directories: boolean }>; types?: Array<'*' | string | { include_directories: boolean }>; } }[]; + /** @todo TODO */ file_system_provider_capabilities?: { configurable?: boolean; multiple_mounts?: boolean; source?: 'network' | string; }; + /** @todo TODO */ import?: { id: string; }[]; + /** @todo TODO */ key?: string; + /** @todo TODO */ kiosk?: { always_update: any; required_platform_version: any; }; - kiosk_enabled?: boolean, - kiosk_only?: boolean, + /** @todo TODO */ + kiosk_enabled?: boolean; + /** @todo TODO */ + kiosk_only?: boolean; + /** @todo TODO */ kiosk_secondary_apps?: any; /** * @example * "minimum_chrome_version": "33.0.1715.0" */ minimum_chrome_version?: string; + /** @todo TODO */ nacl_modules?: { path: string; mime_type: string; }[]; + /** @todo TODO */ oauth2?: { client_id: string; scopes?: string[]; }; + /** @todo TODO */ offline_enabled?: boolean; + /** @todo TODO */ optional_permissions?: Permission[] | Array; + /** @todo TODO */ permissions?: Permission[] | Array; + /** @todo TODO */ platforms?: { nacl_arch?: 'x86-64' | 'x86-32' | 'arm' | string; sub_package_path: string; @@ -6339,6 +6360,7 @@ declare namespace chrome { * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ short_name?: string; + /** @todo TODO */ signature?: any; /** * The sockets manifest property declares which permissions are available @@ -6372,6 +6394,7 @@ declare namespace chrome { */ managed_schema: ManagedSchema; }; + /** @todo TODO */ system_indicator?: any; /** * Autoupdating @@ -6447,6 +6470,7 @@ declare namespace chrome { accessible_resources: string[]; }[] } + /** @todo TODO */ [key: string]: any; } @@ -8773,16 +8797,18 @@ declare namespace chrome { * 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). - **/ + * (accessible via the getTime method of the JavaScript Date object). + * If absent, defaults to 0 (which would remove all browsing data). + * @default 0 + */ since?: integer; } + interface WindowEvent extends chrome.events.Event<() => void> { } interface ConsoleEvent extends Event { @@ -8991,29 +9017,36 @@ declare namespace chrome { addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: ZoomChange) => void, useCapture?: boolean): void; /** * Queries audio state. + * @since Chrome 62. **/ getAudioState(callback: (audible: boolean) => void): void; /** * Sets audio mute state of the webview. * @param mute Mute audio value + * @since Chrome 62. */ setAudioMuted(mute: boolean): void; /** * Queries whether audio is muted. + * @since Chrome 62. */ isAudioMuted(callback: (muted: boolean) => void): void; /** * 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. + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. */ captureVisibleRegion(callback: (dataUrl: string) => void): void; /** * Captures the visible region of the webview. - * @param options - * @param callback + * @param options Extension type + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. */ captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; @@ -9022,6 +9055,7 @@ declare namespace chrome { * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. * You can programmatically add rules or update existing rules. * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. + * @example * webview.addContentScripts([ * { * name: 'myRule', @@ -9037,12 +9071,13 @@ declare namespace chrome { * run_at: 'document_end' * }]); * ... - * * // Navigates webview. * webview.src = 'http://www.foo.com'; + * + * @description * You can defer addContentScripts call until you needs to inject scripts. * The following example shows how to overwrite an existing rule. - * + * @example * webview.addContentScripts([{ * name: 'rule', * matches: ['http://www.foo.com/*'], @@ -9058,17 +9093,22 @@ declare namespace chrome { * matches: ['http://www.bar.com/*'], * js: { files: ['scriptB.js'] }, * run_at: 'document_end'}]); - * If webview has been naviagted to the origin (e.g., foo.com) and calls webview.addContentScripts to add 'myRule', + * @description + * If webview has been naviagted to the origin (e.g., foo.com) and + * calls webview.addContentScripts to add 'myRule', * you need to wait for next navigation to make the scripts injected. * If you want immediate injection, executeScript will do the right thing. - * Rules are preserved even if the guest process crashes or is killed or even if the webview is reparented. + * Rules are preserved even if the guest process crashes + * or is killed or even if the webview is reparented. * Refer to the /extensions/content_scripts documentation for more details. * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. + * @since Chrome 44. */ addContentScripts(contentScriptList: ContentScriptDetails[]): void; /** - * Navigates backward one history entry if possible. Equivalent to go(-1). + * 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; @@ -9091,7 +9131,8 @@ declare namespace chrome { * 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 + * @param callback Called after the data has been successfully cleared. + * @since Chrome 33. */ clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; @@ -9099,47 +9140,61 @@ declare namespace chrome { * 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 + * @example + * webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' }); + * @param details Details of the script to run. + * @param [callback] Called after all the JavaScript has been executed. */ executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; /** * 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 + * @param searchText The string to find in the page. + * @param [options] Options for the find request. + * @param [callback] Called after all find results have been returned for this find request. + * Provides optionally: + * results: Contains all of the results of the find request. + * results can be omitted if it is not utilized in the callback function body; + * e.g. if the callback is only used to discern when the find request has completed. */ - find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; + find(searchText: string, options?: FindOptions, callback?: (results?: FindCallbackResults) => void): void; /** * Navigates forward one history entry if possible. Equivalent to go(1). - * @param callback + * @param [callback] Called after the navigation has either failed or completed successfully. + * Provides *success* which indicates whether the navigation was successful. */ forward(callback?: (success: boolean) => void): void; /** - * 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; + getProcessId(): integer; /** * Returns the user agent string used by the webview for guest page requests. + * @since Since Chrome 33. */ - getUserAgent(): void; + getUserAgent(): string; /** * Gets the current zoom factor. - * @param callback + * @param callback Called after the current zoom factor is retrieved. Provides the current zoom factor. + * @since Chrome 36. */ - getZoom(callback: (zoomFactor: integer) => void): void; + getZoom(callback: (zoomFactor: double) => void): void; /** * Gets the current zoom mode. - * @param callback + * @param callback Called with the webview's current zoom mode. + * @since Since Chrome 43. */ - getZoomMode(callback: (ZoomMode: any) => void): void; + getZoomMode(callback: (ZoomMode: ZoomMode) => void): void; /** * Navigates to a history entry using a history index relative to the current navigation. @@ -9147,21 +9202,29 @@ declare namespace chrome { * @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 + * @param [callback] Called after the navigation has either failed or completed successfully. + * Provides a boolean, *success*, which indicates whether the navigation was successful. */ go(relativeIndex: integer, callback?: (success: boolean) => void): void; /** * Injects CSS into the guest page. * @param details Details of the CSS to insert. - * @param callback + * @param callback Called after the CSS has been inserted. */ insertCSS(details: InjectDetails, callback?: () => void): void; - /** Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. */ + /** + * Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. + * @since Since Chrome 33. + */ isUserAgentOverridden(): void; - /** 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. + * @since Since Chrome 38. + */ print(): void; /** Reloads the current top-level page. */ @@ -9173,14 +9236,16 @@ declare namespace chrome { * @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. + * @param 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. + * @since Chrome 44. */ - removeContentScripts(scriptNameList?: any[]): void; + removeContentScripts(scriptNameList?: string[]): void; /** * Override the user agent string used by the webview for guest page requests. * @param userAgent The user agent string to use. + * @since Since Chrome 33. */ setUserAgentOverride(userAgent: string): void; @@ -9189,14 +9254,16 @@ declare namespace chrome { * The scope and persistence of this change * are determined by the webview's current zoom mode. * @param zoomFactor The new zoom factor. - * @param [callback] + * @param [callback] Called after the page has been zoomed. + * @since Since Chrome 36. */ - setZoom(zoomFactor: integer, callback?: () => void): void; + setZoom(zoomFactor: double, callback?: () => void): void; /** * Sets the zoom mode of the webview. * @param ZoomMode Defines how zooming is handled in the webview. - * @param [callback] + * @param [callback] Called after the zoom mode has been changed. + * @since Since Chrome 43. */ setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; @@ -9207,16 +9274,22 @@ declare namespace chrome { * @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. + * @param 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. + * @since Since Chrome 35. */ - stopFinding(action?: string): void; + stopFinding(action?: 'clear' | 'keep' | 'activate'): void; /** * 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). + * @param dataUrl The data URL to load. + * @param baseUrl The base URL that will be used for relative links. + * @param virtualUrl The URL that will be displayed to the user (in the address bar). + * @since Since Chrome 40. */ loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; @@ -9226,194 +9299,8 @@ declare namespace chrome { * but it will not affect webview tags in other apps. */ terminate(): void; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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 - */ - - loadcommit: chrome.events.Event; - - /** - * Fired when a top-level load request has redirected to a different URL. - * @param callback - */ - - loadredirect: chrome.events.Event; - - /** - * Fired when a load has begun. - * @param callback - */ - - loadstart: chrome.events.Event; - - /** - * 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. - */ - loadstop(event: chrome.events.Event): void; - - /** - * 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; - - /** - * 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; - - /** - * 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; - /** - * Fired when the embedded web content has been resized via autosize. - * @requires Note: Only fires if autosize is enabled. - */ - sizechanged: chrome.events.Event; - /** - * 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; - /** - * Fired when the page's zoom changes. - */ - zoomchange: chrome.events.Event; } - /** 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). - * @default 0 - */ - since?: integer; - } /** A set of data types. Missing properties are interpreted as false. */ interface ClearDataTypeSet { /** Websites' appcaches. */ @@ -9793,7 +9680,12 @@ declare namespace chrome { * @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 */ + onBeforeRequest: chrome.events.Event<(details: any) => void>; + onBeforeSendHeaders: chrome.events.Event<(details: any) => void>; + onSendHeaders: chrome.events.Event<(details: any) => void>; + onHeadersReceived: chrome.events.Event<(details: any) => void>; + onAuthRequired: chrome.events.Event<(details: any) => void>; + } /** * Defines the how zooming is handled in the webview. @@ -10015,9 +9907,9 @@ declare namespace chrome { } interface ZoomChange { /** The page's previous zoom factor. */ - oldZoomFactor: integer; + oldzoomFactor: double; /** The new zoom factor that the page was zoomed to. */ - newZoomFactor: integer; + newzoomFactor: double; } } From a1e828de73ca763c167833f2ec6893227b770e7e Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Mon, 6 Aug 2018 16:59:04 +0200 Subject: [PATCH 036/289] Implementing webview's webRequest interface --- types/chrome-apps/index.d.ts | 375 +++++++++++++++++++++++++++++++- types/chrome-apps/test/index.ts | 15 +- 2 files changed, 383 insertions(+), 7 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index f22cee4024..e76ae8652d 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -9659,6 +9659,216 @@ declare namespace chrome { /** Height of the rectangle. */ height: integer; } + + /** An HTTP Header, represented as an object containing a key and either a value or a binaryValue. */ + interface HttpHeader { + name: string; + value?: string; + binaryValue?: ArrayBuffer; + } + + interface ResourceRequest { + url: string; + /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ + requestId: string; + /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ + frameId: number; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: number; + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ + tabId: number; + /** + * How the requested resource will be used. + */ + type: webRequest.ResourceType; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: number; + /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. + * @since Since Chrome 63. + */ + initiator?: string; + } + + interface WebRequestDetails extends ResourceRequest { + /** Standard HTTP method. */ + method: string; + } + + interface WebRequestHeadersDetails extends WebRequestDetails { + /** Optional. The HTTP request headers that are going to be sent out with this request. */ + requestHeaders?: HttpHeader[]; + } + + interface WebRequestBodyDetails extends WebRequestDetails { + /** + * Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'. + * @since Chrome 23. + */ + requestBody: WebRequestBody; + } + + /** + * Contains data uploaded in a URL request. + * @since Chrome 23. + */ + interface UploadData { + /** Optional. An ArrayBuffer with a copy of the data. */ + bytes?: ArrayBuffer; + /** Optional. A string with the file's path and name. */ + file?: string; + } + + interface WebRequestBody { + /** Optional. Errors when obtaining request body data. */ + error?: string; + /** + * Optional. + * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. + */ + formData?: { [key: string]: string[] }; + /** + * Optional. + * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. + */ + raw?: UploadData[]; + } + + interface WebRequestFullDetails extends WebRequestHeadersDetails, WebRequestBodyDetails { + } + + interface WebResponseDetails extends ResourceRequest { + /** HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line). */ + statusLine: string; + /** + * Standard HTTP status code returned by the server. + * @since Chrome 43. + */ + statusCode: number; + } + + interface WebResponseHeadersDetails extends WebResponseDetails { + /** Optional. The HTTP response headers that have been received with this response. */ + responseHeaders?: HttpHeader[]; + /** standard HTTP method i.e. GET, POST, PUT, etc. */ + method: string; + } + + interface WebResponseCacheDetails extends WebResponseHeadersDetails { + /** + * Optional. + * The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address. + */ + ip?: string; + /** Indicates if this response was fetched from disk cache. */ + fromCache: boolean; + } + + interface WebRedirectionResponseDetails extends WebResponseCacheDetails { + /** The new URL. */ + redirectUrl: string; + } + + /** An object describing filters to apply to webRequest events. */ + interface RequestFilter { + /** Optional. */ + tabId?: number; + /** + * A list of request types. Requests that cannot match any of the types will be filtered out. + */ + types?: chrome.webRequest.ResourceType[]; + /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ + urls: string[]; + + /** Optional. */ + windowId?: number; + } + + export interface AuthCredentials { + username: string; + password: string; + } + + /** Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests. */ + interface BlockingResponse { + /** + * If true, the request is cancelled. + * Used in onBeforeRequest, this prevents the request from being sent. */ + cancel?: boolean; + /** + * Only used as a response to the onBeforeRequest and onHeadersReceived events. + * If set, the original request is prevented from being sent/completed and is + * instead redirected to the given URL. Redirections to non-HTTP schemes such + * as data: are allowed. Redirects initiated by a redirect action use the + * original request method for the redirect, with one exception: If the + * redirect is initiated at the onHeadersReceived stage, then the redirect + * will be issued using the GET method. + */ + redirectUrl?: string; + /** + * Only used as a response to the onHeadersReceived event. + * If set, the server is assumed to have responded with these + * response headers instead. Only return responseHeaders if you really + * want to modify the headers in order to limit the number of conflicts + * (only one extension may modify responseHeaders for each request). + */ + responseHeaders?: HttpHeader[]; + /** + * Only used as a response to the onAuthRequired event. + * If set, the request is made using the supplied credentials. + */ + authCredentials?: AuthCredentials; + /** + * Only used as a response to the onBeforeSendHeaders event. + * If set, the request is made with these request headers instead. + */ + requestHeaders?: HttpHeader[]; + } + + interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { + /** The authentication scheme, e.g. Basic or Digest. */ + scheme: string; + /** The authentication realm provided by the server, if there is one. */ + realm?: string; + /** The server requesting authentication. */ + challenger: WebAuthChallenger; + /** True for Proxy-Authenticate, false for WWW-Authenticate. */ + isProxy: boolean; + } + + interface WebRequestBodyEvent extends chrome.events.Event<(details: WebRequestBodyDetails) => void> { + addListener(callback: (details: WebRequestBodyDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebRequestHeadersEvent extends chrome.events.Event<(details: WebRequestHeadersDetails) => void> { + addListener(callback: (details: WebRequestHeadersDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface _WebResponseHeadersEvent extends chrome.events.Event<(details: T) => void> { + addListener(callback: (details: T) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseHeadersEvent extends _WebResponseHeadersEvent { } + + interface WebResponseCacheEvent extends _WebResponseHeadersEvent { } + + interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent { } + + interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { + addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseErrorEvent extends _WebResponseHeadersEvent { } + + interface WebResponseErrorDetails extends WebResponseCacheDetails { + /** The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. */ + error: string; + } + + interface WebAuthChallenger { + host: string; + port: number; + } + /** * Interface which provides access to webRequest events on the guest page. * @see[chrome.webRequest]{@link http://developer.chrome.com/extensions/webRequest} @@ -9680,12 +9890,54 @@ declare namespace chrome { * @example const rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]); **/ interface WebRequestEventInterface { - onBeforeRequest: chrome.events.Event<(details: any) => void>; - onBeforeSendHeaders: chrome.events.Event<(details: any) => void>; - onSendHeaders: chrome.events.Event<(details: any) => void>; - onHeadersReceived: chrome.events.Event<(details: any) => void>; - onAuthRequired: chrome.events.Event<(details: any) => void>; - + /** Fired when a request is about to occur. */ + onBeforeRequest: WebRequestBodyEvent; + /** + * Fired before sending an HTTP request, once the request headers are available. + * This may occur after a TCP connection is made to the server, but before any HTTP data is sent. + */ + onBeforeSendHeaders: WebRequestHeadersEvent; + /** + * Fired just before a request is going to be sent to the server + * (modifications of previous onBeforeSendHeaders callbacks + * are visible by the time onSendHeaders is fired). + */ + onSendHeaders: WebRequestHeadersEvent; + /** Fired when HTTP response headers of a request have been received. */ + onHeadersReceived: WebResponseHeadersEvent; + /** + * Fired when an authentication failure is received. + * The listener has three options: it can provide authentication credentials, + * it can cancel the request and display the error page, or it can take no + * action on the challenge. If bad user credentials are provided, this may be + * called multiple times for the same request. + */ + onAuthRequired: WebAuthenticationChallengeEvent; + /** + * Fired when the first byte of the response body is received. + * For HTTP requests, this means that the status line and + * response headers are available. + */ + onResponseStarted: WebResponseCacheEvent; + /** Fired when a server-initiated redirect is about to occur. */ + onBeforeRedirect: WebRedirectionResponseEvent; + /** Fired when a request is completed. */ + onCompleted: WebResponseCacheEvent; + /** Fired when an error occurs. */ + onErrorOccured: WebResponseErrorEvent; + /** + * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onRequest: webViewRequest.OnRequestEvent; + /** + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onMessage: webViewRequest.OnMessageEvent; } /** * Defines the how zooming is handled in the webview. @@ -9913,6 +10165,117 @@ declare namespace chrome { } } + namespace webRequest { + type ResourceType = + "main_frame" | "sub_frame" | "stylesheet" | + "script" | "image" | "font" | "object" | + "xmlhttprequest" | "ping" | "csp_report" + | "media" | "websocket" | "other"; + } + + namespace webViewRequest { + type Stage = "onBeforeRequest" | "onBeforeSendHeaders" | "onHeadersReceived" | "onAuthRequired"; + interface HeaderFilter { + /** Matches if the header name starts with the specified string. */ + namePrefix?: string; + /** Matches if the header name ends with the specified string. */ + nameSuffix?: string; + /** Matches if the header name contains all of the specified strings. */ + nameContains?: string | string[]; + /** Matches if the header name is equal to the specified string. */ + nameEquals?: string; + /** Matches if the header value starts with the specified string. */ + valuePrefix?: string; + /** Matches if the header value ends with the specified string. */ + valueSuffix?: string; + /** Matches if the header value contains all of the specified strings. */ + valueContains?: string | string[]; + /** Matches if the header value is equal to the specified string. */ + valueEquals?: string; + + } + interface RequestMatcherFields { + /** Matches if the conditions of the UrlFilter are fulfilled for the URL of the request. */ + url?: chrome.events.UrlFilter; + /** + * Matches if the conditions of the UrlFilter are fulfilled for the + * 'first party' URL of the request. The 'first party' URL of a request, + * when present, can be different from the request's target URL, and + * describes what is considered 'first party' for the sake of third-party + * checks for cookies. + */ + firstPartyForCookiesUrl?: chrome.events.UrlFilter; + /** + * Matches if the request type of a request is contained in the list. + * Requests that cannot match any of the types will be filtered out. */ + resourceType?: webRequest.ResourceType[]; + /** + * Matches if the MIME media type of a response + * (from the HTTP Content-Type header) + * is contained in the list. */ + contentType?: string[]; + /** + * Matches if the MIME media type of a response + * (from the HTTP Content-Type header) is not contained in the list. + */ + excludeContentType?: string[]; + /** + * Matches if some of the request headers is matched by one of the HeaderFilters. + */ + requestHeaders?: HeaderFilter[]; + /** + * Matches if none of the request headers is matched by any of the HeaderFilters. + */ + excludeRequestHeaders?: HeaderFilter[]; + /** + * Matches if some of the response headers is matched by one of the HeaderFilters. + */ + responseHeaders?: HeaderFilter[]; + /** + * Matches if none of the response headers is matched by any of the HeaderFilters. + */ + excludeResponseHeaders?: HeaderFilter[]; + /** + * If set to true, matches requests that are subject to third-party cookie policies. + * If set to false, matches all other requests. + */ + thirdPartyForCookies?: boolean; + /** + * Contains a list of strings describing stages. + * If this attribute is present, then it limits the applicable stages to those listed. + * Note that the whole condition is only applicable in stages compatible with all attributes. */ + stages?: Stage[]; + } + /** + * @description Matches network events by various criteria. + */ + export class RequestMatcher implements RequestMatcherFields { + /** + * Matches network events by various criteria. + * @param criterias Search using these criterias + */ + constructor (criterias: RequestMatcherFields); + } + export class CancelRequest { } + /** Declarative event action that redirects a network request. */ + export class RedirectRequest { + /** + * Declarative event action that redirects a network request. + * @param redirectUrl Destination to where the request is redirected. + */ + constructor (redirectUrl: string); + } + + /** @todo TODO add extra supported actions */ + + interface OnRequestEvent { + /** @todo TODO */ + } + interface OnMessageEvent { + /** @todo TODO */ + } + } + ///////////// // METHODS // ///////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 1b4c03f64d..36a198a9e4 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1113,8 +1113,21 @@ wve.addEventListener('loadstart', (ev) => { return; }); wve.addEventListener('zoomchange', (ev) => { - return ev.newZoomFactor || ev.oldZoomFactor; + return ev.newzoomFactor || ev.oldzoomFactor; }); wve.addEventListener('loadredirect', (ev) => { return ev.newUrl || ev.oldUrl; }); + +wve.request.onBeforeRequest.addListener( + function (details) { return { cancel: true }; }, + { urls: ["*://www.evil.com/*"] }, + ["blocking"]); + +var rule = { + conditions: [ + new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) + ], + actions: [new chrome.webViewRequest.CancelRequest()] +}; +wve.request.onRequest.addRules([rule]); From ee0d392ca1cd95a564b5acf2e925b8c5387388d9 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 7 Aug 2018 11:48:11 +0200 Subject: [PATCH 037/289] webviewWebRequests: Typings + docs + tests --- types/chrome-apps/index.d.ts | 499 +++++++++++++++++++++++++++++--- types/chrome-apps/test/index.ts | 35 ++- 2 files changed, 495 insertions(+), 39 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index e76ae8652d..055bc41fa6 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2420,8 +2420,12 @@ declare namespace chrome { hasListeners(): boolean; } - /** Description of a declarative rule for handling events. */ - interface Rule { + /** + * Description of a declarative rule for handling events. + * @template T Type for conditions array, default: any. + * @template K Type for actions array, default: any. + */ + interface Rule { /** Identifier that allows referencing this rule. */ id?: string; @@ -2432,10 +2436,10 @@ declare namespace chrome { tags?: string[]; /** List of conditions that can trigger the actions. */ - conditions: any[]; + conditions: T[]; /** List of actions that are triggered if one of the condtions is fulfilled. */ - actions: any[]; + actions: K[]; /** * Optional priority of this rule. @@ -8834,23 +8838,6 @@ declare namespace chrome { reason: ExitEventReason; } - /** Description of a declarative rule for handling events. */ - interface Rule { - /** Optional priority of this rule. Defaults to 100. */ - priority?: integer; - /** List of conditions that can trigger the actions. */ - conditions: any[]; - /** Optional identifier that allows referencing this rule. */ - id?: string; - /** List of actions that are triggered if one of the condtions is fulfilled. */ - actions: any[]; - /** - * Tags can be used to annotate rules and perform operations on sets of rules.¨ - * @since Chrome 28 - */ - tags?: string[]; - } - /** * 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. */ @@ -9783,7 +9770,7 @@ declare namespace chrome { windowId?: number; } - export interface AuthCredentials { + interface AuthCredentials { username: string; password: string; } @@ -10249,31 +10236,469 @@ declare namespace chrome { /** * @description Matches network events by various criteria. */ - export class RequestMatcher implements RequestMatcherFields { - /** - * Matches network events by various criteria. - * @param criterias Search using these criterias - */ - constructor (criterias: RequestMatcherFields); + class RequestMatcher { + protected readonly typeGuard: 'RequestMatcher'; + constructor (parameters?: RequestMatcherFields); + public readonly instanceType: string; } - export class CancelRequest { } + + /** Declarative event action that cancels a network request. */ + class CancelRequest { + protected readonly typeGuard: 'CancelRequest'; + public readonly instanceType: string; + } + + interface RedirectRequestParams { + /** Destination to where the request is redirected. */ + redirectUrl: string; + } + /** Declarative event action that redirects a network request. */ - export class RedirectRequest { + class RedirectRequest { + protected readonly typeGuard: 'RedirectRequest'; + constructor (parameters: RedirectRequestParams); + public readonly instanceType: string; + } + + /** Declarative event action that redirects a network request to a transparent image. */ + class RedirectToTransparentImage { + protected readonly typeGuard: 'RedirectToTransparentImage'; + public readonly instanceType: string; + } + + /** Declarative event action that redirects a network request to an empty document. */ + class RedirectToEmptyDocument { + protected readonly typeGuard: 'RedirectToEmptyDocument'; + public readonly instanceType: string; + } + + interface RedirectByRegExParams { /** - * Declarative event action that redirects a network request. - * @param redirectUrl Destination to where the request is redirected. + * A match pattern that may contain capture groups. + * Capture groups are referenced in the Perl syntax ($1, $2, ...) + * instead of the RE2 syntax (\1, \2, ...) in order to be closer + * to JavaScript Regular Expressions. */ - constructor (redirectUrl: string); + from: string; + /** Destination pattern. @see from */ + to: string; } - /** @todo TODO add extra supported actions */ + /** + * Redirects a request by applying a regular expression on the URL. + * The regular expressions use the RE2 syntax. + * @see[RE2 syntax]{@link https://github.com/google/re2/blob/master/doc/syntax.txt} + */ + class RedirectByRegEx { + protected readonly typeGuard: 'RedirectByRegEx'; + constructor (parameters: RedirectByRegExParams); + public readonly instanceType: string; + } + interface SetRequestHeaderParams { + /** HTTP request header name */ + name: string; + /** HTTP request header value */ + value: string; + } + + /** + * Sets the request header of the specified name to the specified value. + * If a header with the specified name did not exist before, a new one is created. + * Header name comparison is always case-insensitive. + * Each request header name occurs only once in each request. + */ + class SetRequestHeader { + protected readonly typeGuard: 'SetRequestHeader'; + constructor (parameters: SetRequestHeaderParams); + public readonly instanceType: string; + } + + interface RemoveRequestHeaderParams { + /** HTTP request header name (case-insensitive) */ + name: string; + } + + /** + * Removes the request header of the specified name. + * Do not use SetRequestHeader and RemoveRequestHeader with + * the same header name on the same request. + * Each request header name occurs only once in each request. + */ + class RemoveRequestHeader { + protected readonly typeGuard: 'RemoveRequestHeader'; + constructor (parameters: RemoveRequestHeaderParams); + public readonly instanceType: string; + } + + interface AddResponseHeaderParams { + /** HTTP response header name */ + name: string; + /** HTTP response header value */ + value: string; + } + + /** + * Adds the response header to the response of this web request. + * As multiple response headers may share the same name, + * you need to first remove and then add a new + * response header in order to replace one. + */ + class AddResponseHeader { + protected readonly typeGuard: 'AddResponseHeader'; + constructor (parameters: AddResponseHeaderParams); + public readonly instanceType: string; + } + + interface RemoveResponseHeaderParams { + /** HTTP request header name (case-insensitive). */ + name: string; + /** HTTP request header value (case-insensitive). */ + value?: string; + } + + /** + * Removes all response headers of the specified names and values. + */ + class RemoveResponseHeader { + protected readonly typeGuard: 'RemoveResponseHeader'; + constructor (parameters: RemoveResponseHeaderParams); + public readonly instanceType: string; + } + + interface IgnoreRulesParams { + /** + * If set, rules with a lower priority than the specified value are ignored. + * This boundary is not persisted, it affects only rules and their actions + * of the same network request stage. + */ + lowerPriorityThan?: integer; + /** + * If set, rules with the specified tag are ignored. This ignoring is not persisted, + * it affects only rules and their actions of the same network request stage. + * Note that rules are executed in descending order of their priorities. + * This action affects rules of lower priority than the current rule. + * Rules with the same priority may or may not be ignored. + */ + hasTag?: string; + } + + /** + * Masks all rules that match the specified criteria. + */ + class IgnoreRules { + protected readonly typeGuard: 'IgnoreRules'; + constructor (parameters: IgnoreRulesParams); + public readonly instanceType: string; + } + + interface SendMessageParams { + /** + * The value that will be passed in the message attribute + * of the dictionary that is passed to the event handler. + */ + message: string; + } + + /** + * Triggers the webviewWebRequest.*OnMessageEvent* event which are used in webviews. + */ + class SendMessageToExtension { + protected readonly typeGuard: 'SendMessageToExtension'; + constructor (parameters: SendMessageParams); + public readonly instanceType: string; + } + + /** + * A filter or specification of a cookie in HTTP Requests. + */ + interface RequestCookie { + /** Name of a cookie. */ + name?: string; + /** Value of a AddRequestCookie, may be padded in double-quotes. */ + value?: string; + } + + /** + * A specification of a cookie in HTTP Responses. + */ + + interface ResponseCookie { + /** Name of a cookie. */ + name?: string; + /** Value of a cookie, may be padded in double-quotes. */ + value?: string; + /** Value of the Expires cookie attribute. */ + expires?: string; + /** Value of the Max-Age cookie attribute */ + maxAge?: number; + /** Value of the Domain cookie attribute. */ + domain?: string; + /** Value of the Path cookie attribute. */ + path?: string; + /** Existence of the Secure cookie attribute. */ + secure?: string; + /** Existence of the HttpOnly cookie attribute. */ + httpOnly?: string; + } + + /** A filter of a cookie in HTTP Responses. */ + interface FilterResponseCookie { + /** Name of a cookie. */ + name?: string; + /** Value of a cookie, may be padded in double-quotes. */ + value?: string; + /** Value of the Expires cookie attribute. */ + expires?: string; + /** Value of the Max-Age cookie attribute */ + maxAge?: double; + /** Value of the Domain cookie attribute. */ + domain?: string; + /** Value of the Path cookie attribute. */ + path?: string; + /** Existence of the Secure cookie attribute. */ + secure?: string; + /** Existence of the HttpOnly cookie attribute */ + httpOnly?: string; + /** + * Inclusive upper bound on the cookie lifetime (specified in seconds after current time). + * Only cookies whose expiration date-time is in the interval [now, now + ageUpperBound] + * fulfill this criterion. Session cookies and cookies whose expiration date-time is + * in the past do not meet the criterion of this filter. The cookie lifetime is calculated + * from either 'max-age' or 'expires' cookie attributes. If both are specified, 'max-age' + * is used to calculate the cookie lifetime. + */ + ageUpperBound?: integer; + /** + * Inclusive lower bound on the cookie lifetime (specified in seconds after current time). + * Only cookies whose expiration date-time is set to 'now + ageLowerBound' or later fulfill + * this criterion. Session cookies do not meet the criterion of this filter. The cookie + * lifetime is calculated from either 'max-age' or 'expires' cookie attributes. If both + * are specified, 'max-age' is used to calculate the cookie lifetime. + */ + ageLowerBound?: integer; + /** + * Filters session cookies. + * Session cookies have no lifetime specified in any of 'max-age' or 'expires' attributes. + */ + sessionCookie?: boolean; + } + + /** + * @private + * @template T Type of cookie + */ + interface AddCookie { + /** + * Cookie to be added to the request. + * No field may be undefined. + * The name and value need to be specified. + */ + cookie: T; + } + + /** + * Adds a cookie to the request or overrides a cookie, in case another cookie of the same name exists already. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class AddRequestCookie { + protected readonly typeGuard: 'AddRequestCookie'; + constructor (parameters: AddCookie); + public readonly instanceType: string; + } + + + /** + * Adds a cookie to the response or overrides a cookie, in case another cookie of the same name exists already. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class AddResponseCookie { + protected readonly typeGuard: 'AddResponseCookie'; + constructor (parameters: AddCookie); + public readonly instanceType: string; + } + + /** + * @private + * @template T First parameter type + * @template K Second parameter type + */ + interface EditCookieParams { + /** + * Filter for cookies that will be modified. + * All empty entries are ignored. + */ + filter: T; + /** + * Attributes that shall be overridden in cookies that machted the filter + * Attributes that are set to an empty string are removed. + */ + modification: K; + } + + /** + * Edits one or more cookies of request. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class EditRequestCookie { + protected readonly typeGuard: 'EditRequestCookie'; + /** + * @param filter + * @param modification Attributes that shall be overridden in cookies that machted the filter. + * Attributes that are set to an empty string are removed. + */ + constructor (parameters: EditCookieParams); + public readonly instanceType: string; + } + + /** + * Edits one or more cookies of response. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class EditResponseCookie { + protected readonly typeGuard: 'EditResponseCookie'; + /** + * @param filter Filter for cookies that will be modified.All empty entries are ignored. + * @param modification + */ + constructor (parameter: EditCookieParams); + public readonly instanceType: string; + } + + /** + * Removes one or more cookies of request. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class RemoveRequestCookie { + protected readonly typeGuard: 'RemoveRequestCookie'; + constructor (parameters: RemoveCookieParams); + public readonly instanceType: string; + } + + + + /** + * @private + * @template T Filter type + */ + interface RemoveCookieParams { + /** + * Filter for cookies that will be removed. + * All empty entries are ignored. + */ + filter: T; + } + + /** + * Removes one or more cookies of response. + * Note that it is preferred to use the Cookies API because this is computationally less expensive. + */ + class RemoveResponseCookie { + protected readonly typeGuard: 'RemoveResponseCookie'; + constructor (parameters: RemoveCookieParams); + public readonly instanceType: string; + } + + /** Supported conditions */ + type OnRequestConditions = + RequestMatcher; + + /** Supported actions */ + type OnRequestActions = + AddRequestCookie | + AddResponseCookie | + AddResponseHeader | + CancelRequest | + EditRequestCookie | + EditResponseCookie | + RedirectRequest | + RedirectToTransparentImage | + RedirectToEmptyDocument | + RedirectByRegEx | + RemoveRequestCookie | + RemoveResponseCookie | + RemoveRequestHeader | + RemoveResponseHeader | + SetRequestHeader | + SendMessageToExtension | + IgnoreRules; + + /** + * Description of a declarative rule for handling events. + * With correct types for the onRequest event. + */ + interface OnRequestRule extends chrome.events.Rule { } + + /** + * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. + */ interface OnRequestEvent { - /** @todo TODO */ + /** + * Registers rules to handle events. + * @param rules Rules to be registered. These do not replace previously registered rules. + * @param [callback] Called with registered rules. + */ + addRules(rules: OnRequestRule[], callback?: (rules: OnRequestRule[]) => void): void; + + /** + * Returns currentlt registered rules. + * @param callback Called with registered rules. + */ + getRules(callback: (rules: OnRequestRule[]) => void): void; + + /** + * Returns currentlt registered rules. + * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are returned. + * @param callback Called with registered rules. + */ + getRules(ruleIdentifiers: string[], callback: (rules: OnRequestRule[]) => void): void; + + /** + * Unregisters currently registered rules. + * @param [ruleIdentifiers] If an array is passed, only rules with identifiers contained in this array are unregistered. + * @param [callback] Called when rules were unregistered. + */ + removeRules(ruleIdentifiers?: string[], callback?: () => void): void; } - interface OnMessageEvent { - /** @todo TODO */ + + interface OnMessageEventDetails { + /** The message sent by the calling script. */ + message: string; + /** The stage of the network request during which the event was triggered. */ + stage: Stage; + /** + * The ID of the request. + * Request IDs are unique within a browser session. + * As a result, they could be used to relate different events of the same request. + */ + requestId: string; + /** URL */ + url: string; + /** Standard HTTP method. */ + method: string; + /** + * The value 0 indicates that the request happens in the main frame; + * a positive value indicates the ID of a subframe in which the request happens. + * If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), + * frameId indicates the ID of this frame, not the ID of the outer frame. + * Frame IDs are unique within a tab. + */ + frameId: integer; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: integer; + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ + tabId: integer; + /** How the requested resource will be used. */ + type: webRequest.ResourceType; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: double; } + + /** + * Fired when a message is sent via **declarativeWebRequest.SendMessageToExtension** + * from an action of the declarative web request API. + */ + interface OnMessageEvent extends chrome.events.Event<(details: OnMessageEventDetails) => void> { } } ///////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 36a198a9e4..ada6d85ebf 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1124,10 +1124,41 @@ wve.request.onBeforeRequest.addListener( { urls: ["*://www.evil.com/*"] }, ["blocking"]); -var rule = { +const rule: chrome.webViewRequest.OnRequestRule = { conditions: [ + // new chrome.webViewRequest.CancelRequest(), // This is incompatible - should break it :) new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], - actions: [new chrome.webViewRequest.CancelRequest()] + actions: [ + new chrome.webViewRequest.CancelRequest(), + new chrome.webViewRequest.IgnoreRules({ + 'lowerPriorityThan': 1000 + }), + new chrome.webViewRequest.SendMessageToExtension({ + 'message': JSON.stringify({ + 'type': 'error', + 'action': 'cancelled' + }) + }) + ] }; + +new chrome.webViewRequest.RequestMatcher({ + 'url': { 'urlMatches': '.*' }, + 'resourceType': [ + 'image' + ] +}); + +new chrome.webViewRequest.RedirectRequest({ redirectUrl: 'http://127.0.0.1' }); + +new chrome.webViewRequest.RedirectByRegEx({ + 'from': '^.*:\/\/([^/]*)[^#?]*\/([^#?]*)([#?].*)?$', + 'to': 'http://dummyimage.com/xga/000/0f0.png&text=BLOCKED:$1/.../$2' +}); + +new chrome.webViewRequest.RequestMatcher({ + 'url': { 'hostSuffix': 'dummyimage.com' } +}); + wve.request.onRequest.addRules([rule]); From 3bc19aca5f133975b560c83f62f8f8e1bfc11101 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 7 Aug 2018 13:05:51 +0200 Subject: [PATCH 038/289] chrome.alarms test + make helper types double and integer unique --- types/chrome-apps/index.d.ts | 30 ++++++++++++++++++------------ types/chrome-apps/test/index.ts | 28 ++++++++++++++++++---------- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 055bc41fa6..eb2e4a05c3 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -26,13 +26,19 @@ declare namespace chrome { /** * Integer + * - + * Chrome uses JS number, but internally requires an integer or double. + * This is a helper type to prevent mixup. */ - type integer = number; + type integer = number | 'integer'; + /** * Double + * - + * Chrome uses JS number, but internally requires an integer or double. + * This is a helper type to prevent mixup. */ - type double = number; - + type double = number | 'double'; //////////////////////////// // Accessibility Features // @@ -9659,17 +9665,17 @@ declare namespace chrome { /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ requestId: string; /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ - frameId: number; + frameId: integer; /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ - parentFrameId: number; + parentFrameId: integer; /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ - tabId: number; + tabId: integer; /** * How the requested resource will be used. */ type: webRequest.ResourceType; /** The time when this signal is triggered, in milliseconds since the epoch. */ - timeStamp: number; + timeStamp: double; /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. * @since Since Chrome 63. */ @@ -9730,7 +9736,7 @@ declare namespace chrome { * Standard HTTP status code returned by the server. * @since Chrome 43. */ - statusCode: number; + statusCode: integer; } interface WebResponseHeadersDetails extends WebResponseDetails { @@ -9758,7 +9764,7 @@ declare namespace chrome { /** An object describing filters to apply to webRequest events. */ interface RequestFilter { /** Optional. */ - tabId?: number; + tabId?: integer; /** * A list of request types. Requests that cannot match any of the types will be filtered out. */ @@ -9767,7 +9773,7 @@ declare namespace chrome { urls: string[]; /** Optional. */ - windowId?: number; + windowId?: integer; } interface AuthCredentials { @@ -9853,7 +9859,7 @@ declare namespace chrome { interface WebAuthChallenger { host: string; - port: number; + port: integer; } /** @@ -10431,7 +10437,7 @@ declare namespace chrome { /** Value of the Expires cookie attribute. */ expires?: string; /** Value of the Max-Age cookie attribute */ - maxAge?: number; + maxAge?: integer; /** Value of the Domain cookie attribute. */ domain?: string; /** Value of the Path cookie attribute. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index ada6d85ebf..90fe73368c 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -561,6 +561,14 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { } } + +// ALARMS + +chrome.alarms.create('name', { + delayInMinutes: 10 +}) + + // BLUETOOTH // BLUETOOTH SOCKET // BLUETOOTH LE @@ -594,7 +602,7 @@ var connectToDevice = (result: chrome.bluetooth.Device[]) => { chrome.bluetoothSocket.connect( socket.socketId, device.address, kUUID, - () => connectCallback(socket) + () => connectCallback(socket)) }); } }; @@ -791,7 +799,7 @@ chrome.runtime.sendMessage( // SOCKETS // https://developer.chrome.com/apps/sockets_tcp function test_socketsTcp(): void { - var socketId: number = 0; + var socketId: chrome.integer = 0; var properties: chrome.sockets.SocketProperties = {}; var buffer: ArrayBuffer = new ArrayBuffer(256); @@ -813,14 +821,14 @@ function test_socketsTcp(): void { chrome.sockets.tcp.setPaused(socketId, true, () => { }); // setKeepAlive - chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); - chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, (result) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result) => { }); // setNoDelay - chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setNoDelay(socketId, true, (result) => { }); // connect - chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { }); + chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result) => { }); // disconnect chrome.sockets.tcp.disconnect(socketId); @@ -878,7 +886,7 @@ function testSocketsTcpTypes(): void { // https://developer.chrome.com/apps/sockets_udp function test_socketsUdp(): void { - var socketId: number = 0 + var socketId: chrome.integer = 0 var properties: chrome.sockets.SocketProperties = {}; var buffer: ArrayBuffer = new ArrayBuffer(256); @@ -967,7 +975,7 @@ function testSocketsUdpTypes(): void { // https://developer.chrome.com/apps/sockets_tcpServer function test_socketsTcpServer(): void { - var socketId: number = 0; + var socketId: chrome.integer = 0; var properties: chrome.sockets.tcpServer.SocketProperties = {}; var buffer: ArrayBuffer = new ArrayBuffer(256); @@ -989,8 +997,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) => { }); + chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, 128, (result) => { }); // disconnect chrome.sockets.tcp.disconnect(socketId); From 58fbd4a07a2ba5e096011d4e10960e6429e15f31 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 7 Aug 2018 16:04:40 +0200 Subject: [PATCH 039/289] Cleanup + fixed some todos --- types/chrome-apps/index.d.ts | 1512 ++----------------------------- types/chrome-apps/test/index.ts | 35 +- types/chrome-apps/webview.d.ts | 1368 ++++++++++++++++++++++++++++ 3 files changed, 1485 insertions(+), 1430 deletions(-) create mode 100644 types/chrome-apps/webview.d.ts diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index eb2e4a05c3..178e875593 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5,6 +5,7 @@ // TypeScript Version: 2.8 /// +/// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WebView ref // @@ -22,7 +23,16 @@ declare namespace chrome { /** @deprecated Should never be used, used to guide migrations. */ type deprecated = never; - // Not proper types, but used to give the programmer a hint // + /** + * Convert constant and variables that function as enums to string literals. + * Makes it possible to use both the enum and string. + * String enums are a combination of 'enum type' and string literal type. + */ + type IDict = F; + type ToStringLiteral< + C extends Object, + K = keyof C, + V = K extends keyof C ? Exclude : never> = IDict; /** * Integer @@ -32,6 +42,11 @@ declare namespace chrome { */ type integer = number | 'integer'; + /// + /// BigInt is supported in Chrome now, but not in the api. + /// TypeScript doesn't support it either, so till then, use helper types. + /// + /** * Double * - @@ -302,9 +317,6 @@ declare namespace chrome { * and can shut down the app at anytime. */ namespace app.runtime { - /** - * @todo TODO UNDOCUMENTED? - */ enum PlayStoreStatus { ENABLED = 'enabled', AVAILABLE = 'available', @@ -808,13 +820,25 @@ declare namespace chrome { * This API is currently only implemented for ChromeOS. */ namespace audio { - 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'; + '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. */ @@ -854,29 +878,6 @@ declare namespace chrome { */ level?: integer; } - /** @todo TODO INTEGRATE */ - interface OnLevelChangedEvent { - addListener(callback: (event: { - deviceId: string, - level: integer - }) => void): void; - } - /** @todo TODO INTEGRATE */ - interface OnMuteChangedEvent { - 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: - * function(array of AudioDeviceInfo devices) {...}; - * @param {(devices: AudioDeviceInfo[]) => void} callback `devices` contains a list of all present audio devices after the change. - */ - addListener(callback: (devices: AudioDeviceInfo[]) => void): void; - } /** * Device properties by which to filter the list of returned audio devices. If the filter is not set or set to {}, returned device list will contain all available audio devices. */ @@ -901,23 +902,32 @@ declare namespace chrome { function setProperties(id: string, properties: SetDeviceProperties, callback: () => void): void; /** * 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)=> void} callback Callback reporting whether mute is set or not for specified stream type. + * @param streamType Stream type for which mute state should be fetched. + * @param callback Callback reporting whether mute is set or not for specified stream type. */ function getMute(streamType: StreamType, callback: (value: boolean) => void): void; /** * 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 {()=> void} [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; + * @param streamType Stream type for which mute state should be set. + * @param isMuted New mute value. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; */ function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; + /** Fired when sound level changes for an active audio device. */ - 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. */ - const onMuteChanged: OnMuteChangedEvent; - /** Fired when audio devices change, either new devices being added, or existing devices being removed. */ - const onDeviceListChanged: OnDeviceListChangedEvent; + const onLevelChanged: chrome.events.Event<(deviceId: string, level: integer) => void>; + /** + * 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. + */ + const onMuteChanged: chrome.events.Event<(streamType: StreamType[], isMuted: boolean) => void>; + /** + * Fired when audio devices change, either new devices being added, + * or existing devices being removed. + * callback `devices` contains a list of all present audio devices after the change. + */ + const onDeviceListChanged: chrome.events.Event<(devices: AudioDeviceInfo[]) => void>; } /////////////// @@ -5722,24 +5732,36 @@ declare namespace chrome { const onAdded: PermissionsAddedEvent; } - //////////////////// - // Power - //////////////////// + /////////// + // Power // + /////////// /** * Use the chrome.power API to override the system's power management features. - * Permissions: 'power' + * @requires Permissions: 'power' * @since Chrome 27. */ 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. */ - function requestKeepAwake(level: string): void; + /** @enum */ + const Level: { + /** Prevent the system from sleeping in response to user inactivity. */ + SYSTEM: 'system', + /** Prevent the display from being turned off or dimmed or the system from sleeping in response to user inactivity. */ + DISPLAY: 'display' + } + /** + * Requests that power management be temporarily disabled. + * @param level 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. + * @see Enum: chrome.power.Level + */ + function requestKeepAwake(level: ToStringLiteral): void; /** Releases a request previously made via requestKeepAwake(). */ function releaseKeepAwake(): void; } - //////////////////// - // Printer Provider - //////////////////// + ////////////////////// + // Printer Provider // + ////////////////////// /** * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. * Permissions: 'printerProvider' @@ -6104,6 +6126,18 @@ declare namespace chrome { send?: SocketPermissionOptions | string; } + interface WebViewPartition { + name: string; + /** + * Path to files, relative, absolute or pattern + * @example + * ["local_*.html", "*.png", "*.js"] + * ["img/epic.html"] + * + */ + accessible_resources: string[]; + } + /** * The top-level object can't have additionalProperties. @@ -6468,20 +6502,9 @@ declare namespace chrome { * @see[Accessing packaged resources]{@link https://developer.chrome.com/apps/tags/webview#local_resources} */ webview?: { - partitions?: { - name: string; - /** - * Path to files, relative, absolute or pattern - * @example - * ["local_*.html", "*.png", "*.js"] - * ["img/epic.html"] - * - */ - accessible_resources: string[]; - }[] + /** Webview partition list */ + partitions: WebViewPartition[] } - /** @todo TODO */ - [key: string]: any; } /** @@ -8798,1365 +8821,7 @@ declare namespace chrome { } - ///////////////// - // 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. - */ - namespace webview { - /** 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). - * @default 0 - */ - since?: integer; - } - interface WindowEvent extends chrome.events.Event<() => void> { } - - interface ConsoleEvent extends Event { - /** The severity level of the log message. Ranges from 0 to 4. */ - level: integer; - /** The logged message contents.*/ - message: string; - /** The line number of the message source.*/ - line: integer; - /** A string identifying the resource which logged the message. */ - sourceId: string; - } - - type ExitEventReason = - 'normal' | - 'abnormal' | - 'crash' | - 'kill'; - interface ExitEvent extends Event { - /** Chrome's internal ID of the process that exited. */ - processID: integer; - /** String indicating the reason for the exit. */ - reason: ExitEventReason; - } - - /** - * 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 { - /** - * 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, - /** - * JavaScript or CSS file to inject. - */ - file?: string - } - - /** - * WebView element from html - */ - 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. - * The src attribute cannot be cleared or removed once it has been set, unless the webview is removed from the DOM. - * 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. - * 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. - * 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. */ - contextMenus: webview.ContextMenus; - /** - * 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. - */ - addEventListener(type: 'close', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; - /** - * 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: 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: - * @example - * webview.addEventListener('contentload', function() { - * webview.executeScript({ code: 'document.body.style.fontSize = '42px'' }) - * }); - */ - addEventListener(type: 'contentload', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; - /** - * 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. - */ - 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: 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: 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: 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: 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: LoadRedirect) => void, useCapture?: boolean): void; - /** - * Fired when a load has begun. - */ - 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. - * 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. - */ - addEventListener(type: 'loadstop', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; - /** - * 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); - * }); - */ - 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. - * 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(); - * } - * }); - */ - 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: 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: 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: ProcessUnresponsive) => void, useCapture?: boolean): void; - /** Fired when the page's zoom changes. */ - addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: ZoomChange) => void, useCapture?: boolean): void; - /** - * Queries audio state. - * @since Chrome 62. - **/ - getAudioState(callback: (audible: boolean) => void): void; - - /** - * Sets audio mute state of the webview. - * @param mute Mute audio value - * @since Chrome 62. - */ - setAudioMuted(mute: boolean): void; - - /** - * Queries whether audio is muted. - * @since Chrome 62. - */ - isAudioMuted(callback: (muted: boolean) => void): void; - - /** - * Captures the visible region of the webview. - * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. - * May be assigned to the 'src' property of an HTML Image element for display. - * @since Chrome 50. - */ - captureVisibleRegion(callback: (dataUrl: string) => void): void; - /** - * Captures the visible region of the webview. - * @param options Extension type - * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. - * May be assigned to the 'src' property of an HTML Image element for display. - * @since Chrome 50. - */ - captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; - - /** - * Adds content script injection rules to the webview. - * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. - * You can programmatically add rules or update existing rules. - * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. - * @example - * webview.addContentScripts([ - * { - * name: 'myRule', - * matches: ['http://www.foo.com/*'], - * css: { files: ['mystyles.css'] }, - * js: { files: ['jquery.js', 'myscript.js'] }, - * run_at: 'document_start' - * }, - * { - * name: 'anotherRule', - * matches: ['http://www.bar.com/*'], - * js: { code: 'document.body.style.backgroundColor = 'red';' }, - * run_at: 'document_end' - * }]); - * ... - * // Navigates webview. - * webview.src = 'http://www.foo.com'; - * - * @description - * You can defer addContentScripts call until you needs to inject scripts. - * The following example shows how to overwrite an existing rule. - * @example - * webview.addContentScripts([{ - * name: 'rule', - * matches: ['http://www.foo.com/*'], - * js: { files: ['scriptA.js'] }, - * run_at: 'document_start'}]); - * - * // Do something. - * webview.src = 'http://www.foo.com/*'; - * ... - * // Overwrite 'rule' defined before. - * webview.addContentScripts([{ - * name: 'rule', - * matches: ['http://www.bar.com/*'], - * js: { files: ['scriptB.js'] }, - * run_at: 'document_end'}]); - * @description - * If webview has been naviagted to the origin (e.g., foo.com) and - * calls webview.addContentScripts to add 'myRule', - * you need to wait for next navigation to make the scripts injected. - * If you want immediate injection, executeScript will do the right thing. - * Rules are preserved even if the guest process crashes - * or is killed or even if the webview is reparented. - * Refer to the /extensions/content_scripts documentation for more details. - * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. - * @since Chrome 44. - */ - addContentScripts(contentScriptList: ContentScriptDetails[]): void; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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 Called after the data has been successfully cleared. - * @since Chrome 33. - */ - clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; - - /** - * 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] Called after all the JavaScript has been executed. - */ - executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; - - /** - * Initiates a find-in-page request. - * @param searchText The string to find in the page. - * @param [options] Options for the find request. - * @param [callback] Called after all find results have been returned for this find request. - * Provides optionally: - * results: Contains all of the results of the find request. - * results can be omitted if it is not utilized in the callback function body; - * e.g. if the callback is only used to discern when the find request has completed. - */ - find(searchText: string, options?: FindOptions, callback?: (results?: FindCallbackResults) => void): void; - - /** - * Navigates forward one history entry if possible. Equivalent to go(1). - * @param [callback] Called after the navigation has either failed or completed successfully. - * Provides *success* which indicates whether the navigation was successful. - */ - forward(callback?: (success: boolean) => void): void; - - /** - * 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(): integer; - - /** - * Returns the user agent string used by the webview for guest page requests. - * @since Since Chrome 33. - */ - getUserAgent(): string; - - /** - * Gets the current zoom factor. - * @param callback Called after the current zoom factor is retrieved. Provides the current zoom factor. - * @since Chrome 36. - */ - getZoom(callback: (zoomFactor: double) => void): void; - - /** - * Gets the current zoom mode. - * @param callback Called with the webview's current zoom mode. - * @since Since Chrome 43. - */ - getZoomMode(callback: (ZoomMode: ZoomMode) => void): void; - - /** - * 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] Called after the navigation has either failed or completed successfully. - * Provides a boolean, *success*, which indicates whether the navigation was successful. - */ - go(relativeIndex: integer, callback?: (success: boolean) => void): void; - - /** - * Injects CSS into the guest page. - * @param details Details of the CSS to insert. - * @param callback Called after the CSS has been inserted. - */ - insertCSS(details: InjectDetails, callback?: () => void): void; - - /** - * Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. - * @since Since Chrome 33. - */ - isUserAgentOverridden(): void; - - /** - * Prints the contents of the webview. - * This is equivalent to calling scripted print function from the webview itself. - * @since Since Chrome 38. - */ - print(): void; - - /** Reloads the current top-level page. */ - reload(): void; - - /** - * 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(); - * @param 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. - * @since Chrome 44. - */ - removeContentScripts(scriptNameList?: string[]): void; - - /** - * Override the user agent string used by the webview for guest page requests. - * @param userAgent The user agent string to use. - * @since Since Chrome 33. - */ - setUserAgentOverride(userAgent: string): void; - - /** - * 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] Called after the page has been zoomed. - * @since Since Chrome 36. - */ - setZoom(zoomFactor: double, callback?: () => void): void; - - /** - * Sets the zoom mode of the webview. - * @param ZoomMode Defines how zooming is handled in the webview. - * @param [callback] Called after the zoom mode has been changed. - * @since Since Chrome 43. - */ - setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; - - /** Stops loading the current webview navigation if in progress. */ - stop(): void; - - /** - * @todo TODO Fix action param - * Ends the current find session (clearing all highlighting) - * and cancels all find requests in progress. - * @param 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. - * @since Since Chrome 35. - */ - stopFinding(action?: 'clear' | 'keep' | 'activate'): void; - - /** - * 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 dataUrl The data URL to load. - * @param baseUrl The base URL that will be used for relative links. - * @param virtualUrl The URL that will be displayed to the user (in the address bar). - * @since Since Chrome 40. - */ - loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; - - /** - * 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; - } - - /** A set of data types. Missing properties are interpreted as false. */ - interface ClearDataTypeSet { - /** Websites' appcaches. */ - appcache?: boolean; - /** - * 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. - */ - 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. - **/ - 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 { - /** - * 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; - - /** JavaScript or CSS file to inject. */ - file?: string - } - /** The type of injection item: code or a set of files. */ - interface InjectionItems { - /** JavaScript code or CSS to be injected into matching pages. */ - code?: string - /** - * 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. **/ - interface ContentScriptDetails { - /** The name of the content script to inject. */ - name: string - - /** Specifies which pages this content script will be injected into. */ - matches: any[] - - /** Excludes pages that this content script would otherwise be injected into. */ - exclude_matches?: any[] - - /** JavaScript or CSS file to inject. */ - file?: string - } - /** The type of injection item: code or a set of files. */ - interface InjectionItems { - /** JavaScript code or CSS to be injected into matching pages. */ - code?: string - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * The soonest that the JavaScript or CSS will be injected into the tab. - * Defaults to 'document_idle'. - */ - run_at?: chrome.extensionTypes.RunAt; - - /** - * 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; - - /** - * Applied after matches to include only those URLs that also match this glob. - * Intended to emulate the @include Greasemonkey keyword. - */ - include_globs?: string[]; - - /** - * Applied after matches to exclude URLs that match this glob. - * Intended to emulate the @exclude Greasemonkey keyword. - */ - exclude_globs?: string[]; - } - /** @todo TODO Add documentation */ - interface ContextMenuCreateProperties { - - /** - * The type of menu item. Defaults to 'normal' if not specified. - */ - type?: chrome.contextMenus.ItemType; - - /** - * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. - */ - 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?: any[]; - - /** - * A function that will be called back when the menu item is clicked. - */ - onclick?: (info: any) => void - - /** - * The ID of a parent menu item; this makes the item a child of a previously added item. - */ - parentId?: integer | 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?: any[]; - - /** - * 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[]; - - /** - * Whether this context menu item is enabled or disabled. Defaults to true. - */ - enabled?: boolean; - } - /**@todo Add documentation */ - interface ContextMenuUpdateProperties { - /** The type of menu item. */ - type?: chrome.webview.ContextType; - - /** The text to be displayed in the item */ - title?: string; - - /** - * 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; - - /** - * List of contexts this menu item will appear in. - */ - contexts?: any[]; - - /** - * A function that will be called back when the menu item is clicked. - * @param callback - */ - onclick?: (info: any) => void; - - /** - * 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?: integer | 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.) - */ - documentUrlPatterns?: any[]; - - /** - * 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[]; - - /** - * Whether this context menu item is enabled or disabled. - */ - enabled?: boolean; - } - interface ContextMenus { - /** - * 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; - - /** - * 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: integer | string, updateProperties: object, callback?: () => void): void; - - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param [callback] - */ - remove(menuItemId: integer | string, callback?: () => void): void; - - /** - * Removes all context menu items added to this webview. - * @param [callback] - */ - removeAll(callback?: () => void): void; - - /** - * 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; - } - interface OnShowEvent { - /** Call this to prevent showing the context menu. */ - preventDefault: () => void; - } - interface ContentWindow { - /** - * 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 { - /** - * 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; - /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ - cancel(): void; - } - /** Contains all of the results of the find request. */ - interface FindCallbackResults { - /** The number of times searchText was matched on the page. */ - numberOfMatches: integer; - /** The ordinal number of the current match. */ - activeMatchOrdinal: integer; - /** Describes a rectangle around the active match in screen coordinates. */ - selectionRect: SelectionRect; - /** Indicates whether this find request was canceled. */ - canceled: boolean; - } - interface FindOptions { - /** - * Flag to find matches in reverse order. - * @default false - */ - backward?: boolean; - /** - * Flag to match with case-sensitivity. - * @default false - */ - matchCase?: boolean; - } - interface NewWindow { - /** - * 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: HTMLWebViewElement): void; - /** - * Cancel the new window request. - */ - discard(): void; - } - interface PermissionRequestHandler { - /** Allow the permission request. */ - allow(): void; - /** Deny the permission request. This is the default behavior if allow is not called. */ - deny(): void; - } - /** - * 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 { - /** Distance from the left edge of the screen to the left edge of the rectangle. */ - left: integer; - /** Distance from the top edge of the screen to the top edge of the rectangle. */ - top: integer; - /** Width of the rectangle. */ - width: integer; - /** Height of the rectangle. */ - height: integer; - } - - /** An HTTP Header, represented as an object containing a key and either a value or a binaryValue. */ - interface HttpHeader { - name: string; - value?: string; - binaryValue?: ArrayBuffer; - } - - interface ResourceRequest { - url: string; - /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ - requestId: string; - /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ - frameId: integer; - /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ - parentFrameId: integer; - /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ - tabId: integer; - /** - * How the requested resource will be used. - */ - type: webRequest.ResourceType; - /** The time when this signal is triggered, in milliseconds since the epoch. */ - timeStamp: double; - /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. - * @since Since Chrome 63. - */ - initiator?: string; - } - - interface WebRequestDetails extends ResourceRequest { - /** Standard HTTP method. */ - method: string; - } - - interface WebRequestHeadersDetails extends WebRequestDetails { - /** Optional. The HTTP request headers that are going to be sent out with this request. */ - requestHeaders?: HttpHeader[]; - } - - interface WebRequestBodyDetails extends WebRequestDetails { - /** - * Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'. - * @since Chrome 23. - */ - requestBody: WebRequestBody; - } - - /** - * Contains data uploaded in a URL request. - * @since Chrome 23. - */ - interface UploadData { - /** Optional. An ArrayBuffer with a copy of the data. */ - bytes?: ArrayBuffer; - /** Optional. A string with the file's path and name. */ - file?: string; - } - - interface WebRequestBody { - /** Optional. Errors when obtaining request body data. */ - error?: string; - /** - * Optional. - * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. - */ - formData?: { [key: string]: string[] }; - /** - * Optional. - * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. - */ - raw?: UploadData[]; - } - - interface WebRequestFullDetails extends WebRequestHeadersDetails, WebRequestBodyDetails { - } - - interface WebResponseDetails extends ResourceRequest { - /** HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line). */ - statusLine: string; - /** - * Standard HTTP status code returned by the server. - * @since Chrome 43. - */ - statusCode: integer; - } - - interface WebResponseHeadersDetails extends WebResponseDetails { - /** Optional. The HTTP response headers that have been received with this response. */ - responseHeaders?: HttpHeader[]; - /** standard HTTP method i.e. GET, POST, PUT, etc. */ - method: string; - } - - interface WebResponseCacheDetails extends WebResponseHeadersDetails { - /** - * Optional. - * The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address. - */ - ip?: string; - /** Indicates if this response was fetched from disk cache. */ - fromCache: boolean; - } - - interface WebRedirectionResponseDetails extends WebResponseCacheDetails { - /** The new URL. */ - redirectUrl: string; - } - - /** An object describing filters to apply to webRequest events. */ - interface RequestFilter { - /** Optional. */ - tabId?: integer; - /** - * A list of request types. Requests that cannot match any of the types will be filtered out. - */ - types?: chrome.webRequest.ResourceType[]; - /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ - urls: string[]; - - /** Optional. */ - windowId?: integer; - } - - interface AuthCredentials { - username: string; - password: string; - } - - /** Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests. */ - interface BlockingResponse { - /** - * If true, the request is cancelled. - * Used in onBeforeRequest, this prevents the request from being sent. */ - cancel?: boolean; - /** - * Only used as a response to the onBeforeRequest and onHeadersReceived events. - * If set, the original request is prevented from being sent/completed and is - * instead redirected to the given URL. Redirections to non-HTTP schemes such - * as data: are allowed. Redirects initiated by a redirect action use the - * original request method for the redirect, with one exception: If the - * redirect is initiated at the onHeadersReceived stage, then the redirect - * will be issued using the GET method. - */ - redirectUrl?: string; - /** - * Only used as a response to the onHeadersReceived event. - * If set, the server is assumed to have responded with these - * response headers instead. Only return responseHeaders if you really - * want to modify the headers in order to limit the number of conflicts - * (only one extension may modify responseHeaders for each request). - */ - responseHeaders?: HttpHeader[]; - /** - * Only used as a response to the onAuthRequired event. - * If set, the request is made using the supplied credentials. - */ - authCredentials?: AuthCredentials; - /** - * Only used as a response to the onBeforeSendHeaders event. - * If set, the request is made with these request headers instead. - */ - requestHeaders?: HttpHeader[]; - } - - interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { - /** The authentication scheme, e.g. Basic or Digest. */ - scheme: string; - /** The authentication realm provided by the server, if there is one. */ - realm?: string; - /** The server requesting authentication. */ - challenger: WebAuthChallenger; - /** True for Proxy-Authenticate, false for WWW-Authenticate. */ - isProxy: boolean; - } - - interface WebRequestBodyEvent extends chrome.events.Event<(details: WebRequestBodyDetails) => void> { - addListener(callback: (details: WebRequestBodyDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebRequestHeadersEvent extends chrome.events.Event<(details: WebRequestHeadersDetails) => void> { - addListener(callback: (details: WebRequestHeadersDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface _WebResponseHeadersEvent extends chrome.events.Event<(details: T) => void> { - addListener(callback: (details: T) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebResponseHeadersEvent extends _WebResponseHeadersEvent { } - - interface WebResponseCacheEvent extends _WebResponseHeadersEvent { } - - interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent { } - - interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { - addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebResponseErrorEvent extends _WebResponseHeadersEvent { } - - interface WebResponseErrorDetails extends WebResponseCacheDetails { - /** The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. */ - error: string; - } - - interface WebAuthChallenger { - host: string; - port: integer; - } - - /** - * 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 { - /** Fired when a request is about to occur. */ - onBeforeRequest: WebRequestBodyEvent; - /** - * Fired before sending an HTTP request, once the request headers are available. - * This may occur after a TCP connection is made to the server, but before any HTTP data is sent. - */ - onBeforeSendHeaders: WebRequestHeadersEvent; - /** - * Fired just before a request is going to be sent to the server - * (modifications of previous onBeforeSendHeaders callbacks - * are visible by the time onSendHeaders is fired). - */ - onSendHeaders: WebRequestHeadersEvent; - /** Fired when HTTP response headers of a request have been received. */ - onHeadersReceived: WebResponseHeadersEvent; - /** - * Fired when an authentication failure is received. - * The listener has three options: it can provide authentication credentials, - * it can cancel the request and display the error page, or it can take no - * action on the challenge. If bad user credentials are provided, this may be - * called multiple times for the same request. - */ - onAuthRequired: WebAuthenticationChallengeEvent; - /** - * Fired when the first byte of the response body is received. - * For HTTP requests, this means that the status line and - * response headers are available. - */ - onResponseStarted: WebResponseCacheEvent; - /** Fired when a server-initiated redirect is about to occur. */ - onBeforeRedirect: WebRedirectionResponseEvent; - /** Fired when a request is completed. */ - onCompleted: WebResponseCacheEvent; - /** Fired when an error occurs. */ - onErrorOccured: WebResponseErrorEvent; - /** - * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. - * This interface supports declarative webRequest rules through - * **onRequest** and **onMessage** events. - * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} - */ - onRequest: webViewRequest.OnRequestEvent; - /** - * This interface supports declarative webRequest rules through - * **onRequest** and **onMessage** events. - * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} - */ - onMessage: webViewRequest.OnMessageEvent; - } - /** - * 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. - * '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). - * 'disabled' - * > 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 { - /** - * 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; - /** The logged message contents. */ - message: string; - /** The line number of the message source. */ - line: integer; - /** A string identifying the resource which logged the message. */ - sourceId: string; - } - type DialogMessageType = - 'alert' | - 'confirm' | - 'prompt'; - - interface Dialog { - /** - * The type of modal dialog requested by the guest. - */ - messageType: DialogMessageType; - /** - * The text the guest attempted to display in the modal dialog. - */ - messageText: string; - /** - * An interface that can be used to respond to the guest's modal request. - */ - dialog: DialogController; - } - type ExitReason = - 'normal' | - 'abnormal' | - 'crash' | - 'kill'; - interface Exit { - /** Chrome's internal ID of the process that exited. */ - processID: integer; - /** String indicating the reason for the exit. */ - reason: ExitReason; - } - interface FindUpdate { - /** - * The string that is being searched for in the page. - */ - searchText: string; - /** - * The number of matches found for searchText on the page so far. - */ - numberOfMatches: integer; - /** - * The ordinal number of the current active match, - * if it has been found. This will be 0 until then. - */ - activeMatchOrdinal: integer; - /** - * Describes a rectangle around the active match, - * if it has been found, in screen coordinates. - */ - selectionRect: SelectionRect; - /** - * Indicates whether the find request was canceled. - */ - canceled: boolean; - /** - * Indicates that all find requests have completed - * and that no more findupdate events will be fired - * until more find requests are made. - */ - finalUpdate: string; - } - interface LoadAbort { - /** Requested URL. */ - url: string; - /** Whether the load was top-level or in a subframe. */ - isTopLevel: boolean; - /** - * 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: integer; - /** - * 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: LoadAbortReason; - } - interface LoadCommit { - /** The URL that committed. */ - url: string; - /** Whether the load is 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; - } - interface LoadStart { - /** Requested URL. */ - url: string; - /** Whether the load is top-level or in a subframe. */ - isTopLevel: boolean; - } - type WindowOpenDisposition = - 'ignore' | - 'save_to_disk' | - 'current_tab' | - 'new_background_tab' | - 'new_foreground_tab' | - 'new_window' | - 'new_popup'; - interface 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; - - /** The target URL requested for the new window. */ - targetUrl: string; - - /** The initial width requested for the new window. */ - initialWidth: integer; - - /** The initial height requested for the new window. */ - initialHeight: integer; - - /** The requested name of the new window. */ - name: string; - - /** The requested disposition of the new window. */ - windowOpenDisposition: WindowOpenDisposition; - } - 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; - } - interface ProcessResponsive { - /** Chrome's internal ID of the process that became responsive. */ - processID: integer; - } - interface SizeChanged { - /** Old width of embedded web content. */ - oldWidth: integer; - /** Old height of embedded web content. */ - oldHeight: integer; - /** New width of embedded web content. */ - newWidth: integer; - /** New height of embedded web content. */ - newHeight: integer; - } - interface ProcessUnresponsive { - /** Chrome's internal ID of the process that has become unresponsive. */ - processID: integer; - } - interface ZoomChange { - /** The page's previous zoom factor. */ - oldzoomFactor: double; - /** The new zoom factor that the page was zoomed to. */ - newzoomFactor: double; - } - } namespace webRequest { type ResourceType = @@ -10737,4 +9402,5 @@ declare namespace chrome { ///////////////////// interface Window { chrome: typeof chrome; + WebView: HTMLWebViewElement; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 90fe73368c..9a5bbddb23 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -782,6 +782,7 @@ chrome.fileSystem.getVolumeList((volumes) => { }); }); + // MESSAGING chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => { @@ -795,6 +796,26 @@ chrome.runtime.sendMessage( } ); +// POWER + +chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); +chrome.power.requestKeepAwake('display'); + +type IEnum = F; +type EnumType< + C extends Object, + T = undefined, + K = keyof C, + V = K extends keyof C ? Exclude : never> = IEnum; +type ETEST = EnumType<{ + SYSTEM: "system", + DISPLAY: "display" +}>; +let etest: ETEST; +etest = 'display'; +etest = 'DISPLAY'; +etest = etest.DISPLAY; + // SOCKETS // https://developer.chrome.com/apps/sockets_tcp @@ -908,7 +929,7 @@ 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) => { }); // send chrome.sockets.udp.send(socketId, buffer, '172.21.0.1', 10080, (info: chrome.sockets.SendInfo) => { }); @@ -924,16 +945,16 @@ function test_socketsUdp(): void { chrome.sockets.udp.getSockets((infos: chrome.sockets.SocketInfo[]) => { }); // joinGroup - chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { }); + chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result) => { }); // leaveGroup - chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { }); + chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result) => { }); // setMulticastTimeToLive - chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result) => { }); // setMulticastLoopbackMode - chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result) => { }); // getJoinedGroups chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); @@ -1097,7 +1118,7 @@ chrome.usb.getUserSelectedDevices({ // WEBVIEW -let wve: chrome.webview.HTMLWebViewElement = (document.getElementById('webview')); +let wve: HTMLWebViewElement = (document.getElementById('webview')); wve.name = 'test'; wve.src = 'https://github.com/DefinitelyTyped'; wve.allowtransparency = true; @@ -1128,7 +1149,7 @@ wve.addEventListener('loadredirect', (ev) => { }); wve.request.onBeforeRequest.addListener( - function (details) { return { cancel: true }; }, + (details) => { return { cancel: true }; }, { urls: ["*://www.evil.com/*"] }, ["blocking"]); diff --git a/types/chrome-apps/webview.d.ts b/types/chrome-apps/webview.d.ts new file mode 100644 index 0000000000..9b81f5821b --- /dev/null +++ b/types/chrome-apps/webview.d.ts @@ -0,0 +1,1368 @@ +// Type definitions for Chrome packaged application development +// Project: http://developer.chrome.com/apps/ +// 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.8 + +///////////////// +// 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. + */ + +declare class HTMLWebViewElement extends HTMLElement { + /** Create a new element */ + constructor (); + + /** 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. + * The src attribute cannot be cleared or removed once it has been set, unless the webview is removed from the DOM. + * 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. + * 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. + * 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: WebView.ContentWindow; + + /** Interface which provides access to webRequest events on the guest page. */ + request: WebView.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. */ + contextMenus: WebView.ContextMenus; + /** + * 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. + */ + addEventListener(type: 'close', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * 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: WebView.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: + * @example + * webview.addEventListener('contentload', function() { + * webview.executeScript({ code: 'document.body.style.fontSize = '42px'' }) + * }); + */ + addEventListener(type: 'contentload', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * 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. + */ + addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: WebView.Dialog) => void, useCapture?: boolean): void; + /** + * Fired when the process rendering the guest web content has exited. + */ + addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: WebView.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: WebView.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: WebView.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: WebView.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: WebView.LoadRedirect) => void, useCapture?: boolean): void; + /** + * Fired when a load has begun. + */ + addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: WebView.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. + * 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. + */ + addEventListener(type: 'loadstop', listener: (this: HTMLWebViewElement) => void, useCapture?: boolean): void; + /** + * 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); + * }); + */ + addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: WebView.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. + * 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(); + * } + * }); + */ + addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: WebView.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: WebView.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: WebView.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: WebView.ProcessUnresponsive) => void, useCapture?: boolean): void; + /** Fired when the page's zoom changes. */ + addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: WebView.ZoomChange) => void, useCapture?: boolean): void; + /** + * Queries audio state. + * @since Chrome 62. + **/ + getAudioState(callback: (audible: boolean) => void): void; + + /** + * Sets audio mute state of the webview. + * @param mute Mute audio value + * @since Chrome 62. + */ + setAudioMuted(mute: boolean): void; + + /** + * Queries whether audio is muted. + * @since Chrome 62. + */ + isAudioMuted(callback: (muted: boolean) => void): void; + + /** + * Captures the visible region of the webview. + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. + */ + captureVisibleRegion(callback: (dataUrl: string) => void): void; + /** + * Captures the visible region of the webview. + * @param options Extension type + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. + */ + captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; + + /** + * Adds content script injection rules to the webview. + * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. + * You can programmatically add rules or update existing rules. + * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. + * @example + * webview.addContentScripts([ + * { + * name: 'myRule', + * matches: ['http://www.foo.com/*'], + * css: { files: ['mystyles.css'] }, + * js: { files: ['jquery.js', 'myscript.js'] }, + * run_at: 'document_start' + * }, + * { + * name: 'anotherRule', + * matches: ['http://www.bar.com/*'], + * js: { code: 'document.body.style.backgroundColor = 'red';' }, + * run_at: 'document_end' + * }]); + * ... + * // Navigates webview. + * webview.src = 'http://www.foo.com'; + * + * @description + * You can defer addContentScripts call until you needs to inject scripts. + * The following example shows how to overwrite an existing rule. + * @example + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.foo.com/*'], + * js: { files: ['scriptA.js'] }, + * run_at: 'document_start'}]); + * + * // Do something. + * webview.src = 'http://www.foo.com/*'; + * ... + * // Overwrite 'rule' defined before. + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.bar.com/*'], + * js: { files: ['scriptB.js'] }, + * run_at: 'document_end'}]); + * @description + * If webview has been naviagted to the origin (e.g., foo.com) and + * calls webview.addContentScripts to add 'myRule', + * you need to wait for next navigation to make the scripts injected. + * If you want immediate injection, executeScript will do the right thing. + * Rules are preserved even if the guest process crashes + * or is killed or even if the webview is reparented. + * Refer to the /extensions/content_scripts documentation for more details. + * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. + * @since Chrome 44. + */ + addContentScripts(contentScriptList: WebView.ContentScriptDetails[]): void; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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 Called after the data has been successfully cleared. + * @since Chrome 33. + */ + clearData(options: WebView.ClearDataOptions, types: WebView.ClearDataTypeSet, callback?: () => void): void; + + /** + * 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] Called after all the JavaScript has been executed. + */ + executeScript(details: WebView.InjectDetails, callback?: (result?: any[]) => void): void; + + /** + * Initiates a find-in-page request. + * @param searchText The string to find in the page. + * @param [options] Options for the find request. + * @param [callback] Called after all find results have been returned for this find request. + * Provides optionally: + * results: Contains all of the results of the find request. + * results can be omitted if it is not utilized in the callback function body; + * e.g. if the callback is only used to discern when the find request has completed. + */ + find(searchText: string, options?: WebView.FindOptions, callback?: (results?: WebView.FindCallbackResults) => void): void; + + /** + * Navigates forward one history entry if possible. Equivalent to go(1). + * @param [callback] Called after the navigation has either failed or completed successfully. + * Provides *success* which indicates whether the navigation was successful. + */ + forward(callback?: (success: boolean) => void): void; + + /** + * 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(): chrome.integer; + + /** + * Returns the user agent string used by the webview for guest page requests. + * @since Since Chrome 33. + */ + getUserAgent(): string; + + /** + * Gets the current zoom factor. + * @param callback Called after the current zoom factor is retrieved. Provides the current zoom factor. + * @since Chrome 36. + */ + getZoom(callback: (zoomFactor: chrome.double) => void): void; + + /** + * Gets the current zoom mode. + * @param callback Called with the webview's current zoom mode. + * @since Since Chrome 43. + */ + getZoomMode(callback: (ZoomMode: WebView.ZoomMode) => void): void; + + /** + * 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] Called after the navigation has either failed or completed successfully. + * Provides a boolean, *success*, which indicates whether the navigation was successful. + */ + go(relativeIndex: chrome.integer, callback?: (success: boolean) => void): void; + + /** + * Injects CSS into the guest page. + * @param details Details of the CSS to insert. + * @param callback Called after the CSS has been inserted. + */ + insertCSS(details: WebView.InjectDetails, callback?: () => void): void; + + /** + * Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. + * @since Since Chrome 33. + */ + isUserAgentOverridden(): void; + + /** + * Prints the contents of the webview. + * This is equivalent to calling scripted print function from the webview itself. + * @since Since Chrome 38. + */ + print(): void; + + /** Reloads the current top-level page. */ + reload(): void; + + /** + * 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(); + * @param 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. + * @since Chrome 44. + */ + removeContentScripts(scriptNameList?: string[]): void; + + /** + * Override the user agent string used by the webview for guest page requests. + * @param userAgent The user agent string to use. + * @since Since Chrome 33. + */ + setUserAgentOverride(userAgent: string): void; + + /** + * 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] Called after the page has been zoomed. + * @since Since Chrome 36. + */ + setZoom(zoomFactor: chrome.double, callback?: () => void): void; + + /** + * Sets the zoom mode of the webview. + * @param ZoomMode Defines how zooming is handled in the webview. + * @param [callback] Called after the zoom mode has been changed. + * @since Since Chrome 43. + */ + setZoomMode(ZoomMode: WebView.ZoomMode, callback?: () => void): void; + + /** Stops loading the current webview navigation if in progress. */ + stop(): void; + + /** + * @todo TODO Fix action param + * Ends the current find session (clearing all highlighting) + * and cancels all find requests in progress. + * @param 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. + * @since Since Chrome 35. + */ + stopFinding(action?: 'clear' | 'keep' | 'activate'): void; + + /** + * 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 dataUrl The data URL to load. + * @param baseUrl The base URL that will be used for relative links. + * @param virtualUrl The URL that will be displayed to the user (in the address bar). + * @since Since Chrome 40. + */ + loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; + + /** + * 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; +} +declare namespace WebView { + /** 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). + * @default 0 + */ + since?: chrome.integer; + } + + interface WindowEvent extends chrome.events.Event<() => void> { } + + interface ConsoleEvent extends Event { + /** The severity level of the log message. Ranges from 0 to 4. */ + level: chrome.integer; + /** The logged message contents.*/ + message: string; + /** The line number of the message source.*/ + line: chrome.integer; + /** A string identifying the resource which logged the message. */ + sourceId: string; + } + + type ExitEventReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; + interface ExitEvent extends Event { + /** Chrome's internal ID of the process that exited. */ + processID: chrome.integer; + /** String indicating the reason for the exit. */ + reason: ExitEventReason; + } + + /** + * 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 { + /** + * 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, + /** + * JavaScript or CSS file to inject. + */ + file?: string + } + + /** + * WebView element from html + */ + + + /** A set of data types. Missing properties are interpreted as false. */ + interface ClearDataTypeSet { + /** Websites' appcaches. */ + appcache?: boolean; + /** + * 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. + */ + 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. + **/ + 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 { + /** + * 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; + + /** JavaScript or CSS file to inject. */ + file?: string + } + /** The type of injection item: code or a set of files. */ + interface InjectionItems { + /** JavaScript code or CSS to be injected into matching pages. */ + code?: string + /** + * 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. **/ + interface ContentScriptDetails { + /** The name of the content script to inject. */ + name: string + + /** Specifies which pages this content script will be injected into. */ + matches: any[] + + /** Excludes pages that this content script would otherwise be injected into. */ + exclude_matches?: any[] + + /** JavaScript or CSS file to inject. */ + file?: string + } + /** The type of injection item: code or a set of files. */ + interface InjectionItems { + /** JavaScript code or CSS to be injected into matching pages. */ + code?: string + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * The soonest that the JavaScript or CSS will be injected into the tab. + * Defaults to 'document_idle'. + */ + run_at?: chrome.extensionTypes.RunAt; + + /** + * 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; + + /** + * Applied after matches to include only those URLs that also match this glob. + * Intended to emulate the @include Greasemonkey keyword. + */ + include_globs?: string[]; + + /** + * Applied after matches to exclude URLs that match this glob. + * Intended to emulate the @exclude Greasemonkey keyword. + */ + exclude_globs?: string[]; + } + interface ContextMenuCreateProperties { + + /** + * The type of menu item. Defaults to 'normal' if not specified. + */ + type?: chrome.contextMenus.ItemType; + + /** + * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. + */ + 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?: any[]; + + /** + * A function that will be called back when the menu item is clicked. + */ + onclick?: (info: any) => void + + /** + * The ID of a parent menu item; this makes the item a child of a previously added item. + */ + parentId?: chrome.integer | 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?: any[]; + + /** + * 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[]; + + /** + * Whether this context menu item is enabled or disabled. Defaults to true. + */ + enabled?: boolean; + } + interface ContextMenuUpdateProperties { + /** The type of menu item. */ + type?: WebView.ContextType; + + /** The text to be displayed in the item */ + title?: string; + + /** + * 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; + + /** + * List of contexts this menu item will appear in. + */ + contexts?: any[]; + + /** + * A function that will be called back when the menu item is clicked. + * @param callback + */ + onclick?: (info: any) => void; + + /** + * 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?: chrome.integer | 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.) + */ + documentUrlPatterns?: any[]; + + /** + * 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[]; + + /** + * Whether this context menu item is enabled or disabled. + */ + enabled?: boolean; + } + interface ContextMenus { + /** + * 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; + + /** + * 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: chrome.integer | string, updateProperties: object, callback?: () => void): void; + + /** + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param [callback] + */ + remove(menuItemId: chrome.integer | string, callback?: () => void): void; + + /** + * Removes all context menu items added to this webview. + * @param [callback] + */ + removeAll(callback?: () => void): void; + + /** + * 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; + } + interface OnShowEvent { + /** Call this to prevent showing the context menu. */ + preventDefault: () => void; + } + interface ContentWindow { + /** + * 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 { + /** + * 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; + /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ + cancel(): void; + } + /** Contains all of the results of the find request. */ + interface FindCallbackResults { + /** The number of times searchText was matched on the page. */ + numberOfMatches: chrome.integer; + /** The ordinal number of the current match. */ + activeMatchOrdinal: chrome.integer; + /** Describes a rectangle around the active match in screen coordinates. */ + selectionRect: SelectionRect; + /** Indicates whether this find request was canceled. */ + canceled: boolean; + } + interface FindOptions { + /** + * Flag to find matches in reverse order. + * @default false + */ + backward?: boolean; + /** + * Flag to match with case-sensitivity. + * @default false + */ + matchCase?: boolean; + } + interface NewWindow { + /** + * 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: HTMLWebViewElement): void; + /** + * Cancel the new window request. + */ + discard(): void; + } + interface PermissionRequestHandler { + /** Allow the permission request. */ + allow(): void; + /** Deny the permission request. This is the default behavior if allow is not called. */ + deny(): void; + } + /** + * 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 { + /** Distance from the left edge of the screen to the left edge of the rectangle. */ + left: chrome.integer; + /** Distance from the top edge of the screen to the top edge of the rectangle. */ + top: chrome.integer; + /** Width of the rectangle. */ + width: chrome.integer; + /** Height of the rectangle. */ + height: chrome.integer; + } + + /** An HTTP Header, represented as an object containing a key and either a value or a binaryValue. */ + interface HttpHeader { + name: string; + value?: string; + binaryValue?: ArrayBuffer; + } + + interface ResourceRequest { + url: string; + /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ + requestId: string; + /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ + frameId: chrome.integer; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: chrome.integer; + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ + tabId: chrome.integer; + /** + * How the requested resource will be used. + */ + type: chrome.webRequest.ResourceType; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: chrome.double; + /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. + * @since Since Chrome 63. + */ + initiator?: string; + } + + interface WebRequestDetails extends ResourceRequest { + /** Standard HTTP method. */ + method: string; + } + + interface WebRequestHeadersDetails extends WebRequestDetails { + /** Optional. The HTTP request headers that are going to be sent out with this request. */ + requestHeaders?: HttpHeader[]; + } + + interface WebRequestBodyDetails extends WebRequestDetails { + /** + * Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'. + * @since Chrome 23. + */ + requestBody: WebRequestBody; + } + + /** + * Contains data uploaded in a URL request. + * @since Chrome 23. + */ + interface UploadData { + /** Optional. An ArrayBuffer with a copy of the data. */ + bytes?: ArrayBuffer; + /** Optional. A string with the file's path and name. */ + file?: string; + } + + interface WebRequestBody { + /** Optional. Errors when obtaining request body data. */ + error?: string; + /** + * Optional. + * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. + */ + formData?: { [key: string]: string[] }; + /** + * Optional. + * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. + */ + raw?: UploadData[]; + } + + interface WebRequestFullDetails extends WebRequestHeadersDetails, WebRequestBodyDetails { + } + + interface WebResponseDetails extends ResourceRequest { + /** HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line). */ + statusLine: string; + /** + * Standard HTTP status code returned by the server. + * @since Chrome 43. + */ + statusCode: chrome.integer; + } + + interface WebResponseHeadersDetails extends WebResponseDetails { + /** Optional. The HTTP response headers that have been received with this response. */ + responseHeaders?: HttpHeader[]; + /** standard HTTP method i.e. GET, POST, PUT, etc. */ + method: string; + } + + interface WebResponseCacheDetails extends WebResponseHeadersDetails { + /** + * Optional. + * The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address. + */ + ip?: string; + /** Indicates if this response was fetched from disk cache. */ + fromCache: boolean; + } + + interface WebRedirectionResponseDetails extends WebResponseCacheDetails { + /** The new URL. */ + redirectUrl: string; + } + + /** An object describing filters to apply to webRequest events. */ + interface RequestFilter { + /** Optional. */ + tabId?: chrome.integer; + /** + * A list of request types. Requests that cannot match any of the types will be filtered out. + */ + types?: chrome.webRequest.ResourceType[]; + /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ + urls: string[]; + + /** Optional. */ + windowId?: chrome.integer; + } + + interface AuthCredentials { + username: string; + password: string; + } + + /** Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests. */ + interface BlockingResponse { + /** + * If true, the request is cancelled. + * Used in onBeforeRequest, this prevents the request from being sent. */ + cancel?: boolean; + /** + * Only used as a response to the onBeforeRequest and onHeadersReceived events. + * If set, the original request is prevented from being sent/completed and is + * instead redirected to the given URL. Redirections to non-HTTP schemes such + * as data: are allowed. Redirects initiated by a redirect action use the + * original request method for the redirect, with one exception: If the + * redirect is initiated at the onHeadersReceived stage, then the redirect + * will be issued using the GET method. + */ + redirectUrl?: string; + /** + * Only used as a response to the onHeadersReceived event. + * If set, the server is assumed to have responded with these + * response headers instead. Only return responseHeaders if you really + * want to modify the headers in order to limit the number of conflicts + * (only one extension may modify responseHeaders for each request). + */ + responseHeaders?: HttpHeader[]; + /** + * Only used as a response to the onAuthRequired event. + * If set, the request is made using the supplied credentials. + */ + authCredentials?: AuthCredentials; + /** + * Only used as a response to the onBeforeSendHeaders event. + * If set, the request is made with these request headers instead. + */ + requestHeaders?: HttpHeader[]; + } + + interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { + /** The authentication scheme, e.g. Basic or Digest. */ + scheme: string; + /** The authentication realm provided by the server, if there is one. */ + realm?: string; + /** The server requesting authentication. */ + challenger: WebAuthChallenger; + /** True for Proxy-Authenticate, false for WWW-Authenticate. */ + isProxy: boolean; + } + + interface WebRequestBodyEvent extends chrome.events.Event<(details: WebRequestBodyDetails) => void> { + addListener(callback: (details: WebRequestBodyDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebRequestHeadersEvent extends chrome.events.Event<(details: WebRequestHeadersDetails) => void> { + addListener(callback: (details: WebRequestHeadersDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface _WebResponseHeadersEvent extends chrome.events.Event<(details: T) => void> { + addListener(callback: (details: T) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseHeadersEvent extends _WebResponseHeadersEvent { } + + interface WebResponseCacheEvent extends _WebResponseHeadersEvent { } + + interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent { } + + interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { + addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseErrorEvent extends _WebResponseHeadersEvent { } + + interface WebResponseErrorDetails extends WebResponseCacheDetails { + /** The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. */ + error: string; + } + + interface WebAuthChallenger { + host: string; + port: chrome.integer; + } + + /** + * 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 { + /** Fired when a request is about to occur. */ + onBeforeRequest: WebRequestBodyEvent; + /** + * Fired before sending an HTTP request, once the request headers are available. + * This may occur after a TCP connection is made to the server, but before any HTTP data is sent. + */ + onBeforeSendHeaders: WebRequestHeadersEvent; + /** + * Fired just before a request is going to be sent to the server + * (modifications of previous onBeforeSendHeaders callbacks + * are visible by the time onSendHeaders is fired). + */ + onSendHeaders: WebRequestHeadersEvent; + /** Fired when HTTP response headers of a request have been received. */ + onHeadersReceived: WebResponseHeadersEvent; + /** + * Fired when an authentication failure is received. + * The listener has three options: it can provide authentication credentials, + * it can cancel the request and display the error page, or it can take no + * action on the challenge. If bad user credentials are provided, this may be + * called multiple times for the same request. + */ + onAuthRequired: WebAuthenticationChallengeEvent; + /** + * Fired when the first byte of the response body is received. + * For HTTP requests, this means that the status line and + * response headers are available. + */ + onResponseStarted: WebResponseCacheEvent; + /** Fired when a server-initiated redirect is about to occur. */ + onBeforeRedirect: WebRedirectionResponseEvent; + /** Fired when a request is completed. */ + onCompleted: WebResponseCacheEvent; + /** Fired when an error occurs. */ + onErrorOccured: WebResponseErrorEvent; + /** + * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onRequest: chrome.webViewRequest.OnRequestEvent; + /** + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onMessage: chrome.webViewRequest.OnMessageEvent; + } + /** + * 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. + * '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). + * 'disabled' + * > 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 { + /** + * 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; + /** The logged message contents. */ + message: string; + /** The line number of the message source. */ + line: chrome.integer; + /** A string identifying the resource which logged the message. */ + sourceId: string; + } + type DialogMessageType = + 'alert' | + 'confirm' | + 'prompt'; + + interface Dialog { + /** + * The type of modal dialog requested by the guest. + */ + messageType: DialogMessageType; + /** + * The text the guest attempted to display in the modal dialog. + */ + messageText: string; + /** + * An interface that can be used to respond to the guest's modal request. + */ + dialog: DialogController; + } + type ExitReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; + interface Exit { + /** Chrome's internal ID of the process that exited. */ + processID: chrome.integer; + /** String indicating the reason for the exit. */ + reason: ExitReason; + } + interface FindUpdate { + /** + * The string that is being searched for in the page. + */ + searchText: string; + /** + * The number of matches found for searchText on the page so far. + */ + numberOfMatches: chrome.integer; + /** + * The ordinal number of the current active match, + * if it has been found. This will be 0 until then. + */ + activeMatchOrdinal: chrome.integer; + /** + * Describes a rectangle around the active match, + * if it has been found, in screen coordinates. + */ + selectionRect: SelectionRect; + /** + * Indicates whether the find request was canceled. + */ + canceled: boolean; + /** + * Indicates that all find requests have completed + * and that no more findupdate events will be fired + * until more find requests are made. + */ + finalUpdate: string; + } + interface LoadAbort { + /** Requested URL. */ + url: string; + /** Whether the load was top-level or in a subframe. */ + isTopLevel: boolean; + /** + * Unique chrome.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 chrome.integer. + */ + code: chrome.integer; + /** + * 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: LoadAbortReason; + } + interface LoadCommit { + /** The URL that committed. */ + url: string; + /** Whether the load is 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; + } + interface LoadStart { + /** Requested URL. */ + url: string; + /** Whether the load is top-level or in a subframe. */ + isTopLevel: boolean; + } + type WindowOpenDisposition = + 'ignore' | + 'save_to_disk' | + 'current_tab' | + 'new_background_tab' | + 'new_foreground_tab' | + 'new_window' | + 'new_popup'; + interface 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; + + /** The target URL requested for the new window. */ + targetUrl: string; + + /** The initial width requested for the new window. */ + initialWidth: chrome.integer; + + /** The initial height requested for the new window. */ + initialHeight: chrome.integer; + + /** The requested name of the new window. */ + name: string; + + /** The requested disposition of the new window. */ + windowOpenDisposition: WindowOpenDisposition; + } + 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; + } + interface ProcessResponsive { + /** Chrome's internal ID of the process that became responsive. */ + processID: chrome.integer; + } + interface SizeChanged { + /** Old width of embedded web content. */ + oldWidth: chrome.integer; + /** Old height of embedded web content. */ + oldHeight: chrome.integer; + /** New width of embedded web content. */ + newWidth: chrome.integer; + /** New height of embedded web content. */ + newHeight: chrome.integer; + } + interface ProcessUnresponsive { + /** Chrome's internal ID of the process that has become unresponsive. */ + processID: chrome.integer; + } + interface ZoomChange { + /** The page's previous zoom factor. */ + oldzoomFactor: chrome.double; + /** The new zoom factor that the page was zoomed to. */ + newzoomFactor: chrome.double; + } +} From 3774ea75882212ca5fd85d6350f2348690b9a817 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 7 Aug 2018 16:53:41 +0200 Subject: [PATCH 040/289] Working on manifest representation. Hard to find docs... --- types/chrome-apps/index.d.ts | 48 ++++++++++++++++++++++++--------- types/chrome-apps/test/index.ts | 1 - 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 178e875593..136807056f 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -406,7 +406,7 @@ declare namespace chrome { * |____________________|____________|____________________________________________| * @since Since Chrome 54. */ - actionData?: ActionType; + actionData?: actionType; } interface LaunchDataItem { @@ -6157,6 +6157,18 @@ declare namespace chrome { }; } + interface AutomationDesktop { + desktop: true; + interact?: true; + } + interface AutomationNonInteractive { + interact: false; + desktop?: false; + /** Patterns for matching */ + matches?: string[]; + } + type AutomationOptions = boolean | AutomationDesktop | AutomationNonInteractive; + interface Manifest { ////////////// // REQUIRED // @@ -6262,9 +6274,7 @@ declare namespace chrome { /** @todo TODO */ author?: any; /** @todo TODO */ - automation?: boolean | { - [key: string]: string - }; + automation?: AutomationOptions; /** @todo TODO */ bluetooth?: { uuids?: string[]; @@ -6346,17 +6356,31 @@ declare namespace chrome { }; /** @todo TODO */ offline_enabled?: boolean; - /** @todo TODO */ + /** + * Permissions that are optional and user controlled. + */ optional_permissions?: Permission[] | Array; - /** @todo TODO */ + /** + * Permissions your application needs access to. + */ permissions?: Permission[] | Array; - /** @todo TODO */ + /** + * Native Client + * @see[NDK Docs]{@link https://github.com/crosswalk-project/chromium-crosswalk/blob/af36cc3ce3f5fcb8033f16236725718f8012abfe/native_client_sdk/src/doc/devguide/distributing.rst} + * @see[Chromium Source]{@link https://github.com/crosswalk-project/chromium-crosswalk/blob/af36cc3ce3f5fcb8033f16236725718f8012abfe/native_client_sdk/src/tools/fix_manifest.py} + */ platforms?: { - nacl_arch?: 'x86-64' | 'x86-32' | 'arm' | string; + nacl_arch: 'x86-64' | 'x86-32' | 'arm'; sub_package_path: string; }[]; /** - * Technologies required by the app or extension. Hosting sites such as the Chrome Web Store may use this list to dissuade users from installing apps or extensions that will not work on their computer. Supported requirements currently include '3D' and 'plugins'; additional requirements checks may be added in the future. + * Technologies required by the app or extension. + * Hosting sites such as the Chrome Web Store may use + * this list to dissuade users from installing apps or + * extensions that will not work on their computer. + * Supported requirements currently include '3D' + * and 'plugins'; additional requirements checks + * may be added in the future. */ requirements?: { /** @@ -6434,12 +6458,12 @@ declare namespace chrome { storage?: { /** * The storage.managed_schema property indicates a file within the app that contains the policy schema. + * @see ManagedSchema for schema content typings * @see[Docs and Schema Format]{@link https://developer.chrome.com/apps/manifest/storage} */ - managed_schema: ManagedSchema; + managed_schema: string; }; - /** @todo TODO */ - system_indicator?: any; + // system_indicator?: any; // Deprecated / removed: https://bugs.chromium.org/p/chromium/issues/detail?id=142450 /** * Autoupdating * Only set this if you want to host somewhere other than the store. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 9a5bbddb23..9842da12b5 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -220,7 +220,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "nacl_arch": "arm", "sub_package_path": "_platform_specific/arm/" }], - "web_accessible_resources": ["html/crosh.html", "html/nassh.html", "html/nassh_google_relay.html", "html/nassh_connect_dialog.html"], "permissions": [ "https://www.google-analytics.com/*", "http://localhost:8080/*", From 5565d58d349774d80cd3975ef2f8bef9c0abaa99 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 9 Aug 2018 14:43:47 +0200 Subject: [PATCH 041/289] Better documentation of poorly documented manifest fields. --- types/chrome-apps/index.d.ts | 776 +++++++++++++++++++------------- types/chrome-apps/test/index.ts | 86 ++-- 2 files changed, 493 insertions(+), 369 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 136807056f..06acde4e73 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -317,33 +317,39 @@ declare namespace chrome { * and can shut down the app at anytime. */ namespace app.runtime { - enum PlayStoreStatus { - ENABLED = 'enabled', - AVAILABLE = 'available', - UNKNOWN = 'unknown' + /** @enum */ + const 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' + /** @enum */ + const ActionType: { + NEW_NOTE: 'new_note' + } + /** @enum */ + const 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 EmbedRequested { @@ -361,12 +367,6 @@ declare namespace chrome { deny: () => void; } - 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. @@ -396,8 +396,9 @@ declare namespace chrome { isPublicSession?: boolean; /** * Where the app is launched from. + * @see enum LaunchSource */ - source?: LaunchSource; + source?: ToStringLiteral; /** * 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. * ______________________________________________________________________________ @@ -406,7 +407,7 @@ declare namespace chrome { * |____________________|____________|____________________________________________| * @since Since Chrome 54. */ - actionData?: actionType; + actionData?: ToStringLiteral; } interface LaunchDataItem { @@ -458,6 +459,18 @@ declare namespace chrome { height?: integer; } + /** + * @enum + * @internal + * @private + */ + const _State: { + NORMAL: 'normal', + FULLSCREEN: 'fullscreen', + MAXIMIZED: 'maximized', + MINIMIZED: 'minimized' + } + interface BoundsSpecification { /** The X coordinate of the content or window. */ left?: integer; @@ -546,13 +559,6 @@ declare namespace chrome { inactiveColor?: string; } - enum State { - NORMAL = 'normal', - FULLSCREEN = 'fullscreen', - MAXIMIZED = 'maximized', - MINIMIZED = 'minimized' - } - interface CreateWindowOptions { /** * Id to identify the window. @@ -630,7 +636,7 @@ declare namespace chrome { /** * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. */ - state?: State; + state?: ToStringLiteral; /** * 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. */ @@ -769,6 +775,17 @@ declare namespace chrome { } interface ChromeAppWindow extends AppWindow { + /** + * @enum + * Window state enum + */ + readonly State: typeof _State; + + readonly WindowType: { + SHELL: 'shell', + PANEL: 'panel' + } + /** * 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). @@ -2228,12 +2245,13 @@ declare namespace chrome { /** * 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. + * @param callback Provides 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. + * @return Request ID to be used by cancelChooseDesktopMedia */ - function chooseDesktopMedia - (sources: Array, callback: (streamId: string) => void): integer; + function chooseDesktopMedia(sources: ToStringLiteral[], callback: (streamId: string) => void): integer; + /** * Hides desktop media picker dialog shown by chooseDesktopMedia(). * @param desktopMediaRequestId Id returned by chooseDesktopMedia() @@ -2709,19 +2727,20 @@ declare namespace chrome { * */ function retainEntry(entry: Entry): string; /** + * @requires(Kiosk) Kiosk mode only + * @requires Permissions: The writable option requires the 'fileSystem': {'write'} permission in the manifest. * 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. * Otherwise, it will be read-only. - * The writable option requires the 'fileSystem': {'write'} permission in the manifest. - * 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. */ function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; /** + * @requires(Kiosk) Chrome OS Kiosk mode only + * @requires Permissions: The 'fileSystem': {'requestFileSystem'} manifest permission is required. * 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. @@ -2743,7 +2762,7 @@ declare namespace chrome { * 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(CrOS) 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: @@ -4315,111 +4334,139 @@ declare namespace chrome { // 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' + * The chrome.management API provides ways to + * manage the list of extensions/apps + * that are installed and running. */ namespace management { + const ExtensionDisabledReason: { + UNKNOWN: "unknown", + PERMISSIONS_INCREASE: "permissions_increase" + }; + const ExtensionInstallType: { + ADMIN: "admin", + DEVELOPMENT: "development", + NORMAL: "normal", + SIDELOAD: "sideload", + OTHER: "other" + }; + const ExtensionType: { + EXTENSION: "extension", + HOSTED_APP: "hosted_app", + PACKAGED_APP: "packaged_app", + LEGACY_PACKAGED_APP: "legacy_packaged_app", + THEME: "theme" + }; + const LaunchType: { + OPEN_AS_REGULAR_TAB: "OPEN_AS_REGULAR_TAB", + OPEN_AS_PINNED_TAB: "OPEN_AS_PINNED_TAB", + OPEN_AS_WINDOW: "OPEN_AS_WINDOW", + OPEN_FULL_SCREEN: "OPEN_FULL_SCREEN" + }; /** Information about an installed extension, app, or theme. */ interface ExtensionInfo { /** - * Optional. * A reason the item is disabled. * @since Chrome 17. + * @see enum ExtensionDisabledReason + */ + disabledReason?: ToStringLiteral; + /** + * The launch url. */ - disabledReason?: string; - /** Optional. The launch url (only present for apps). */ appLaunchUrl?: string; /** - * The description of this extension, app, or theme. - * @since Chrome 9. + * The description of this app. */ description: string; /** * Returns a list of API based permissions. - * @since Chrome 9. */ - permissions: string[]; + permissions: chrome.runtime.Permission[]; /** - * 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. + * 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. + * Permissions regarding url access. */ hostPermissions: string[]; /** Whether it is currently enabled or disabled. */ enabled: boolean; /** - * Optional. - * The URL of the homepage of this extension, app, or theme. + * The URL of the homepage of this app. * @since Chrome 11. */ homepageUrl?: string; /** - * Whether this extension can be disabled or uninstalled by the user. - * @since Chrome 12. + * Whether this app can be disabled or uninstalled by the user. */ mayDisable: boolean; /** - * How the extension was installed. + * How the app was installed. * @since Chrome 22. */ - installType: string; - /** The version of this extension, app, or theme. */ + installType: ToStringLiteral; + + /** The version of this app. */ version: string; + + /** This app's version name */ + versionName: string; + /** The extension's unique identifier. */ id: string; + /** - * Whether the extension, app, or theme declares that it supports offline. + * Whether the app declares that it supports offline. * @since Chrome 15. */ offlineEnabled: boolean; /** - * Optional. - * The update URL of this extension, app, or theme. + * The update URL of this app. * @since Chrome 16. */ updateUrl?: string; /** - * The type of this extension, app, or theme. + * The type of this app. * @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. */ + type: 'packaged_app'; + /** The name of this app. */ name: string; /** - * A short version of the name of this extension, app, or theme. + * A short version of the name of this app. * @since Chrome 31. */ shortName: string; /** - * True if this is an app. + * True if this is an app, which it will be till this is removed. * @deprecated since Chrome 33. Please use management.ExtensionInfo.type. */ - isApp: boolean; + isApp?: true; /** - * Optional. - * The app launch type (only present for apps). + * The app launch type. * @since Chrome 37. */ - launchType?: string; + launchType?: ToStringLiteral; /** - * Optional. - * The currently available launch types (only present for apps). + * The currently available launch types. * @since Chrome 37. */ - availableLaunchTypes?: string[]; + availableLaunchTypes?: ToStringLiteral[]; } /** 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. */ + /** + * 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: integer; @@ -4427,79 +4474,21 @@ declare namespace chrome { 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. + * 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) {...}; + * @param manifestStr Extension manifest JSON string. See example + * @param [callback] Permissions warnings as string array + * @example + * chrome.management.getPermissionWarningsByManifest(JSON.stringify(chrome.runtime.getManifest()), (warnings) => { *Do something here* }); */ 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. @@ -4507,56 +4496,15 @@ declare namespace chrome { * 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() {...}; + * @param [options] Optional unstall options + * @param [callback] */ 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; } //////////////////// @@ -5817,6 +5765,39 @@ declare namespace chrome { * @since Chrome 22 */ namespace runtime { + const OnInstalledReason: { + INSTALL: 'install', + UPDATE: 'update', + CHROME_UPDATE: 'chrome_update', + SHARED_MODULE_UPDATE: 'shared_module_update' + }; + const OnRestartRequiredReason: { + APP_UPDATE: 'app_update', + OS_UPDATE: 'os_update', + PERIODIC: 'periodic' + }; + const PlatformArch: { + ARM: 'arm', + X86_32: 'x86-32', + X86_64: 'x86-64', + MIPS: 'mips', + MIPS64: 'mips64' + }; + const PlatformNaclArch: typeof PlatformArch; + const PlatformOs: { + ANDROID: 'android', + CROS: 'cros', + LINUX: 'linux', + MAC: 'mac', + OPENBSD: 'openbsd', + WIN: 'win' + }; + const RequestUpdateCheckStatus: { + THROTTLED: 'throttled', + NO_UPDATE: 'no_update', + UPDATE_AVAILABLE: 'update_available' + }; + /** This will be defined during an API method callback if there was an error */ const lastError: LastError | undefined; /** The ID of the extension/app. */ @@ -5834,9 +5815,9 @@ declare namespace chrome { interface InstalledDetails { /** * The reason that this event is being dispatched. - * One of: 'install', 'update', 'chrome_update', or 'shared_module_update' + * @see enum OnInstalledReason */ - reason: string; + reason: ToStringLiteral; /** * Optional. * Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'. @@ -5886,19 +5867,19 @@ declare namespace chrome { interface PlatformInfo { /** * The operating system chrome is running on. - * One of: 'mac', 'win', 'android', 'cros', 'linux', or 'openbsd' + * @see enum PlatformOs */ - os: string; + os: ToStringLiteral; /** * The machine's processor architecture. - * One of: 'arm', 'x86-32', or 'x86-64' + * @see enum PlatformArch */ - arch: string; + arch: ToStringLiteral; /** * The native client architecture. This may be different from arch on some platforms. - * One of: 'arm', 'x86-32', or 'x86-64' + * @see enum PlatformNaclArch */ - nacl_arch: string; + nacl_arch: ToStringLiteral; } /** @@ -5967,24 +5948,54 @@ declare namespace chrome { } type UrlPermission = - "https://www.google-analytics.com/*" - | "https://www.googleapis.com/*" + 'https://www.google-analytics.com/*' + | 'https://www.googleapis.com/*' | '' | 'http://*/*' | 'https://*/*' | 'file:///*/*'; + type ChromeOSOnlyPermissions = + 'certificateProvider' | + 'clipboard' | + 'documentScan' | + 'enterprise.platformKeys' | + 'fileBrowserHandler' | + 'fileSystemProvider' | + 'enterprise' | // ? + 'enterprise.platformKeys' | + 'enterprise.deviceAttributes' | + 'networking.config' | + 'platformKeys' | + 'virtualKeyboard' | + 'vpnProvider' | + 'wallpaper'; + + type KioskOnlyPermissions = + 'networking.onc'; + + /** Undocumented but used permissions */ + type UndocumentedPermissions = + 'experimental' | + 'app.window.alpha' | + 'app.window.shape' | + 'geolocation' | + 'alwaysOnTopWindows' | + 'overrideEscFullscreen' | + 'geolocation' | + 'experimental' | + 'diagnostics' | + 'app.window.fullscreen' | + 'app.window.fullscreen.overrideEsc'; + type Permission = 'alarms' | - "app.window.fullscreen" | - "app.window.fullscreen.overrideEsc" | + 'app.window.fullscreen' | + 'app.window.fullscreen.overrideEsc' | 'audio' | 'audioCapture' | 'background' | - 'bluetooth' | 'browser' | - 'certificateProvider' | - 'clipboard' | 'clipboardRead' | 'clipboardWrite' | 'contextMenus' | @@ -5992,48 +6003,36 @@ declare namespace chrome { 'diagnostics' | 'displaySource' | 'dns' | - 'documentScan' | - 'enterprise.deviceAttributes' | - 'enterprise.platformKeys' | 'experimental' | - 'fileBrowserHandler' | 'fileSystem' | 'gcm' | 'geolocation' | 'hid' | 'identity' | 'idle' | - 'management' | 'mdns' | 'mediaGalleries' | 'nativeMessaging' | - 'networking.config' | - 'networking.onc' | 'notifications' | - 'platformKeys' | 'pointerLock' | 'power' | 'printerProvider' | - 'proxy' | // 'serial' | // Deprecated 'signedInDevices' | - 'socket' | 'storage' | 'syncFileSystem' | 'system.cpu' | 'system.display' | 'system.memory' | 'system.network' | - 'system.powerSource' | 'system.storage' | 'tts' | 'unlimitedStorage' | 'usb' | 'videoCapture' | - 'virtualKeyboard' | - 'vpnProvider' | - 'wallpaper' | 'webview' | + ChromeOSOnlyPermissions | + KioskOnlyPermissions | MediaGalleriesPermission | SocketPermission | PrivatePermissions | @@ -6089,9 +6088,9 @@ declare namespace chrome { } interface JSONSchemaObjectType { /** - * An "object" can have known properties listed as "properties", and can - * optionally have "additionalProperties" indicating a schema to apply to - * keys that aren't found in "properties". + * An 'object' can have known properties listed as 'properties', and can + * optionally have 'additionalProperties' indicating a schema to apply to + * keys that aren't found in 'properties'. */ type: 'object'; properties?: { @@ -6131,8 +6130,8 @@ declare namespace chrome { /** * Path to files, relative, absolute or pattern * @example - * ["local_*.html", "*.png", "*.js"] - * ["img/epic.html"] + * ['local_*.html', '*.png', '*.js'] + * ['img/epic.html'] * */ accessible_resources: string[]; @@ -6145,11 +6144,11 @@ declare namespace chrome { */ interface ManagedSchema { /** Each schema must have either a $ref value or exactly one type. */ - "$ref"?: string; + '$ref'?: string; /** The top-level schema must have type object. */ type: 'object'; /** - * "properties" maps an optional key of this object to its schema. At the + * 'properties' maps an optional key of this object to its schema. At the * top-level object, these keys are the policy names supported. */ properties?: { @@ -6169,7 +6168,36 @@ declare namespace chrome { } type AutomationOptions = boolean | AutomationDesktop | AutomationNonInteractive; - interface Manifest { + interface InvalidManifest extends ValidManifest { + // + // Never types - should never exist + // Are declared to prevent use since many + // legacy app are using them. Will result + // in errors. Many examples and code bases + // have these included. + // + + /** Not for packaged apps */ + options_ui?: never; + /** Not for packaged apps */ + options_page?: never; + /** Not for packaged apps */ + browser_action?: never; + /** + * Not for packaged apps + * Only for extensions and legacy packaged apps + */ + content_security_policy?: never; + /** + * Not for packaged apps + * Only for extensions and legacy packaged apps + */ + chrome_url_overrides?: never; + } + + type Manifest = ValidManifest | InvalidManifest; + + interface ValidManifest { ////////////// // REQUIRED // ////////////// @@ -6182,8 +6210,8 @@ declare namespace chrome { app: { background: { scripts?: string[]; - } - } + } | never; + } | never; /** * One integer specifying the version of the manifest file format your package requires. * As of Chrome 18, developers should specify 2 (without quotes). @@ -6202,6 +6230,7 @@ declare namespace chrome { * You can specify locale-specific strings, see Internationalization docs: * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} * @required + * @requires string - Maximum 45 characters! */ name: string; /** @@ -6220,11 +6249,12 @@ declare namespace chrome { /** * Specifies the subdirectory of _locales that contains the default strings for this extension. - * This field is required in extensions that have a _locales directory; it must be absent in - * extensions that have no _locales directory. For details, see Internationalization: + * This field is required in apps that have a _locales directory; it must be absent in + * apps that have no _locales directory. For details, see Internationalization: * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ default_locale?: string; + /** * A plain text string (no HTML or other formatting; no more than 132 characters) * that describes the extension. The description should be suitable for both the @@ -6233,6 +6263,7 @@ declare namespace chrome { * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ description?: string; + /** * One or more icons that represent the extension, app, or theme. * You should always provide a 128x128 icon; it's used during @@ -6270,7 +6301,7 @@ declare namespace chrome { * @example * 'action_handlers': ['new_note'] */ - action_handlers?: app.runtime.actionType[]; + action_handlers?: ToStringLiteral[]; /** @todo TODO */ author?: any; /** @todo TODO */ @@ -6282,7 +6313,7 @@ declare namespace chrome { low_energy?: boolean; peripheral?: boolean; }; - /** @todo TODO */ + /** Keyboard command shorcuts */ commands?: { [name: string]: { suggested_key?: { @@ -6296,19 +6327,56 @@ declare namespace chrome { global?: boolean } }; - /** @todo TODO */ + /** + * @todo TODO ? + */ current_locale?: string; - /** @todo TODO */ + display_in_launcher?: boolean; + display_in_new_tab_page?: boolean; + /** + * The *event_rules* manifest property provides a mechanism to add rules that + * intercept, block, or modify web requests in-flight using **declarativeWebRequest** + * or take actions depending on the content of a page, without requiring permission + * to read the page's content using **declarativeContent**. + * @see[event_rules docs]{@link https://developer.chrome.com/extensions/manifest/event_rules} + */ event_rules?: { - event?: string; + /** Event name */ + event?: chrome.webViewRequest.DeclarativeWebRequestEventList; actions?: { - type: string; + /** Action type */ + type: chrome.webViewRequest.DeclarativeWebRequestActionsList; }[]; conditions?: { - type: string, - css?: string[] + /** Condition */ + type: chrome.webViewRequest.DeclarativeWebRequestConditionsList, + /** Arguments, see original condition docs in chrome.webViewRequest */ + [key: string]: any | any[]; }[]; }[]; + /** + * Declares which extensions, apps, and web pages can connect + * to your extension via runtime.connect and runtime.sendMessage. + */ + externally_connectable: { + /** + * The IDs of extensions or apps that are allowed to connect. + * If left empty or unspecified, no extensions or apps can connect. + * The wildcard '*' will allow all extensions and apps to connect. + */ + id: string[]; + /** + * The URL patterns for web pages that are allowed to connect. + * This does not affect content scripts. + * If left empty or unspecified, no web pages can connect. + */ + matches: string[]; + /** + * Determines if messages sent via `runtime.connect` or `runtime.sendMessage` + * are allowed to set `runtime.MessageSender.tlsChannelId`. + */ + accept_tls_channel_id: boolean; + } /** @todo TODO */ file_handlers?: { [key: string]: { @@ -6326,7 +6394,7 @@ declare namespace chrome { import?: { id: string; }[]; - /** @todo TODO */ + /** This value can be used to control the unique ID of an app when it is loaded during development. */ key?: string; /** @todo TODO */ kiosk?: { @@ -6341,27 +6409,42 @@ declare namespace chrome { kiosk_secondary_apps?: any; /** * @example - * "minimum_chrome_version": "33.0.1715.0" + * 'minimum_chrome_version': '33.0.1715.0' */ minimum_chrome_version?: string; - /** @todo TODO */ + /** One or more mappings from MIME types to the Native Client module that handles each type. */ nacl_modules?: { + /** The location of a Native Client manifest (a .nmf file) within the extension directory. */ path: string; + /** The MIME type for which the Native Client module will be registered as content handler. */ mime_type: string; }[]; - /** @todo TODO */ + /** + * Use the Chrome Identity API to authenticate users: + * the getAuthToken for users logged into their Google Account + * and the launchWebAuthFlow for users logged into a non-Google account. + */ oauth2?: { + /** You need to register your app in the Google APIs Console to get the client ID. */ client_id: string; - scopes?: string[]; + /** Applies to these scopes */ + scopes: string[]; }; - /** @todo TODO */ + /** + * Whether the app or extension is expected to work offline. + * When Chrome detects that it is offline, apps with this field set to true will be highlighted on the New Tab page. + */ offline_enabled?: boolean; /** - * Permissions that are optional and user controlled. + * Use the chrome.permissions API to request declared optional permissions + * at run time rather than install time, so users understand why the + * permissions are needed and grant only those that are necessary. */ optional_permissions?: Permission[] | Array; /** - * Permissions your application needs access to. + * Permissions help to limit damage if your app is compromised by malware. + * Some permissions are also displayed to users before installation, + * as detailed in Permission Warnings. */ permissions?: Permission[] | Array; /** @@ -6370,16 +6453,15 @@ declare namespace chrome { * @see[Chromium Source]{@link https://github.com/crosswalk-project/chromium-crosswalk/blob/af36cc3ce3f5fcb8033f16236725718f8012abfe/native_client_sdk/src/tools/fix_manifest.py} */ platforms?: { - nacl_arch: 'x86-64' | 'x86-32' | 'arm'; + nacl_arch: ToStringLiteral; sub_package_path: string; }[]; /** - * Technologies required by the app or extension. - * Hosting sites such as the Chrome Web Store may use - * this list to dissuade users from installing apps or - * extensions that will not work on their computer. - * Supported requirements currently include '3D' - * and 'plugins'; additional requirements checks + * Technologies required by the app. Hosting sites such + * as the Chrome Web Store may use this list to dissuade + * users from installing apps or extensions that will not + * work on their computer. Supported requirements currently + * include '3D' and 'plugins'; additional requirements checks * may be added in the future. */ requirements?: { @@ -6392,10 +6474,14 @@ declare namespace chrome { * } */ '3D'?: { - features?: Array; + features: 'webgl'; }; /** - * The 'plugins' requirement indicates if an app or extension requires NPAPI to run. This requirement is enabled by default when the manifest includes the 'plugins' field. For apps and extensions that still work when plugins aren't available, you can disable this requirement by setting NPAPI to false. You can also enable this requirement manually, by setting NPAPI to true, as shown in this example: + * The 'plugins' requirement indicates if an app or extension requires NPAPI to run. + * This requirement is enabled by default when the manifest includes the 'plugins' field. + * For apps and extensions that still work when plugins aren't available, + * you can disable this requirement by setting NPAPI to false. + * You can also enable this requirement manually, by setting NPAPI to true, as shown in this example: * 'requirements': { * 'plugins': { * 'npapi': true @@ -6403,16 +6489,21 @@ declare namespace chrome { * } */ plugins?: { - npapi?: boolean; + /** @default true */ + npapi: boolean; } - - [key: string]: any; }; /** - * @deprecated Warning: Starting in version 57, Chrome will no longer allow external web content (including embedded frames and scripts) inside sandboxed pages. Please use a webview instead. + * @deprecated + * Warning: Starting in version 57, Chrome will no longer allow external web content + * (including embedded frames and scripts) inside sandboxed pages. + * Please use a webview instead. */ sandbox?: { pages: string[]; + /** + * @default "sandbox allow-scripts allow-forms" + */ content_security_policy?: string; }; /** @@ -6428,7 +6519,7 @@ declare namespace chrome { * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ short_name?: string; - /** @todo TODO */ + /** @todo TODO What is this? */ signature?: any; /** * The sockets manifest property declares which permissions are available @@ -6446,8 +6537,8 @@ declare namespace chrome { * Unlike the local and sync storage areas, * the managed storage area requires its structure * to be declared as JSON Schema and is strictly validated by Chrome. - * This schema must be stored in a file indicated by the "managed_schema" - * property of the "storage" manifest key and declares the enterprise + * This schema must be stored in a file indicated by the 'managed_schema' + * property of the 'storage' manifest key and declares the enterprise * policies supported by the app. Policies are analogous to options * but are configured by a system administrator instead of the user, * allowing the app to be preconfigured for all users of an organization. @@ -6465,11 +6556,12 @@ declare namespace chrome { }; // system_indicator?: any; // Deprecated / removed: https://bugs.chromium.org/p/chromium/issues/detail?id=142450 /** - * Autoupdating - * Only set this if you want to host somewhere other than the store. + * If you publish using the Chrome Developer Dashboard, ignore this field. + * If you host your own extension or app: URL to an update manifest XML file. * **Warning** * As of M33, Windows stable / beta channel users can only * download extensions hosted in the Chrome Web Store + * @requires(not Windows) * (@see[Protecting Windows users from malicious extensions]{@link http://blog.chromium.org/2013/11/protecting-windows-users-from-malicious.html}). * @see[Documentation]{@link https://developer.chrome.com/apps/autoupdate} */ @@ -6480,13 +6572,14 @@ declare namespace chrome { * each having an identifier, a URL pattern, and a title. * Here's an example of how to specify url_handlers: * @example - * "view_foobar_presentation": { - * "matches": [ - * "https://www.foobar.com/presentation/view/*" + * 'view_foobar_presentation': { + * 'matches': [ + * 'https://www.foobar.com/presentation/view/*' * ], - * "title": "View FooBar presentation" + * 'title': 'View FooBar presentation' * } * @see[Documentation]{@link https://developer.chrome.com/apps/manifest/url_handlers} + * */ url_handlers?: { [name: string]: { @@ -6512,9 +6605,9 @@ declare namespace chrome { * version_name can be set to a descriptive version string and will be used for display purposes if present. * If no version_name is present, the version field will be used for display purposes as well. * @example - * "version_name": "0.8 beta" - * "version_name": "build rc3" - * "version_name": "Gold Edition" + * 'version_name': '0.8 beta' + * 'version_name': 'build rc3' + * 'version_name': 'Gold Edition' */ version_name?: string; /** @@ -6529,6 +6622,7 @@ declare namespace chrome { /** Webview partition list */ partitions: WebViewPartition[] } + } /** @@ -6593,10 +6687,10 @@ declare namespace chrome { * Requests an update check for this app/extension. * @since Chrome 25. * @param callback - * Parameter status: Result of the update check. One of: 'throttled', 'no_update', or 'update_available' + * Parameter status: Result of the update check. See enum RequestUpdateCheckStatus. * Optional parameter details: If an update is available, this contains more information about the available update. */ - function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + function requestUpdateCheck(callback: (status: ToStringLiteral, details?: UpdateCheckDetails) => void): void; /** * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op. @@ -6657,14 +6751,6 @@ declare namespace chrome { */ 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. - */ - function openOptionsPage(callback?: () => void): void; - interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } @@ -6704,17 +6790,27 @@ declare namespace chrome { */ 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. + * @required(Chrome OS Kiosk app) Currently, this event is only fired for Chrome OS kiosk apps. + * 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. * @since Chrome 29. */ - const onRestartRequired: chrome.events.Event<(reason: string) => void>; + const onRestartRequired: chrome.events.Event<(reason: ToStringLiteral) => 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. + * 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. */ const onUpdateAvailable: chrome.events.Event<(details: UpdateAvailableDetails) => void>; /** - * @deprecated since Chrome 33. Please use chrome.runtime.onRestartRequired. + * @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. */ const onBrowserUpdateAvailable: RuntimeEvent; @@ -6742,7 +6838,7 @@ declare namespace chrome { * Note: Starting with Chrome 33, this API is deprecated in favor of the sockets.udp, sockets.tcp * and sockets.tcpServer APIs. */ - // const socket: chrome.deprecated; // Removed to not be confused with chrome.sockets.* + // const socket: chrome.deprecatedButUsable; // Removed to not be confused with chrome.sockets.* /** chrome.sockets.tcp API */ namespace sockets { @@ -8306,7 +8402,7 @@ declare namespace chrome { // USB // ///////// /** - * @requires Permissions: "usb" + * @requires Permissions: 'usb' * @since Available since Chrome 26. * Use the chrome.usb API to interact with connected USB devices. * This API provides access to USB operations from within the context of an app. @@ -8444,7 +8540,7 @@ declare namespace chrome { } interface GenericTransferInfo { - /** The transfer direction ("in" or "out"). */ + /** The transfer direction ('in' or 'out'). */ direction: Direction; /** The target endpoint address. The interface containing this endpoint must be claimed. */ endpoint: integer; @@ -8488,9 +8584,9 @@ declare namespace chrome { type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; interface TransferInfo { - /** The transfer direction ("in" or "out"). */ + /** The transfer direction ('in' or 'out'). */ direction: Direction; - /** The transfer target. The target given by index must be claimed if "interface" or "endpoint". */ + /** The transfer target. The target given by index must be claimed if 'interface' or 'endpoint'. */ recipient: TransferRecipient; /** The request type. */ requestType: TransferRequestType; @@ -8723,13 +8819,13 @@ declare namespace chrome { } - //////////////////// - // VPN Provider - //////////////////// + ////////////////// + // VPN Provider // + ////////////////// /** * Use the chrome.vpnProvider API to implement a VPN client. - * Permissions: 'vpnProvider' - * Important: This API works only on Chrome OS. + * @requires(CrOS) Important: This API works only on Chrome OS. + * @requires Permissions: 'vpnProvider' * @since Chrome 43. */ namespace vpnProvider { @@ -8741,11 +8837,23 @@ declare namespace chrome { /** 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. + * 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. */ exclusionList: string[]; /** - * 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. + * 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[]; /** A list of search domains. (default: no search domain) */ @@ -8849,14 +8957,46 @@ declare namespace chrome { namespace webRequest { type ResourceType = - "main_frame" | "sub_frame" | "stylesheet" | - "script" | "image" | "font" | "object" | - "xmlhttprequest" | "ping" | "csp_report" - | "media" | "websocket" | "other"; + 'main_frame' | 'sub_frame' | 'stylesheet' | + 'script' | 'image' | 'font' | 'object' | + 'xmlhttprequest' | 'ping' | 'csp_report' + | 'media' | 'websocket' | 'other'; } namespace webViewRequest { - type Stage = "onBeforeRequest" | "onBeforeSendHeaders" | "onHeadersReceived" | "onAuthRequired"; + type Stage = 'onBeforeRequest' | 'onBeforeSendHeaders' | 'onHeadersReceived' | 'onAuthRequired'; + type DeclarativeWebRequestEventList = + 'declarativeContent.onBeforeRequest' | + 'declarativeContent.onBeforeSendHeaders' | + 'declarativeContent.onSendHeaders' | + 'declarativeContent.onHeadersReceived' | + 'declarativeContent.onAuthRequired' | + 'declarativeContent.onResponseStarted' | + 'declarativeContent.onBeforeRedirect' | + 'declarativeContent.onCompleted' | + 'declarativeContent.onErrorOccured' | + 'declarativeContent.onRequest' | + 'declarativeContent.onMessage'; + type DeclarativeWebRequestConditionsList = + 'declarativeContent.PageStateMatcher'; + type DeclarativeWebRequestActionsList = + 'declarativeWebRequest.AddRequestCookie' | + 'declarativeWebRequest.AddResponseCookie' | + 'declarativeWebRequest.AddResponseHeader' | + 'declarativeWebRequest.CancelRequest' | + 'declarativeWebRequest.EditRequestCookie' | + 'declarativeWebRequest.EditResponseCookie' | + 'declarativeWebRequest.RedirectRequest' | + 'declarativeWebRequest.RedirectToTransparentImage' | + 'declarativeWebRequest.RedirectToEmptyDocument' | + 'declarativeWebRequest.RedirectByRegEx' | + 'declarativeWebRequest.RemoveRequestCookie' | + 'declarativeWebRequest.RemoveResponseCookie' | + 'declarativeWebRequest.RemoveRequestHeader' | + 'declarativeWebRequest.RemoveResponseHeader' | + 'declarativeWebRequest.SetRequestHeader' | + 'declarativeWebRequest.SendMessageToExtension' | + 'declarativeWebRequest.IgnoreRules'; interface HeaderFilter { /** Matches if the header name starts with the specified string. */ namePrefix?: string; @@ -9396,6 +9536,18 @@ declare namespace chrome { interface OnMessageEvent extends chrome.events.Event<(details: OnMessageEventDetails) => void> { } } + ///////////// + // CLASSES // + ///////////// + + /** + * New Chrome Event + * @constructor + */ + const Event: { + new (): chrome.events.Event; + } + ///////////// // METHODS // ///////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 9842da12b5..3a967f8873 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,6 +1,12 @@ import runtime = chrome.app.runtime; const cwindow = chrome.app.window; +// APP.WINDOW + +// Test enums +cwindow.WindowType.PANEL; +cwindow.State.FULLSCREEN; + const createOptions: chrome.app.CreateWindowOptions = { id: 'My Window', bounds: { @@ -194,14 +200,9 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "version": "2.1", "minimum_chrome_version": "33.0.1715.0", "default_locale": "en", - "options_page": "options.html", "chrome_url_overrides": { "newtab": "app.html" }, - "options_ui": { - "chrome_style": true, - "page": "options.html" - }, "launch": { "web_url": "https://developer.mbed.org/compiler/#nav:/;" }, @@ -237,7 +238,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "usb", "metricsPrivate", "networkingPrivate", "bluetooth", - "tabCapture", "unlimitedStorage", { "fileSystem": ["write", "retainEntries", "directory"] }, "clipboardRead", @@ -248,8 +248,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "mdns", "gcm", "power", - "clipboardRead", - "clipboardWrite", "cookies", "tabs", "http://*/*", "https://*/*", @@ -324,11 +322,7 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { } }, "sockets": { - "udp": { "bind": "*", "send": "*" }, "tcpServer": { "listen": "" }, - "tcp": { - "connect": "*:*" - }, "tcp": { "connect": ["*:5555", "*:5559"] }, "udp": { "bind": ["*:5554", "*:5556"], "multicastMembership": "", "send": ["*:5554", "*:5556"] } }, @@ -382,7 +376,7 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "content_security_policy": "sandbox allow-scripts allow-popups; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com/ga.js;", "pages": ["sandbox.html"] }, - "content_security_policy": "script-src 'self' https://www.gstatic.com/; object-src 'self'" + "content_security_policy": "script-src 'self' https://www.gstatic.com/; object-src 'self'", "file_handlers": { "image": { "types": [ @@ -394,7 +388,7 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "types": [ "text/*" ], - "extensions": ["abap", "as", "ada", "adb", "ads", "conf", "asciidoc", "asm", "ahk", "bat", "c", "cpp", "h", "hpp", "cc", "cirru", "clj", "cob", "cbl", "ccp", "cb2", "cof", "coffee", "cfm", "cfc", "cfml", "cs", "css", "curly", "dart", "diff", "djt", "djhtml", "dt", "d", "dot", "ejs", "erl", "frt", "ftl", "feature", "glsl", "go", "groovy", "haml", "hbs", "handlebars", "hs", "hx", "htm", "html", "erb", "ini", "jk", "jack", "jade", "java", "class", "js", "gs", "javascript", "jsoniq", "json", "jsp", "jsx", "jl", "latex", "less", "liquid", "lisp", "ls", "logic", "logiql", "lsl", "lua", "lp", "lucene", "make", "makefile", "mak", "md", "mat", "mel", "mc", "mush", "mysql", "nix", "m", "mm", "ml", "mli", "mll", "pas", "pl", "pm", "pgsql", "php", "inc", "text", "txt", "readme", "log", "ps1", "psm1", "pro", "p", "plg", "properties", "proto", "py", "rdoc", "rd", "rhtml", "r", "rb", "rbx", "rs", "sass", "scad", "scala", "scm", "ss", "scss", "sh", "sjs", "smarty", "snippets", "soy", "space", "sql", "styl", "stylus", "svg", "tcl", "tex", "textile", "tmsnippet", "toml", "twig", "ts", "vbs", "vbe", "vm", "v", "vhd", "vhdl", "xml", "rss", "atom", "xhtml", "xquery", "xq", "yaml", "yml", "mcc"] + "extensions": ["abap", "as", "ada", "adb", "ads", "cfm", "cfc", "cfml", "cs", "css", "dt", "d", "dot", "ejs", "erl", "frt", "ftl", "html", "erb", "ini", "jk", "java", "class", "js", "gs", "javascript", "jsoniq", "json", "jsp", "jsx", "lisp", "ls", "logic", "make", "makefile", "mak", "md", "mysql", "nix", "m", "php", "inc", "text", "txt", "log", "ps1", "rd", "sass", "scad", "scala", "scm", "ss", "scss", "sh", "sjs", "sql", "svg", "tcl", "tex", "ts", "vbs", "vbe", "vm", "v", "vhd", "vhdl", "xml", "rss", "atom", "xhtml", "yaml", "yml", "mcc"] }, "any": { "extensions": [ @@ -402,22 +396,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "skrup" ] }, - "7zip": { - "extensions": ["7z"], - "types": ["application/x-7z", "application/x-7z-compressed"] - }, - "Z": { - "extensions": ["Z"], - "types": ["application/x-compress"] - }, - "ar": { - "extensions": ["a"], - "types": ["application/x-archive"] - }, - "bzip2": { - "extensions": ["bz", "bz2"], - "types": ["application/x-bzip", "application/x-bzip2"] - }, "cab": { "extensions": ["cab"], "types": ["application/x-cab"] @@ -475,10 +453,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "types": ["application/java-archive", "application/x-chrome-extension"] } }, - "file_system_provider_capabilities": { - "multipleMounts": true, - "source": "file" - }, "requirements": { "3D": { "features": ["webgl"] @@ -490,7 +464,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "oauth2": { // client_id below is specifc to the application key. Follow the // documentation to obtain one for your app. - "auto_approve": true, "client_id": "1111111222333.apps.googleusercontent.com", "scopes": ["https://www.googleapis.com/auth/plus.login"] }, @@ -551,16 +524,9 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "64": "assets/icon-64x64.png", "128": "icon128.png" }, - "action_handlers": ["new_note"], - "offline_enabled": true, - "sockets": { - "tcp": { - "connect": "*:*" - } - } + "action_handlers": ["new_note"] } - // ALARMS chrome.alarms.create('name', { @@ -697,6 +663,10 @@ chrome.contextMenus.onClicked.addListener((info) => { chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); +// EVENTS + +const e = new chrome.Event(); // Used const instead of class to be able to return the interface +e.addListener(() => { }); // HID @@ -800,21 +770,23 @@ chrome.runtime.sendMessage( chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); chrome.power.requestKeepAwake('display'); -type IEnum = F; -type EnumType< - C extends Object, - T = undefined, - K = keyof C, - V = K extends keyof C ? Exclude : never> = IEnum; -type ETEST = EnumType<{ - SYSTEM: "system", - DISPLAY: "display" -}>; -let etest: ETEST; -etest = 'display'; -etest = 'DISPLAY'; -etest = etest.DISPLAY; +// RUNTIME +chrome.runtime.reload(); +chrome.runtime.requestUpdateCheck((status, details) => { + if (status === chrome.runtime.RequestUpdateCheckStatus.THROTTLED) { + if (details !== undefined) { + console.log(details.version); + } else { + console.log('Unknown'); + } + } +}); +const os = chrome.runtime.PlatformOs.ANDROID; +if (os === 'android') { + console.log('Enum ok'); +} +const appId = chrome.runtime.id; // SOCKETS // https://developer.chrome.com/apps/sockets_tcp From f464124670aae15384082b73163879eb9f8757c3 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 9 Aug 2018 16:56:56 +0200 Subject: [PATCH 042/289] Checked through chromium sources to make the typings better. --- types/chrome-apps/index.d.ts | 313 +++++++++++++++++++++----------- types/chrome-apps/test/index.ts | 2 - 2 files changed, 208 insertions(+), 107 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 06acde4e73..d6605bea48 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -11,6 +11,19 @@ // WebView ref // // https://chromium.googlesource.com/chromium/src/+/68.0.3432.1/chrome/common/extensions/api/webview_tag.json // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Extra sources in addition to the Chromium source code and official documentation: +// +// Manifest: +// - https://github.com/jasonkarns/chrome-extension-manifest-schema/blob/master/manifest.schema.cson +// - https://github.com/chromium/chromium/blob/master/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc#L155 +// - https://chromium.googlesource.com/chromium/src.git/+/master/extensions/common/api/_manifest_features.json +// - https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/ +// - https://chromium.googlesource.com/chromium/src/+/master/extensions/common/manifest_constants.cc +// +// Permissions: +// - https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/_permission_features.json +// declare namespace chrome { ////////////// @@ -5958,33 +5971,40 @@ declare namespace chrome { type ChromeOSOnlyPermissions = 'certificateProvider' | 'clipboard' | + 'dns' | 'documentScan' | - 'enterprise.platformKeys' | - 'fileBrowserHandler' | - 'fileSystemProvider' | - 'enterprise' | // ? + 'enterprise' | 'enterprise.platformKeys' | 'enterprise.deviceAttributes' | + 'fileBrowserHandler' | + 'fileSystemProvider' | 'networking.config' | 'platformKeys' | - 'virtualKeyboard' | 'vpnProvider' | 'wallpaper'; + type DevOnly = + 'app.window.alpha' | + 'audio' | // Dev channel except for ChromeOS kiosk + 'diagnostics' | + 'displaySource'; + type KioskOnlyPermissions = - 'networking.onc'; + 'audio' | + 'networking.onc' | + 'system.powerSource' | + 'virtualKeyboard'; /** Undocumented but used permissions */ type UndocumentedPermissions = + 'appview' | 'experimental' | - 'app.window.alpha' | - 'app.window.shape' | + 'app.window.shape' | // Works on stable 'geolocation' | 'alwaysOnTopWindows' | 'overrideEscFullscreen' | 'geolocation' | 'experimental' | - 'diagnostics' | 'app.window.fullscreen' | 'app.window.fullscreen.overrideEsc'; @@ -5992,7 +6012,6 @@ declare namespace chrome { 'alarms' | 'app.window.fullscreen' | 'app.window.fullscreen.overrideEsc' | - 'audio' | 'audioCapture' | 'background' | 'browser' | @@ -6001,8 +6020,6 @@ declare namespace chrome { 'contextMenus' | 'desktopCapture' | 'diagnostics' | - 'displaySource' | - 'dns' | 'experimental' | 'fileSystem' | 'gcm' | @@ -6017,7 +6034,10 @@ declare namespace chrome { 'pointerLock' | 'power' | 'printerProvider' | - // 'serial' | // Deprecated + /** Runtime is not actually a permisison, but some sysems check these values to verify restrictions. */ + 'runtime' | + /** @deprecated Serial is deprecated */ + 'serial' | 'signedInDevices' | 'storage' | 'syncFileSystem' | @@ -6029,16 +6049,16 @@ declare namespace chrome { 'tts' | 'unlimitedStorage' | 'usb' | + 'usbDevices' | 'videoCapture' | 'webview' | ChromeOSOnlyPermissions | + FileSystemPermission | KioskOnlyPermissions | MediaGalleriesPermission | SocketPermission | - PrivatePermissions | - USBDevicesPermission | - FileSystemPermission | - UrlPermission; + UrlPermission | + USBDevicesPermission; interface MediaGalleriesPermission { mediaGalleries: Array<'read' | 'allAutoDetected'>; @@ -6047,7 +6067,10 @@ declare namespace chrome { usbDevices: { vendorId: integer, productId: integer }[] } interface FileSystemPermission { - fileSystem: Array<'write' | 'retainEntries' | 'directory'>; + /** + * 'requestFileSystem' is only for ChromeOS + */ + fileSystem: Array<'write' | 'retainEntries' | 'directory' | 'requestFileSystem'>; } interface SocketPermission { /** @@ -6063,19 +6086,6 @@ declare namespace chrome { socket: string[]; } - /** - * Only for whitelisted internal apps and extensions - * @private - * @internal - */ - type PrivatePermissions = 'Private' - | 'metricsPrivate' - | 'developerPrivate' - | 'activityLogPrivate' - | 'networkingPrivate' - | 'terminalPrivate'; - - /// For chrome managed storage type JSONBasicTypes = 'integer' | 'string' | 'number'; @@ -6168,36 +6178,7 @@ declare namespace chrome { } type AutomationOptions = boolean | AutomationDesktop | AutomationNonInteractive; - interface InvalidManifest extends ValidManifest { - // - // Never types - should never exist - // Are declared to prevent use since many - // legacy app are using them. Will result - // in errors. Many examples and code bases - // have these included. - // - - /** Not for packaged apps */ - options_ui?: never; - /** Not for packaged apps */ - options_page?: never; - /** Not for packaged apps */ - browser_action?: never; - /** - * Not for packaged apps - * Only for extensions and legacy packaged apps - */ - content_security_policy?: never; - /** - * Not for packaged apps - * Only for extensions and legacy packaged apps - */ - chrome_url_overrides?: never; - } - - type Manifest = ValidManifest | InvalidManifest; - - interface ValidManifest { + interface PartialManifest { ////////////// // REQUIRED // ////////////// @@ -6210,8 +6191,8 @@ declare namespace chrome { app: { background: { scripts?: string[]; - } | never; - } | never; + }; + }; /** * One integer specifying the version of the manifest file format your package requires. * As of Chrome 18, developers should specify 2 (without quotes). @@ -6292,7 +6273,7 @@ declare namespace chrome { ////////////// /** - * @requires(CrOS) **This API is only available on ChromeOS.** + * @requires(CrOS) **Will only work on Chrome OS.** * @description * The action_handlers manifest property declares which user actions or intents the * application supports; these can serve as alternate launch points for your application. @@ -6302,20 +6283,46 @@ declare namespace chrome { * 'action_handlers': ['new_note'] */ action_handlers?: ToStringLiteral[]; + + /** + * App author information + * @see[Not implemented anywhere in code]{@link https://github.com/chromium/chromium/blob/master/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc#L46} + */ + author?: { + name: string, + email: string, + } | any; + /** @todo TODO */ - author?: any; - /** @todo TODO */ - automation?: AutomationOptions; - /** @todo TODO */ + automation?: AutomationOptions | boolean; + + /** + * Note: The "bluetooth" manifest permission is used by the + * chrome.bluetooth, chrome.bluetoothSocket and + * chrome.bluetoothLowEnergy APIs. + * @requires Platforms: Chrome OS, Windows and Mac + */ bluetooth?: { - uuids?: string[]; - socket?: boolean; - low_energy?: boolean; - peripheral?: boolean; + uuids?: string[], + socket?: boolean, + low_energy?: boolean, + peripheral?: boolean, }; - /** Keyboard command shorcuts */ + /** + * Use the commands API to add keyboard shortcuts that trigger actions in your app. + * E.g. an action to open the browser action or send a command to the app. + */ commands?: { [name: string]: { + /** + * Keys can be provided matching this pattern: + * ^(Ctrl|Command|MacCtrl|Alt|Option)\\+(Shift\\+)?[A-Z] + * @example + * "suggested_key": { + * "default": "Ctrl+Shift+Y", + * "mac": "Command+Shift+Y" + * }, + */ suggested_key?: { default?: string; windows?: string; @@ -6323,15 +6330,19 @@ declare namespace chrome { chromeos?: string; linux?: string; }; + /** Command description */ description?: string; + /** Global scope? */ global?: boolean } }; /** - * @todo TODO ? + * An implementation detail (actually written by Chrome, not the app author). */ - current_locale?: string; + readonly current_locale?: string; + /** Restricted to whitelist */ display_in_launcher?: boolean; + /** Restricted to whitelist */ display_in_new_tab_page?: boolean; /** * The *event_rules* manifest property provides a mechanism to add rules that @@ -6342,18 +6353,19 @@ declare namespace chrome { */ event_rules?: { /** Event name */ - event?: chrome.webViewRequest.DeclarativeWebRequestEventList; + event?: chrome.webViewRequest.DeclarativeWebRequestEventList, actions?: { /** Action type */ - type: chrome.webViewRequest.DeclarativeWebRequestActionsList; + type: chrome.webViewRequest.DeclarativeWebRequestActionsList, }[]; conditions?: { /** Condition */ type: chrome.webViewRequest.DeclarativeWebRequestConditionsList, /** Arguments, see original condition docs in chrome.webViewRequest */ - [key: string]: any | any[]; - }[]; + [key: string]: any | any[], + }[], }[]; + /** * Declares which extensions, apps, and web pages can connect * to your extension via runtime.connect and runtime.sendMessage. @@ -6364,54 +6376,51 @@ declare namespace chrome { * If left empty or unspecified, no extensions or apps can connect. * The wildcard '*' will allow all extensions and apps to connect. */ - id: string[]; + id: string[], /** * The URL patterns for web pages that are allowed to connect. * This does not affect content scripts. * If left empty or unspecified, no web pages can connect. */ - matches: string[]; + matches: string[], /** * Determines if messages sent via `runtime.connect` or `runtime.sendMessage` * are allowed to set `runtime.MessageSender.tlsChannelId`. */ - accept_tls_channel_id: boolean; + accept_tls_channel_id: boolean, } + /** @todo TODO */ file_handlers?: { [key: string]: { - extensions?: Array<'*' | string | { include_directories: boolean }>; - types?: Array<'*' | string | { include_directories: boolean }>; - } - }[]; + extensions?: Array<'*' | string | { include_directories: boolean }>, + types?: Array<'*' | string | { include_directories: boolean }>, + }, + }; + /** @todo TODO */ file_system_provider_capabilities?: { - configurable?: boolean; - multiple_mounts?: boolean; - source?: 'network' | string; + configurable?: boolean, + multiple_mounts?: boolean, + watchable?: boolean, + source?: 'network' | string, }; + /** @todo TODO */ import?: { id: string; }[]; + /** This value can be used to control the unique ID of an app when it is loaded during development. */ key?: string; - /** @todo TODO */ - kiosk?: { - always_update: any; - required_platform_version: any; - }; - /** @todo TODO */ - kiosk_enabled?: boolean; - /** @todo TODO */ - kiosk_only?: boolean; - /** @todo TODO */ - kiosk_secondary_apps?: any; + /** + * The minimum version of Chrome that your app, if any. * @example * 'minimum_chrome_version': '33.0.1715.0' */ minimum_chrome_version?: string; + /** One or more mappings from MIME types to the Native Client module that handles each type. */ nacl_modules?: { /** The location of a Native Client manifest (a .nmf file) within the extension directory. */ @@ -6419,6 +6428,7 @@ declare namespace chrome { /** The MIME type for which the Native Client module will be registered as content handler. */ mime_type: string; }[]; + /** * Use the Chrome Identity API to authenticate users: * the getAuthToken for users logged into their Google Account @@ -6430,23 +6440,27 @@ declare namespace chrome { /** Applies to these scopes */ scopes: string[]; }; + /** * Whether the app or extension is expected to work offline. * When Chrome detects that it is offline, apps with this field set to true will be highlighted on the New Tab page. */ offline_enabled?: boolean; + /** * Use the chrome.permissions API to request declared optional permissions * at run time rather than install time, so users understand why the * permissions are needed and grant only those that are necessary. */ optional_permissions?: Permission[] | Array; + /** * Permissions help to limit damage if your app is compromised by malware. * Some permissions are also displayed to users before installation, * as detailed in Permission Warnings. */ permissions?: Permission[] | Array; + /** * Native Client * @see[NDK Docs]{@link https://github.com/crosswalk-project/chromium-crosswalk/blob/af36cc3ce3f5fcb8033f16236725718f8012abfe/native_client_sdk/src/doc/devguide/distributing.rst} @@ -6456,6 +6470,7 @@ declare namespace chrome { nacl_arch: ToStringLiteral; sub_package_path: string; }[]; + /** * Technologies required by the app. Hosting sites such * as the Chrome Web Store may use this list to dissuade @@ -6466,7 +6481,14 @@ declare namespace chrome { */ requirements?: { /** - * The '3D' requirement denotes GPU hardware acceleration. The 'webgl' requirement refers to the WebGL API. For more information on Chrome 3D graphics support, see the help article on WebGL and 3D graphics. You can list the 3D-related features your app requires, as demonstrated in the following example: + * The '3D' requirement denotes GPU hardware acceleration. + * + * The 'webgl' requirement refers to the WebGL API. + * For more information on Chrome 3D graphics support, + * see the help article on WebGL and 3D graphics. + * You can list the 3D-related features your app requires, + * as demonstrated in the following example: + * @example * 'requirements': { * '3D': { * 'features': ['webgl'] @@ -6474,14 +6496,19 @@ declare namespace chrome { * } */ '3D'?: { - features: 'webgl'; + /** List of the 3D-related features your app requires. */ + features: ['webgl']; }; + /** - * The 'plugins' requirement indicates if an app or extension requires NPAPI to run. + * The 'plugins' requirement indicates if an app requires NPAPI to run. + * * This requirement is enabled by default when the manifest includes the 'plugins' field. * For apps and extensions that still work when plugins aren't available, * you can disable this requirement by setting NPAPI to false. - * You can also enable this requirement manually, by setting NPAPI to true, as shown in this example: + * You can also enable this requirement manually, + * by setting NPAPI to true as shown in this example: + * @example * 'requirements': { * 'plugins': { * 'npapi': true @@ -6493,6 +6520,7 @@ declare namespace chrome { npapi: boolean; } }; + /** * @deprecated * Warning: Starting in version 57, Chrome will no longer allow external web content @@ -6506,6 +6534,7 @@ declare namespace chrome { */ 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 @@ -6519,8 +6548,10 @@ declare namespace chrome { * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} */ short_name?: string; + /** @todo TODO What is this? */ signature?: any; + /** * The sockets manifest property declares which permissions are available * for the sockets.udp, sockets.tcp and sockets.tcpServer APIs. @@ -6533,6 +6564,7 @@ declare namespace chrome { /** The udp manifest property declares which sockets.udp operations an app can issue. */ udp?: SocketUdpPermission; }; + /** * Unlike the local and sync storage areas, * the managed storage area requires its structure @@ -6554,6 +6586,7 @@ declare namespace chrome { */ managed_schema: string; }; + // system_indicator?: any; // Deprecated / removed: https://bugs.chromium.org/p/chromium/issues/detail?id=142450 /** * If you publish using the Chrome Developer Dashboard, ignore this field. @@ -6566,6 +6599,7 @@ declare namespace chrome { * @see[Documentation]{@link https://developer.chrome.com/apps/autoupdate} */ update_url?: string; + /** * Used by packaged apps to specify URL patterns the app wants to intercept and handle. * An app can define multiple URL handlers under this manifest entry, @@ -6592,6 +6626,7 @@ declare namespace chrome { title?: string; } }; + /** The usbPrinters manifest property declares which USB printers are supported by an app using the printerProvider API. */ usb_printers?: { /** @@ -6601,6 +6636,7 @@ declare namespace chrome { */ filters: chrome.usb.DeviceFilterStrict[]; }; + /** * version_name can be set to a descriptive version string and will be used for display purposes if present. * If no version_name is present, the version field will be used for display purposes as well. @@ -6610,6 +6646,7 @@ declare namespace chrome { * 'version_name': 'Gold Edition' */ version_name?: string; + /** * By default, webviews are prevented from loading any resources packaged with the app. * However, webview partitions may be granted access to these resources via a webview.partitions @@ -6622,9 +6659,75 @@ declare namespace chrome { /** Webview partition list */ partitions: WebViewPartition[] } - } + /** + * Manifest for Chrome OS Kiosk apps + * @requires(CrOS Kiosk App) **Only for Chrome OS Kiosk Apps.** + */ + interface ValidKioskManifest extends PartialManifest { + /** + * Enable this app to be used as a kiosk app. + */ + kiosk_enabled: true; + + /** Kiosk settings */ + kiosk?: { + /** + * If the key is specified and its value is true, it allows the app to + * be always updated regardless of whether the underlying platform is + * compliant or not. If the value is false or the key is not specified, + * the required platform version is respected and the app update is + * deferred until the underlying platform becomes compliant. + */ + always_update?: boolean; + required_platform_version?: string; + }; + + /** + * This app can only be used as a kiosk app on Chrome OS + */ + kiosk_only?: boolean; + + /** + * Not useful since it will prevent app from running. + * @see[Source]{@link https://github.com/chromium/chromium/blob/master/chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.cc#L155} + */ + kiosk_secondary_apps?: any; + } + interface ValidNonKioskManifest extends PartialManifest { + kiosk_enabled?: false; + } + + interface InvalidManifest extends PartialManifest { + // + // Never types - should never exist + // Are declared to prevent use since many + // legacy app are using them. Will result + // in errors. Many examples and code bases + // have these included. + // + + /** Not for packaged apps */ + options_ui?: never; + /** Not for packaged apps */ + options_page?: never; + /** Not for packaged apps */ + browser_action?: never; + /** + * Not for packaged apps + * Only for extensions and legacy packaged apps + */ + content_security_policy?: never; + /** + * Not for packaged apps + * Only for extensions and legacy packaged apps + */ + chrome_url_overrides?: never; + } + + type Manifest = ValidKioskManifest | C | ValidNonKioskManifest | InvalidManifest; + /** * 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. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 3a967f8873..1e6d54b4f1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -294,7 +294,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "name": "Your name here", "email": "Email@yourmail.com" }, - "author": "hei", "update_url": "https://clients2.google.com/service/update2/crx", "version_name": "10.0.12-stable", "kiosk_enabled": true, @@ -371,7 +370,6 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "automation": { "desktop": true }, - "automation": true, "sandbox": { "content_security_policy": "sandbox allow-scripts allow-popups; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com/ga.js;", "pages": ["sandbox.html"] From 86f3c3d26c91638ef8069c70228275767869617e Mon Sep 17 00:00:00 2001 From: felix-hoc Date: Fri, 10 Aug 2018 10:44:01 +0200 Subject: [PATCH 043/289] Add types for winston-syslog v2.0.0, move existing types to v1/ --- types/winston-syslog/index.d.ts | 55 +++++++++++-------- types/winston-syslog/package.json | 2 +- types/winston-syslog/tsconfig.json | 4 +- types/winston-syslog/v1/index.d.ts | 25 +++++++++ types/winston-syslog/v1/package.json | 6 ++ types/winston-syslog/v1/tsconfig.json | 32 +++++++++++ types/winston-syslog/v1/tslint.json | 3 + .../winston-syslog/v1/winston-syslog-tests.ts | 35 ++++++++++++ types/winston-syslog/winston-syslog-tests.ts | 19 +++---- 9 files changed, 144 insertions(+), 37 deletions(-) create mode 100644 types/winston-syslog/v1/index.d.ts create mode 100644 types/winston-syslog/v1/package.json create mode 100644 types/winston-syslog/v1/tsconfig.json create mode 100644 types/winston-syslog/v1/tslint.json create mode 100644 types/winston-syslog/v1/winston-syslog-tests.ts diff --git a/types/winston-syslog/index.d.ts b/types/winston-syslog/index.d.ts index 816274ded8..bd0ee54cdf 100644 --- a/types/winston-syslog/index.d.ts +++ b/types/winston-syslog/index.d.ts @@ -1,25 +1,36 @@ -// Type definitions for winston-syslog 1.0 -// Project: https://github.com/indexzero/winston-syslog#readme -// Definitions by: Chris Barth +// Type definitions for winston-syslog v2.0.0 +// Project: https://github.com/winstonjs/winston-syslog +// Definitions by: Felix Hochgruber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as winston from "winston"; -export interface SyslogTransportOptions extends winston.GenericTextTransportOptions { - host?: string; - port?: number; - path?: string; - protocol?: string; - pid?: number; - facility?: string; - localhost?: string; - type?: string; - app_name?: string; - eol?: string; -} -export class Syslog extends winston.Transport implements winston.TransportInstance { -} -declare module "winston" { - interface Transports { - Syslog: Syslog; - } +import * as Transport from 'winston-transport'; +import * as dgram from 'dgram'; +import * as net from 'net'; + +declare module 'winston-syslog' { + + export interface SyslogTransportOptions extends Transport.TransportStreamOptions { + host?: string; + port?: number; + path?: string; + protocol?: string; + pid?: number; + facility?: string; + localhost?: string; + type?: string; + app_name?: string; + eol?: string; + } + + interface SyslogTransportInstance extends Transport { + + producer: any; + socket: dgram.Socket | net.Socket; + + connect(callback: (err: (true | null)) => any): void; + + new(options?: SyslogTransportOptions): SyslogTransportInstance; + } } + +export const Syslog: SyslogTransportInstance; diff --git a/types/winston-syslog/package.json b/types/winston-syslog/package.json index 33e1a4f018..0aa4cf368f 100644 --- a/types/winston-syslog/package.json +++ b/types/winston-syslog/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "@types/winston": "^2.3.9" + "winston": "^3.0.0" } } diff --git a/types/winston-syslog/tsconfig.json b/types/winston-syslog/tsconfig.json index e11a89c680..2c0a6050a4 100644 --- a/types/winston-syslog/tsconfig.json +++ b/types/winston-syslog/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "winston-syslog-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/winston-syslog/v1/index.d.ts b/types/winston-syslog/v1/index.d.ts new file mode 100644 index 0000000000..816274ded8 --- /dev/null +++ b/types/winston-syslog/v1/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for winston-syslog 1.0 +// Project: https://github.com/indexzero/winston-syslog#readme +// Definitions by: Chris Barth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as winston from "winston"; +export interface SyslogTransportOptions extends winston.GenericTextTransportOptions { + host?: string; + port?: number; + path?: string; + protocol?: string; + pid?: number; + facility?: string; + localhost?: string; + type?: string; + app_name?: string; + eol?: string; +} +export class Syslog extends winston.Transport implements winston.TransportInstance { +} +declare module "winston" { + interface Transports { + Syslog: Syslog; + } +} diff --git a/types/winston-syslog/v1/package.json b/types/winston-syslog/v1/package.json new file mode 100644 index 0000000000..33e1a4f018 --- /dev/null +++ b/types/winston-syslog/v1/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/winston": "^2.3.9" + } +} diff --git a/types/winston-syslog/v1/tsconfig.json b/types/winston-syslog/v1/tsconfig.json new file mode 100644 index 0000000000..610ded1b9b --- /dev/null +++ b/types/winston-syslog/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "winston-syslog": [ + "winston-syslog/v1" + ], + "winston-syslog/*": [ + "winston-syslog/v1/*" + ] + }, + "noEmit": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "winston-syslog-tests.ts" + ] +} diff --git a/types/winston-syslog/v1/tslint.json b/types/winston-syslog/v1/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/winston-syslog/v1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/winston-syslog/v1/winston-syslog-tests.ts b/types/winston-syslog/v1/winston-syslog-tests.ts new file mode 100644 index 0000000000..a08b80b045 --- /dev/null +++ b/types/winston-syslog/v1/winston-syslog-tests.ts @@ -0,0 +1,35 @@ +import winston = require('winston'); +import { SyslogTransportOptions } from 'winston-syslog'; + +const str = ""; +const bool = true; +const num = 1; +const obj: any = {}; + +const syslogOptions: SyslogTransportOptions = { + host: str, + port: num, + path: str, + protocol: str, + pid: num, + facility: str, + localhost: str, + type: str, + app_name: str, + eol: str, + json: bool, + colorize: bool, + colors: str, + prettyPrint: bool, + showLevel: bool, + label: str, + depth: num, +}; + +winston.add(winston.transports.Syslog, syslogOptions); + +const logger: winston.LoggerInstance = new (winston.Logger)({ + transports: [ + new (winston.transports.Syslog)(syslogOptions), + ] +}); diff --git a/types/winston-syslog/winston-syslog-tests.ts b/types/winston-syslog/winston-syslog-tests.ts index a08b80b045..66a4a71e17 100644 --- a/types/winston-syslog/winston-syslog-tests.ts +++ b/types/winston-syslog/winston-syslog-tests.ts @@ -1,5 +1,5 @@ import winston = require('winston'); -import { SyslogTransportOptions } from 'winston-syslog'; +import { Syslog, SyslogTransportOptions } from 'winston-syslog'; const str = ""; const bool = true; @@ -16,20 +16,15 @@ const syslogOptions: SyslogTransportOptions = { localhost: str, type: str, app_name: str, - eol: str, - json: bool, - colorize: bool, - colors: str, - prettyPrint: bool, - showLevel: bool, - label: str, - depth: num, + eol: str }; -winston.add(winston.transports.Syslog, syslogOptions); +const syslogTransport = new Syslog(syslogOptions); -const logger: winston.LoggerInstance = new (winston.Logger)({ +winston.add(syslogTransport); + +const logger: winston.Logger = winston.createLogger({ transports: [ - new (winston.transports.Syslog)(syslogOptions), + syslogTransport ] }); From cb332fb8495d401358b25ae31395bc630612b2f6 Mon Sep 17 00:00:00 2001 From: felix-hoc Date: Fri, 10 Aug 2018 11:24:46 +0200 Subject: [PATCH 044/289] Fix some linting issues. --- types/winston-syslog/index.d.ts | 40 +++++++++++++++------------------ 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/types/winston-syslog/index.d.ts b/types/winston-syslog/index.d.ts index bd0ee54cdf..d1517cc957 100644 --- a/types/winston-syslog/index.d.ts +++ b/types/winston-syslog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for winston-syslog v2.0.0 +// Type definitions for winston-syslog 2.0 // Project: https://github.com/winstonjs/winston-syslog // Definitions by: Felix Hochgruber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,30 +7,26 @@ import * as Transport from 'winston-transport'; import * as dgram from 'dgram'; import * as net from 'net'; -declare module 'winston-syslog' { +export interface SyslogTransportOptions extends Transport.TransportStreamOptions { + host?: string; + port?: number; + path?: string; + protocol?: string; + pid?: number; + facility?: string; + localhost?: string; + type?: string; + app_name?: string; + eol?: string; +} - export interface SyslogTransportOptions extends Transport.TransportStreamOptions { - host?: string; - port?: number; - path?: string; - protocol?: string; - pid?: number; - facility?: string; - localhost?: string; - type?: string; - app_name?: string; - eol?: string; - } +export interface SyslogTransportInstance extends Transport { + producer: any; + socket: dgram.Socket | net.Socket; - interface SyslogTransportInstance extends Transport { + connect(callback: (err: (true | null)) => any): void; - producer: any; - socket: dgram.Socket | net.Socket; - - connect(callback: (err: (true | null)) => any): void; - - new(options?: SyslogTransportOptions): SyslogTransportInstance; - } + new(options?: SyslogTransportOptions): SyslogTransportInstance; } export const Syslog: SyslogTransportInstance; From 94bf96d4288b20ee56b58b6045c5273f9b447c9c Mon Sep 17 00:00:00 2001 From: felix-hoc Date: Fri, 10 Aug 2018 11:50:28 +0200 Subject: [PATCH 045/289] Disable no-misused-new linting rule, so we can stay in line with winston's conventions. See https://github.com/winstonjs/winston-mongodb/blob/master/lib/winston-mongodb.d.ts and https://github.com/winstonjs/winston-daily-rotate-file/blob/master/index.d.ts --- types/winston-syslog/tslint.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/winston-syslog/tslint.json b/types/winston-syslog/tslint.json index f93cf8562a..bf5a9b916f 100644 --- a/types/winston-syslog/tslint.json +++ b/types/winston-syslog/tslint.json @@ -1,3 +1,8 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // This allows to be in line with winston transport types. + // See https://github.com/winstonjs/winston-mongodb/blob/master/lib/winston-mongodb.d.ts and https://github.com/winstonjs/winston-daily-rotate-file/blob/master/index.d.ts + "no-misused-new": false + } } From 2257e704c4f943ccc9a851a9a048c40ed40b9cb5 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 10 Aug 2018 16:42:36 +0200 Subject: [PATCH 046/289] Cleanup and improve chrome.notifications typings --- types/chrome-apps/index.d.ts | 546 +++++++++++++++++++++----------- types/chrome-apps/test/index.ts | 370 ++++++++++------------ 2 files changed, 530 insertions(+), 386 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index d6605bea48..052749758e 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -825,15 +825,6 @@ declare namespace chrome { * 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; } @@ -3863,8 +3854,6 @@ declare namespace chrome { '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) @@ -5466,6 +5455,25 @@ declare namespace chrome { * @see[Docs]{@link https://developer.chrome.com/extensions/notifications} */ namespace notifications { + /** @enum */ + const TemplateType: { + /** icon, title, message, expandedMessage, up to two buttons */ + BASIC: "basic", + /** icon, title, message, expandedMessage, image, up to two buttons */ + IMAGE: "image", + /** icon, title, message, items, up to two buttons. Users on Mac OS X only see the first item. */ + LIST: "list", + /** icon, title, message, progress, up to two buttons */ + PROGRESS: "progress" + } + /** @enum */ + const PermissionLevel: { + /** User has elected to show notifications from the app or extension. This is the default at install time. */ + GRANTED: "granted", + /** User has elected not to show notifications from the app or extension. */ + DENIED: "denied" + } + interface ButtonOptions { title: string; iconUrl?: string; @@ -5479,218 +5487,214 @@ declare namespace chrome { } interface NotificationOptions { - /** Which type of notification to display. Required for notifications.create method. */ - type?: string; + /** + * Which type of notification to display. Required for notifications.create method. + * @see enum TemplateType + */ + type: ToStringLiteral; /** * Optional. * A URL to the sender's avatar, app icon, or a thumbnail for image notifications. * 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; + iconUrl: string; + + /** + * @deprecated since Chrome 59. The app icon mask is not visible for Mac OS X users. + * A URL to the app icon mask. URLs have the same restrictions as iconUrl. + * The app icon mask should be in alpha channel, + * as only the alpha channel of the image will be considered. + */ + appIconMaskUrl?: string; + /** Title of the notification (e.g. sender name for email). Required for notifications.create method. */ - title?: string; + title: string; + /** Main notification content. Required for notifications.create method. */ - message?: string; + message: string; + /** - * Optional. * Alternate notification content with a lower-weight font. * @since Chrome 31. */ contextMessage?: string; - /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ - priority?: integer; + + /** + * Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. + * On platforms that don't support a notification center (Windows, Linux & Mac), + * -2 and -1 result in an error as notifications with those priorities will not be shown at all. + * @default 0 + */ + priority?: -2 | -1 | 0 | 1 | 2; + /** A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ - eventTime?: integer; + eventTime?: double; + /** Text and icons for up to two notification action buttons. */ buttons?: ButtonOptions[]; - /** Items for multi-item notifications. */ + + /** + * @deprecated Deprecated since Chrome 59. The image is not visible for Mac OS X users. + * A URL to the image thumbnail for image-type notifications. + * URLs have the same restrictions as iconUrl. + */ + imageUrl?: string; + + /** + * Items for multi-item notifications. + * Items for multi-item notifications. Users on Mac OS X only see the first item. + */ items?: ItemOptions[]; + /** - * Optional. * Current progress ranges from 0 to 100. * @since Chrome 30. */ progress?: integer; + /** - * Optional. * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. * @since Chrome 32. */ isClickable?: boolean; + /** - * Optional. - * A URL to the app icon mask. URLs have the same restrictions as iconUrl. The app icon mask should be in alpha channel, as only the alpha channel of the image will be considered. - * @since Chrome 38. - */ - appIconMaskUrl?: string; - /** 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. + * Indicates that the notification should remain visible + * on screen until the user activates or dismisses the notification. * This defaults to false. * @since Chrome 50 */ requireInteraction?: boolean; } - interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> { } - - interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> { } - - interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: integer) => void> { } - - interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> { } - - interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> { } - /** The notification closed, either by the system or by user action. */ - const onClosed: NotificationClosedEvent; + const onClosed: chrome.events.Event<(notificationId: string, byUser: boolean) => void>; /** The user clicked in a non-button area of the notification. */ - const onClicked: NotificationClickedEvent; + const onClicked: chrome.events.Event<(notificationId: string) => void>; /** The user pressed a button in the notification. */ - const onButtonClicked: NotificationButtonClickedEvent; + const onButtonClicked: chrome.events.Event<(notificationId: string, buttonIndex: integer) => void>; /** * The user changes the permission level. * @since Chrome 32. */ - const onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; + const onPermissionLevelChanged: chrome.events.Event<(level: string) => void>; /** * The user clicked on a link for the app's notification settings. * @since Chrome 32. */ - const onShowSettings: NotificationShowSettingsEvent; + const onShowSettings: chrome.events.Event<() => 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. + * @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. * The notificationId parameter is required before Chrome 42. * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string notificationId) {...}; + * @param [callback] Returns the notification id (either supplied or generated) that represents the created notification. */ 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. - * The notificationId parameter is required before Chrome 42. + * @param notificationId Identifier of the notification. * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string notificationId) {...}; + * @param [callback] Returns the notification id (either supplied or generated) that represents the created notification. */ 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. * @param options Contents of the notification to update to. - * @param callback Called to indicate whether a matching notification existed. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasUpdated) {...}; + * @param [callback] Called to indicate whether a matching notification existed. */ 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. * @param callback Called to indicate whether a matching notification existed. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; */ function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; + /** - * Retrieves all the notifications. + * Retrieves all the active notifications. * @since Chrome 29. * @param callback Returns the set of notification_ids currently in the system. - * The callback parameter should be a function that looks like this: - * function(object notifications) {...}; + * Get list of notifications ids using Object.keys(); + * @example + * getAll((result) => { + * console.log('Active notifications:', Object.keys(result)); + * }); */ - function getAll(callback: (notifications: Object) => void): void; + function getAll(callback: (notifications: { [notificationId: string]: true }) => void): void; + /** * Retrieves whether the user has enabled notifications from this app or extension. * @since Chrome 32. * @param callback Returns the current permission level. - * The callback parameter should be a function that looks like this: - * function( PermissionLevel level) {...}; + * @see enum PermissionLevel */ - function getPermissionLevel(callback: (level: string) => void): void; + function getPermissionLevel(callback: (level: ToStringLiteral) => void): void; } //////////////////// // Permissions //////////////////// /** - * Use the chrome.permissions API to request declared optional permissions at run time rather than install time, so users understand why the permissions are needed and grant only those that are necessary. + * Use the chrome.permissions API to request declared optional permissions at run time rather than install time, + * so users understand why the permissions are needed and grant only those that are necessary. * @since Chrome 16. */ namespace permissions { interface Permissions { /** * Optional. - * List of named permissions (does not include hosts or origins). Anything listed here must appear in the optional_permissions list in the manifest. + * List of named permissions (does not include hosts or origins). + * Anything listed here must appear in the optional_permissions list in the manifest. */ - origins?: string[]; + origins?: chrome.runtime.OptionalPermissions[]; /** * Optional. - * List of origin permissions. Anything listed here must be a subset of a host that appears in the optional_permissions list in the manifest. For example, if http://*.example.com/ or http://* appears in optional_permissions, you can request an origin of http://help.example.com/. Any path is ignored. + * List of origin permissions. + * Anything listed here must be a subset of a host that appears in the + * optional_permissions list in the manifest. For example, if + * http://*.example.com/ or http://* appears in optional_permissions, + * you can request an origin of http://help.example.com/. + * Any path is ignored. */ - permissions?: string[]; + permissions?: chrome.runtime.UrlMatches[] | string[]; } - interface PermissionsRemovedEvent { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Permissions permissions) {...}; - * Parameter permissions: The permissions that have been removed. - */ - addListener(callback: (permissions: Permissions) => void): void; - } - - interface PermissionsAddedEvent { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Permissions permissions) {...}; - * Parameter permissions: The newly acquired permissions. - */ - addListener(callback: (permissions: Permissions) => void): void; - } + interface PermissionEvent extends chrome.events.Event<(permissions: chrome.runtime.Permission[]) => void> { } /** - * Checks if the extension has the specified permissions. - * @param callback The callback parameter should be a function that looks like this: - * function(boolean result) {...}; - * Parameter result: True if the extension has the specified permissions. + * Checks if the app has the specified permissions. + * @param callback Parameter result: True if the app has the specified permissions. */ - function contains(permissions: Permissions, callback: (result: boolean) => void): void; + function contains(permissions: chrome.runtime.Permission[], 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. + * Gets the app's current set of permissions. + * @param callback Parameter permissions: The app's active permissions. */ - function getAll(callback: (permissions: Permissions) => void): void; + function getAll(callback: (permissions: chrome.runtime.Permission[]) => 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: - * function(boolean granted) {...}; - * Parameter granted: True if the user granted the specified permissions. + * 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] Parameter granted: True if the user granted the specified permissions. */ - function request(permissions: Permissions, callback?: (granted: boolean) => void): void; + function request(permissions: chrome.runtime.Permission[], 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: - * function(boolean removed) {...}; - * Parameter removed: True if the permissions were removed. + * @param [callback] Parameter removed: True if the permissions were removed. */ - function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; + function remove(permissions: chrome.runtime.Permission[], callback?: (removed: boolean) => void): void; - /** Fired when access to permissions has been removed from the extension. */ - const onRemoved: PermissionsRemovedEvent; - /** Fired when the extension acquires new permissions. */ - const onAdded: PermissionsAddedEvent; + /** Fired when access to permissions has been removed from the app. */ + const onRemoved: PermissionEvent; + /** Fired when the app acquires new permissions. */ + const onAdded: PermissionEvent; } /////////// @@ -5724,8 +5728,11 @@ declare namespace chrome { // Printer Provider // ////////////////////// /** - * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. - * Permissions: 'printerProvider' + * The chrome.printerProvider API exposes events used by print manager + * to query printers controlled by extensions, to query their + * capabilities and to submit print jobs to these printers. + * + * @requires Permissions: 'printerProvider' * @since Chrome 44. */ namespace printerProvider { @@ -5960,32 +5967,56 @@ declare namespace chrome { is_default?: boolean; } - type UrlPermission = + type UrlMatches = 'https://www.google-analytics.com/*' | 'https://www.googleapis.com/*' | '' | 'http://*/*' | 'https://*/*' - | 'file:///*/*'; + | 'file:///*/*' + /** + * Required if the extension uses the "chrome://favicon/**url**" mechanism to display the favicon of a page. + * For example, to display the favicon of http://www.google.com/, you declare the "chrome://favicon/" + * permission and use HTML code like this: + * @example + *
+             * 
+             * 
+ */ + | 'chrome://favicon/' + | 'chrome://extension-icon/'; type ChromeOSOnlyPermissions = + /** Gives your app access to the chrome.certificateProvider API. */ 'certificateProvider' | + /** Gives your app access to the chrome.clipboard API. */ 'clipboard' | + /** Gives your app access to the chrome.dns API. */ 'dns' | + /** Gives your app access to the chrome.documentScan API. */ 'documentScan' | - 'enterprise' | + /** Gives your app access to the chrome.enterprise.platformKeys API. */ 'enterprise.platformKeys' | + /** Gives your app access to the chrome.enterprise.deviceAttributes API. */ 'enterprise.deviceAttributes' | + /** Gives your app access to the chrome.fileBrowserHandler API. */ 'fileBrowserHandler' | + /** + * Gives your app access to the chrome.fileSystemProvider API. + * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. + */ 'fileSystemProvider' | + /** Gives your app access to the chrome.networking.config API. */ 'networking.config' | + /** Gives your app access to the chrome.platformKeys API. */ 'platformKeys' | + /** Gives your app access to the chrome.vpnProvider API. */ 'vpnProvider' | + /** Gives your app access to the chrome.wallpaper API. */ 'wallpaper'; type DevOnly = 'app.window.alpha' | - 'audio' | // Dev channel except for ChromeOS kiosk 'diagnostics' | 'displaySource'; @@ -6000,64 +6031,166 @@ declare namespace chrome { 'appview' | 'experimental' | 'app.window.shape' | // Works on stable - 'geolocation' | 'alwaysOnTopWindows' | 'overrideEscFullscreen' | - 'geolocation' | - 'experimental' | 'app.window.fullscreen' | 'app.window.fullscreen.overrideEsc'; - type Permission = - 'alarms' | - 'app.window.fullscreen' | - 'app.window.fullscreen.overrideEsc' | - 'audioCapture' | - 'background' | - 'browser' | - 'clipboardRead' | - 'clipboardWrite' | - 'contextMenus' | - 'desktopCapture' | - 'diagnostics' | + type NotAllowedAsOptionalPermissions = + 'debugger' | 'experimental' | - 'fileSystem' | - 'gcm' | 'geolocation' | - 'hid' | - 'identity' | - 'idle' | 'mdns' | + 'proxy' | + 'tts' | + 'wallpaper'; + + type OptionalPermission = Exclude; + /** + * Optional permissions + * @see NotAllowedAsOptionalPermissions for permissions that you're not allowed to set. + */ + type OptionalPermissions = Array | Array; + + type Permission = + /** Gives your app access to the chrome.alarms API. */ + 'alarms' | + /** Gives your app access to the chrome.audio API. */ + 'audio' | + /** + * In Chrome Apps, fullscreen is entered without prompting the user or providing exit instructions. + * HTML5 fullscreen requires the app.window.fullscreen permission in the manifest. + * In normal webpages, the browser intercepts the ESC key to exit pointer lock ensuring a consistent escape method for users. + * To block this, set the 'app.window.fullscreen.overrideEsc permission + */ + 'app.window.fullscreen' | + /** That is also the behavior in Chrome Apps unless the app.window.fullscreen.overrideEsc + * permission is used to enable the app to call preventDefault on keydown and keyup events. */ + 'app.window.fullscreen.overrideEsc' | + /** Requests that the app be granted permissions to capture audio directly from the user's Microphone via the getUserMedia API. */ + 'audioCapture' | + /** + * Makes Chrome start up early and and shut down late, so that apps and extensions can have a longer life. + * When any installed app has "background" permission, Chrome runs (invisibly) as soon as the user logs + * into their computer—before the user launches Chrome. The "background" permission also makes Chrome + * continue running (even after its last window is closed) until the user explicitly quits Chrome. + * Note: Disabled apps and extensions are treated as if they aren't installed. + */ + 'background' | + /** Gives your app access to the chrome.browser API. */ + 'browser' | + /** Required if the extension or app uses document.execCommand('paste'). */ + 'clipboardRead' | + /** + * Indicates the extension or app uses document.execCommand('copy') or document.execCommand('cut'). + * This permission is recommended for packaged apps. + */ + 'clipboardWrite' | + /** Gives your app access to the chrome.contextMenus API. */ + 'contextMenus' | + /** Gives your app access to the chrome.desktopCapture API. */ + 'desktopCapture' | + /** Gives your app access to the chrome.diagnostics API. */ + 'diagnostics' | + /** Required if the app uses any chrome.experimental.* APIs. */ + 'experimental' | + /** Gives your app access to the chrome.fileSystem API. */ + 'fileSystem' | + /** + * @deprecated + * Gives your app access to the chrome.gcm API. + */ + 'gcm' | + /** Allows the extension or app to use the proposed HTML5 geolocation API without prompting the user for permission. */ + 'geolocation' | + /** Gives your app access to the chrome.hid API. */ + 'hid' | + /** Gives your app access to the chrome.identity API. */ + 'identity' | + /** Gives your app access to the chrome.idle API. */ + 'idle' | + /** Gives your app access to the chrome.mdns API. */ + 'mdns' | + /** Gives your app access to the chrome.mediaGalleries API. */ 'mediaGalleries' | + /** Gives your app access to the native messaging API. */ 'nativeMessaging' | + /** + * Required if the app uses the chrome.notifications API. + * + * Also allows the app to use the proposed HTML5 notification API + * without calling permission methods (such as checkPermission()). + */ 'notifications' | + /** + * Required to use Pointer Lock via calls to **requestPointerLock** or Pepper's Mouse Lock API. + * In Chrome Apps, pointer lock is entered without requiring a user gesture, prompting the user, + * or providing exit instructions. Pointer lock requires the pointerlock permission in the manifest. + * Also, there is no default exit behavior. + * In normal webpages, the browser intercepts the ESC key to exit pointer lock. + * This behavior is not present in Chrome Apps. + * @see[Pointer Lock Docs]{@link http://www.w3.org/TR/pointerlock/} + * @see[Pepper's Mouse Lock API]{@link https://developers.google.com/native-client/peppercpp/classpp_1_1_mouse_lock} + */ 'pointerLock' | + /** Gives your app access to the chrome.power API. */ 'power' | + /** Gibes your app access to the chrome.printerProvider API. */ 'printerProvider' | /** Runtime is not actually a permisison, but some sysems check these values to verify restrictions. */ 'runtime' | /** @deprecated Serial is deprecated */ 'serial' | + /** Gives your app access to the chrome.signedInDevices API. */ 'signedInDevices' | + /** Gives your app access to the chrome.storage API. */ 'storage' | + /** Required if the app uses the chrome.syncFileSystem API to save and synchronize data on Google Drive. */ 'syncFileSystem' | + /** Gives your app access to the chrome.system.cpu API. */ 'system.cpu' | + /** Gives your app access to the chrome.system.display API. */ 'system.display' | + /** Gives your app access to the chrome.system.memory API. */ 'system.memory' | + /** Gives your app access to the chrome.system.network API. */ 'system.network' | + /** Gives your app access to the chrome.system.storage API. */ 'system.storage' | + /** Gives your app access to the chrome.tts API. */ 'tts' | + /** + * Provides an unlimited quota for storing HTML5 client-side data, such as databases and local storage files. + * Without this permission, the extension or app is limited to 5 MB of local storage. + * + * *Note* + * *This permission applies only to Web SQL Database and application cache* + * *Also, it doesn't currently work with wildcard subdomains such as* + * @example + * http://*.example.com + */ 'unlimitedStorage' | 'usb' | 'usbDevices' | + /** Requests that the app be granted permissions to capture video directly from the user's Web Cam via the getUserMedia API. */ 'videoCapture' | + /** Required if the app uses the Webview Tag to embed live content from the web in the packaged app. */ 'webview' | ChromeOSOnlyPermissions | FileSystemPermission | KioskOnlyPermissions | MediaGalleriesPermission | SocketPermission | - UrlPermission | + /** + * Specifies a **host permission**. + * Required if the app wants to interact with the code running on pages. + * Many capabilities, such as cross-origin XMLHttpRequests, + * programmatically injected content scripts require host permissions. + * For details on the syntax: + * @see[Match Patterns]{@link https://developer.chrome.com/apps/match_patterns} + * A path is allowed but treated as /* + */ + UrlMatches | USBDevicesPermission; interface MediaGalleriesPermission { @@ -6117,22 +6250,36 @@ declare namespace chrome { /// For chrome.sockets /// - type SocketPermissionOptions = '*:*' | '' | '*'; interface SocketTcpPermission { - /** The host:port pattern for connect operations. */ - connect?: SocketPermissionOptions | string; + /** + * The host:port pattern for connect operations. + * *:* are allowed + */ + connect?: string | string[]; } interface SocketTcpServerPermission { - /** The host:port pattern for listen operations. */ - listen?: SocketPermissionOptions | string; + /** + * The host:port pattern for listen operations. + * *:* are allowed + */ + listen?: string | string[]; } interface SocketUdpPermission { - /** The host:port pattern for bind operations. */ - bind?: SocketPermissionOptions | string; - /** The host:port pattern for joinGroup operations. */ - multicastMembership?: SocketPermissionOptions | string; - /** The host:port pattern for send operations. */ - send?: SocketPermissionOptions | string; + /** + * The host:port pattern for bind operations. + * *:* are allowed + */ + bind?: string | string[]; + /** + * The host:port pattern for joinGroup operations. + * *:* are allowed + */ + multicastMembership?: string | string[]; + /** + * The host:port pattern for send operations. + * *:* are allowed + */ + send?: string | string[]; } interface WebViewPartition { @@ -6173,8 +6320,8 @@ declare namespace chrome { interface AutomationNonInteractive { interact: false; desktop?: false; - /** Patterns for matching */ - matches?: string[]; + /** Patterns for matching, use chrome url pattern */ + matches?: UrlMatches[] | string[]; } type AutomationOptions = boolean | AutomationDesktop | AutomationNonInteractive; @@ -6191,7 +6338,7 @@ declare namespace chrome { app: { background: { scripts?: string[]; - }; + } }; /** * One integer specifying the version of the manifest file format your package requires. @@ -6293,7 +6440,10 @@ declare namespace chrome { email: string, } | any; - /** @todo TODO */ + /** + * Allows inspection of page contents, not enabled on stable anyways except for whitelist. + * @see[Docs]{@link https://github.com/chromium/chromium/blob/master/extensions/common/manifest_handlers/automation.cc} + */ automation?: AutomationOptions | boolean; /** @@ -6340,10 +6490,13 @@ declare namespace chrome { * An implementation detail (actually written by Chrome, not the app author). */ readonly current_locale?: string; + /** Restricted to whitelist */ display_in_launcher?: boolean; + /** Restricted to whitelist */ display_in_new_tab_page?: boolean; + /** * The *event_rules* manifest property provides a mechanism to add rules that * intercept, block, or modify web requests in-flight using **declarativeWebRequest** @@ -6387,26 +6540,47 @@ declare namespace chrome { * Determines if messages sent via `runtime.connect` or `runtime.sendMessage` * are allowed to set `runtime.MessageSender.tlsChannelId`. */ - accept_tls_channel_id: boolean, + accept_tls_channel_id?: boolean, } - /** @todo TODO */ + /** + * Triggers a launch of the app when one of these files are handled. + */ file_handlers?: { [key: string]: { extensions?: Array<'*' | string | { include_directories: boolean }>, + /** File types to handle */ types?: Array<'*' | string | { include_directories: boolean }>, }, }; - /** @todo TODO */ + /** + * Files app uses above information in order to render related UI elements approprietly. + */ file_system_provider_capabilities?: { + /** + * For example, if *configurable* is set to **true**, + * then a menu item for configuring volumes will be rendered. + */ configurable?: boolean, + /** + * If *multiple_mounts* is set to **true**, then *Files app* + * will allow to add more than one mount points from the UI. + */ multiple_mounts?: boolean, + /** + * 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. + */ watchable?: boolean, - source?: 'network' | string, + source?: 'network', }; - /** @todo TODO */ + /** + * Import resources from another extension / app. + * @see[Shared modules]{@link https://developer.chrome.com/apps/shared_modules} + */ import?: { id: string; }[]; @@ -6452,7 +6626,7 @@ declare namespace chrome { * at run time rather than install time, so users understand why the * permissions are needed and grant only those that are necessary. */ - optional_permissions?: Permission[] | Array; + optional_permissions?: OptionalPermissions; /** * Permissions help to limit damage if your app is compromised by malware. @@ -6549,7 +6723,7 @@ declare namespace chrome { */ short_name?: string; - /** @todo TODO What is this? */ + /** Doc missing. Declared as a feature, but unused. */ signature?: any; /** @@ -6726,7 +6900,7 @@ declare namespace chrome { chrome_url_overrides?: never; } - type Manifest = ValidKioskManifest | C | ValidNonKioskManifest | InvalidManifest; + type Manifest = ValidKioskManifest | ValidNonKioskManifest | InvalidManifest; /** * 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. @@ -7822,9 +7996,9 @@ declare namespace chrome { } - //////////////////// - // System CPU - //////////////////// + //////////////// + // System CPU // + //////////////// /** * Use the system.cpu API to query CPU metadata. * Permissions: 'system.cpu' @@ -7868,7 +8042,7 @@ declare namespace chrome { } //////////////////// - // System Display + // System Display // //////////////////// /** * Use the system.display API to query display metadata. @@ -8205,9 +8379,9 @@ declare namespace chrome { const onDisplayChanged: DisplayChangedEvent; } - //////////////////// - // System Memory - //////////////////// + /////////////////// + // System Memory // + /////////////////// /** * The chrome.system.memory API. * Permissions: 'system.memory' @@ -8225,9 +8399,9 @@ declare namespace chrome { function getInfo(callback: (info: MemoryInfo) => void): void; } - //////////////////// - // System - Network - //////////////////// + ////////////////////// + // System - Network // + ////////////////////// namespace system.network { interface NetworkInterface { name: string; @@ -8238,8 +8412,22 @@ declare namespace chrome { function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } + ///////////////////////// + // System Power Source // + ///////////////////////// + /** + * The chrome.system.powerSource API. + * @requires Permissions: 'system.powerSource' + * @since Latest + */ + namespace system.powerSource { + /** @todo TODO Document this */ + function getPowerSourceInfo(arg?: any | any[]): any; + function requestStatusUpdate(arg?: any | any[]): any; + } + //////////////////// - // System Storage + // System Storage // //////////////////// /** * Use the chrome.system.storage API to query storage device information and be notified when a removable storage device is attached and detached. @@ -8295,7 +8483,7 @@ declare namespace chrome { } //////////////////// - // Text to Speech + // Text to Speech // //////////////////// /** * Use the chrome.tts API to play synthesized text-to-speech (TTS). See also the related ttsEngine API, which allows an extension to implement a speech engine. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 1e6d54b4f1..87e091dbef 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -192,36 +192,28 @@ window.addEventListener('beforeunload', () => { }); // MANIFEST const ManifestJSONTest1: chrome.runtime.Manifest = { - "container": "GOOGLE_DRIVE", - "api_console_project_id": "619683526622", - "manifest_version": 2, - "name": "Sample Appview Embedded - modified for manifest test", - "description": "__MSG_appDescription__", - "version": "2.1", - "minimum_chrome_version": "33.0.1715.0", - "default_locale": "en", - "chrome_url_overrides": { - "newtab": "app.html" + manifest_version: 2, + name: "Sample Appview Embedded - modified for manifest test", + description: "__MSG_appDescription__", + version: "2.1", + minimum_chrome_version: "33.0.1715.0", + default_locale: "en", + file_system_provider_capabilities: { + configurable: false, + multiple_mounts: true, + source: "network" }, - "launch": { - "web_url": "https://developer.mbed.org/compiler/#nav:/;" - }, - "file_system_provider_capabilities": { - "configurable": false, - "multiple_mounts": true, - "source": "network" - }, - "platforms": [{ - "nacl_arch": "x86-64", - "sub_package_path": "_platform_specific/x86-64/" + platforms: [{ + nacl_arch: "x86-64", + sub_package_path: "_platform_specific/x86-64/" }, { - "nacl_arch": "x86-32", - "sub_package_path": "_platform_specific/x86-32/" + nacl_arch: "x86-32", + sub_package_path: "_platform_specific/x86-32/" }, { - "nacl_arch": "arm", - "sub_package_path": "_platform_specific/arm/" + nacl_arch: "arm", + sub_package_path: "_platform_specific/arm/" }], - "permissions": [ + permissions: [ "https://www.google-analytics.com/*", "http://localhost:8080/*", "https://www.googleapis.com/*", @@ -269,69 +261,82 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "metricsPrivate", "nativeMessaging", "management", "developerPrivate", "activityLogPrivate", { - "mediaGalleries": ["read", "allAutoDetected"] + mediaGalleries: ["read", "allAutoDetected"] + }, + { + socket: [ + "udp-send-to::*", + "tcp-connect", + "udp-send-to", + "udp-bind", + "udp-multicast-membership", + "resolve-host", + "network-state", + "tcp-connect", + "resolve-host", + "network-state" + ] }, - { "socket": ["udp-send-to::*", "tcp-connect", "udp-send-to", "udp-bind", "udp-multicast-membership", "resolve-host", "network-state", "tcp-connect", "resolve-host", "network-state"] }, "tts", "syncFileSystem", { - "usbDevices": [ - { "vendorId": 10168, "productId": 493 } - ] + usbDevices: [{ + vendorId: 10168, + productId: 493 + }] } ], - "storage": { - "managed_schema": "schema.json" + storage: { + managed_schema: "schema.json" }, - "browser_action": { - "default_icon": { - "128": "img/icon.png" - }, - "default_title": "AnimAlerts", - "default_popup": "html/popup.html" + author: { + name: "Your name here", + email: "Email@yourmail.com" }, - "author": { - "name": "Your name here", - "email": "Email@yourmail.com" + automation: { + desktop: true }, - "update_url": "https://clients2.google.com/service/update2/crx", - "version_name": "10.0.12-stable", - "kiosk_enabled": true, - "offline_enabled": true, - "bluetooth": { - "low_energy": true, - "uuids": ["180f"] + update_url: "https://clients2.google.com/service/update2/crx", + version_name: "10.0.12-stable", + kiosk_enabled: true, + offline_enabled: true, + bluetooth: { + low_energy: true, + uuids: ["180f"] }, - "url_handlers": { - "wiki_article": { - "title": "View Wikipedia article", - "matches": [ + url_handlers: { + wiki_article: { + title: "View Wikipedia article", + matches: [ "*://en.wikipedia.org/wiki/*" ] }, - "mobile_wiki_article": { - "title": "View Wikipedia article", - "matches": [ + mobile_wiki_article: { + title: "View Wikipedia article", + matches: [ "*://en.m.wikipedia.org/wiki/*" ] }, - "google_drive_open": { - "matches": ["https://api.chromerestclient.com/GDrive.html*"], - "title": "Open from Google Drive" + google_drive_open: { + matches: ["https://api.chromerestclient.com/GDrive.html*"], + title: "Open from Google Drive" } }, - "sockets": { - "tcpServer": { "listen": "" }, - "tcp": { "connect": ["*:5555", "*:5559"] }, - "udp": { "bind": ["*:5554", "*:5556"], "multicastMembership": "", "send": ["*:5554", "*:5556"] } + sockets: { + tcpServer: { listen: "" }, + tcp: { connect: ["*:5555", "*:5559"] }, + udp: { bind: ["*:5554", "*:5556"], multicastMembership: "", send: ["*:5554", "*:5556"] } }, - "optional_permissions": [ - "audioCapture", - "serial", - { "usbDevices": [{ "vendorId": 2338, "productId": 32 }] } + optional_permissions: [ + "debugger", + "htt", + "mdns", + "app.window.fullscreen", + "mdns", + "debugger" ], - "webview": { - "partitions": [ + webview: { + partitions: [ { "name": "blockable", "accessible_resources": ["browser.css", "blocked.css", "blocked.html"] @@ -342,187 +347,138 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { } ] }, - "externally_connectable": { - "matches": ["https://gauth.fusionlabs.net/*"] + externally_connectable: { + id: ["*"], + matches: ["https://gauth.fusionlabs.net/*"] }, - "commands": { - "cmdNew": { - "suggested_key": { - "default": "Ctrl+Shift+1" + commands: { + cmdNew: { + suggested_key: { + default: "Ctrl+Shift+1" }, - "global": true, - "description": "Create new window" + global: true, + description: "Create new window" }, - "new-team-login": { - "suggested_key": { - "default": "Ctrl+Shift+Y", - "mac": "Command+Shift+Y" + 'new-team-login': { + suggested_key: { + default: "Ctrl+Shift+Y", + mac: "Command+Shift+Y" }, - "description": "New team login" + description: "New team login" }, - "reload": { - "suggested_key": { - "default": "Ctrl+R" + reload: { + suggested_key: { + default: "Ctrl+R" }, - "description": "Reload webview" + description: "Reload webview" } }, - "automation": { - "desktop": true + sandbox: { + content_security_policy: "sandbox allow-scripts allow-popups; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com/ga.js;", + pages: ["sandbox.html"] }, - "sandbox": { - "content_security_policy": "sandbox allow-scripts allow-popups; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com/ga.js;", - "pages": ["sandbox.html"] - }, - "content_security_policy": "script-src 'self' https://www.gstatic.com/; object-src 'self'", - "file_handlers": { - "image": { - "types": [ + file_handlers: { + image: { + types: [ "image/png", "image/jpeg" ] }, - "text": { - "types": [ + text: { + types: [ "text/*" ], - "extensions": ["abap", "as", "ada", "adb", "ads", "cfm", "cfc", "cfml", "cs", "css", "dt", "d", "dot", "ejs", "erl", "frt", "ftl", "html", "erb", "ini", "jk", "java", "class", "js", "gs", "javascript", "jsoniq", "json", "jsp", "jsx", "lisp", "ls", "logic", "make", "makefile", "mak", "md", "mysql", "nix", "m", "php", "inc", "text", "txt", "log", "ps1", "rd", "sass", "scad", "scala", "scm", "ss", "scss", "sh", "sjs", "sql", "svg", "tcl", "tex", "ts", "vbs", "vbe", "vm", "v", "vhd", "vhdl", "xml", "rss", "atom", "xhtml", "yaml", "yml", "mcc"] + extensions: ["abap", "as", "ada", "adb", "ads", "cfm", "cfc", "cfml", "cs", "css", "dt", "d", "dot", "ejs", "erl", "frt", "ftl", "html", "erb", "ini", "jk", "java", "class", "js", "gs", "javascript", "jsoniq", "json", "jsp", "jsx", "lisp", "ls", "logic", "make", "makefile", "mak", "md", "mysql", "nix", "m", "php", "inc", "text", "txt", "log", "ps1", "rd", "sass", "scad", "scala", "scm", "ss", "scss", "sh", "sjs", "sql", "svg", "tcl", "tex", "ts", "vbs", "vbe", "vm", "v", "vhd", "vhdl", "xml", "rss", "atom", "xhtml", "yaml", "yml", "mcc"] }, - "any": { - "extensions": [ + any: { + extensions: [ "skrifa", "skrup" ] }, - "cab": { - "extensions": ["cab"], - "types": ["application/x-cab"] + cab: { + extensions: ["cab"], + types: ["application/x-cab"] }, - "cpio": { - "extensions": ["cpio", "cpio.gz", "cpio.bz2", "cpio.xz"], - "types": ["application/x-cpio"] + cpio: { + extensions: ["cpio", "cpio.gz", "cpio.bz2", "cpio.xz"], + types: ["application/x-cpio"] }, - "deb": { - "extensions": ["deb"], - "types": ["application/vnd.debian.binary-package"] + deb: { + extensions: ["deb"], + types: ["application/vnd.debian.binary-package"] }, - "gzip": { - "extensions": ["gz"], - "types": ["application/x-gzip"] + gzip: { + extensions: ["gz"], + types: ["application/x-gzip"] }, - "iso": { - "extensions": ["iso"], - "types": ["application/x-iso9660-image"] + iso: { + extensions: ["iso"], + types: ["application/x-iso9660-image"] }, - "lha": { - "extensions": ["lha", "lzh"], - "types": ["application/x-lha", "application/x-lzh", "application/x-lzh-compressed"] + lha: { + extensions: ["lha", "lzh"], + types: ["application/x-lha", "application/x-lzh", "application/x-lzh-compressed"] }, - "lz4": { - "extensions": ["lz4"], - "types": ["application/x-lz4"] + lz4: { + extensions: ["lz4"], + types: ["application/x-lz4"] }, - "lzip": { - "extensions": ["lzip"], - "types": ["application/x-lzip"] + lzip: { + extensions: ["lzip"], + types: ["application/x-lzip"] }, - "lzop": { - "extensions": ["lzop"], - "types": ["application/x-lzop"] + lzop: { + extensions: ["lzop"], + types: ["application/x-lzop"] }, - "pax": { - "extensions": ["pax", "pax.gz", "pax.bz2", "pax.xz"], - "types": ["application/x-pax"] + pax: { + extensions: ["pax", "pax.gz", "pax.bz2", "pax.xz"], + types: ["application/x-pax"] }, - "rpm": { - "extensions": ["rpm"], - "types": ["application/x-rpm", "application/x-redhat-package-manager"] + rpm: { + extensions: ["rpm"], + types: ["application/x-rpm", "application/x-redhat-package-manager"] }, - "tar": { - "extensions": ["gtar", "tar", "tgz", "tbz2", "txz", "tz"], - "types": ["application/x-tar", "application/x-gtar", "application/x-gtar-compressed"] + tar: { + extensions: ["gtar", "tar", "tgz", "tbz2", "txz", "tz"], + types: ["application/x-tar", "application/x-gtar", "application/x-gtar-compressed"] }, - "xz": { - "extensions": ["lzma", "xz"], - "types": ["application/x-lzma", "application/x-xz"] + xz: { + extensions: ["lzma", "xz"], + types: ["application/x-lzma", "application/x-xz"] }, - "zip": { - "extensions": ["apk", "crx", "jar"], - "types": ["application/java-archive", "application/x-chrome-extension"] + zip: { + extensions: ["apk", "crx", "jar"], + types: ["application/java-archive", "application/x-chrome-extension"] } }, - "requirements": { - "3D": { - "features": ["webgl"] + requirements: { + '3D': { + features: ["webgl"] } }, - "display_in_launcher": false, - "display_in_new_tab_page": false, - "key": "FIMaMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDJB6ZGcGxtlr/34s+TKgi84QiP7DMekqOjSUS2ubmbhchlM6CN9gYdGQ1aBI3TBXG3YaAu+XyutFA8M8NLLWc4OOGByW123aaa1DP6p67g8a+Ids/gX6cNSRnRHiDZXAd44ATxoN4OZjZJk9iQ26RIUjwX07bzntlI+frwwKCk4WQIDAQAB", - "oauth2": { + display_in_launcher: false, + display_in_new_tab_page: false, + key: "FIMaMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDJB6ZGcGxtlr/34s+TKgi84QiP7DMekqOjSUS2ubmbhchlM6CN9gYdGQ1aBI3TBXG3YaAu+XyutFA8M8NLLWc4OOGByW123aaa1DP6p67g8a+Ids/gX6cNSRnRHiDZXAd44ATxoN4OZjZJk9iQ26RIUjwX07bzntlI+frwwKCk4WQIDAQAB", + oauth2: { // client_id below is specifc to the application key. Follow the // documentation to obtain one for your app. - "client_id": "1111111222333.apps.googleusercontent.com", - "scopes": ["https://www.googleapis.com/auth/plus.login"] + client_id: "1111111222333.apps.googleusercontent.com", + scopes: ["https://www.googleapis.com/auth/plus.login"] }, - "app": { - "icon_color": "#00FDFD", - "urls": ["http://walkerrandolphsmith.com/"], - "background": { - "scripts": ["angular.js", "lodash.js", "background.js"], - "persistent": false, - "transient": true - }, - "linked_icons": [{ - "size": 16, - "url": "https://test.bi:8080/assets/icon_16.png" - }, { - "size": 32, - "url": "https://test.bi:8080/favicon.ico" - }, { - "size": 48, - "url": "https://test.bi:8080/favicon.ico" - }, { - "size": 64, - "url": "https://test.bi:8080/favicon.ico" - }, { - "size": 72, - "url": "https://test.bi:8080/assets/icon_72.png" - }, { - "size": 96, - "url": "https://test.bi:8080/assets/icon_96.webp" - }, { - "size": 128, - "url": "https://test.bi:8080/assets/icon_128.webp" - }, { - "size": 144, - "url": "https://test.bi:8080/assets/icon_144.png" - }, { - "size": 168, - "url": "https://test.bi:8080/assets/icon_168.png" - }, { - "size": 192, - "url": "https://test.bi:8080/assets/icon_192.png" - }, { - "size": 256, - "url": "https://test.bi:8080/assets/exposer_splash_512.webp" - }, { - "size": 512, - "url": "https://test.bi:8080/assets/exposer_splash_512.png" - }], - "theme_color": "rgba(77,208,192,1)", - "launch": { - "web_url": "https://hyjk2000.github.io/party-lottery/?source=chrome-app", - "container": "panel" + app: { + background: { + scripts: ["angular.js", "lodash.js", "background.js"] } }, - "icons": { - "16": "icon16.png", - "48": "icon48.png", - "64": "assets/icon-64x64.png", - "128": "icon128.png" + icons: { + 16: "icon16.png", + 48: "icon48.png", + 64: "assets/icon-64x64.png", + 128: "icon128.png" }, - "action_handlers": ["new_note"] + action_handlers: ["new_note"] } // ALARMS From 6c13ff99e9edcc793f62292ae8ed74b1ddda3efd Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Fri, 10 Aug 2018 17:05:54 +0200 Subject: [PATCH 047/289] Cleanup + placeholder for experimental apis --- types/chrome-apps/index.d.ts | 82 +++++++++++++++++++++++++-------- types/chrome-apps/test/index.ts | 4 +- 2 files changed, 65 insertions(+), 21 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 052749758e..9a5120e8d7 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -829,9 +829,9 @@ declare namespace chrome { const window: ChromeAppWindow; } - //////////////////// - // Audio - //////////////////// + /////////// + // Audio // + /////////// /** * @since Since Chrome 59. * @requires Permissions: 'audio' @@ -2758,9 +2758,9 @@ declare namespace chrome { } - //////////////////// - // File System Provider - //////////////////// + ////////////////////////// + // File System Provider // + ////////////////////////// /** * Use the chrome.fileSystemProvider API to create file systems, * that can be accessible from the file manager on Chrome OS. @@ -5987,49 +5987,79 @@ declare namespace chrome { | 'chrome://extension-icon/'; type ChromeOSOnlyPermissions = - /** Gives your app access to the chrome.certificateProvider API. */ + /** + * Gives your app access to the chrome.certificateProvider API. + * @todo TODO Implement API. + */ 'certificateProvider' | /** Gives your app access to the chrome.clipboard API. */ 'clipboard' | - /** Gives your app access to the chrome.dns API. */ + /** + * Gives your app access to the chrome.dns API. + * @todo TODO Implement API. + */ 'dns' | /** Gives your app access to the chrome.documentScan API. */ 'documentScan' | - /** Gives your app access to the chrome.enterprise.platformKeys API. */ + /** + * Gives your app access to the chrome.enterprise.platformKeys API. + * @todo TODO Implement API. + */ 'enterprise.platformKeys' | - /** Gives your app access to the chrome.enterprise.deviceAttributes API. */ + /** + * Gives your app access to the chrome.enterprise.deviceAttributes API. + * @todo TODO Implement API. + */ 'enterprise.deviceAttributes' | - /** Gives your app access to the chrome.fileBrowserHandler API. */ + /** + * Gives your app access to the chrome.fileBrowserHandler API. + * @todo TODO Implement API. + */ 'fileBrowserHandler' | /** * Gives your app access to the chrome.fileSystemProvider API. * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. */ 'fileSystemProvider' | - /** Gives your app access to the chrome.networking.config API. */ + /** + * Gives your app access to the chrome.networking.config API. + * @todo TODO Implement API. + */ 'networking.config' | - /** Gives your app access to the chrome.platformKeys API. */ + /** + * Gives your app access to the chrome.platformKeys API. + * @todo TODO Implement API. + */ 'platformKeys' | /** Gives your app access to the chrome.vpnProvider API. */ 'vpnProvider' | /** Gives your app access to the chrome.wallpaper API. */ - 'wallpaper'; + 'wallpaper' | + FileSystemPermission; type DevOnly = + /** @todo TODO Implement API. */ 'app.window.alpha' | + /** + * Gives your app access to the chrome.diagnostics API. + * @todo TODO Implement API. + */ 'diagnostics' | + /** @todo TODO Implement API. */ 'displaySource'; type KioskOnlyPermissions = 'audio' | 'networking.onc' | + /** @todo TODO Implement API. */ 'system.powerSource' | + /** @todo TODO Document? */ 'virtualKeyboard'; /** Undocumented but used permissions */ type UndocumentedPermissions = + /** @todo TODO Document these */ 'appview' | - 'experimental' | 'app.window.shape' | // Works on stable 'alwaysOnTopWindows' | 'overrideEscFullscreen' | @@ -6067,7 +6097,10 @@ declare namespace chrome { /** That is also the behavior in Chrome Apps unless the app.window.fullscreen.overrideEsc * permission is used to enable the app to call preventDefault on keydown and keyup events. */ 'app.window.fullscreen.overrideEsc' | - /** Requests that the app be granted permissions to capture audio directly from the user's Microphone via the getUserMedia API. */ + /** + * Requests that the app be granted permissions to capture audio + * directly from the user's Microphone via the getUserMedia API. + */ 'audioCapture' | /** * Makes Chrome start up early and and shut down late, so that apps and extensions can have a longer life. @@ -6090,8 +6123,6 @@ declare namespace chrome { 'contextMenus' | /** Gives your app access to the chrome.desktopCapture API. */ 'desktopCapture' | - /** Gives your app access to the chrome.diagnostics API. */ - 'diagnostics' | /** Required if the app uses any chrome.experimental.* APIs. */ 'experimental' | /** Gives your app access to the chrome.fileSystem API. */ @@ -6177,7 +6208,6 @@ declare namespace chrome { /** Required if the app uses the Webview Tag to embed live content from the web in the packaged app. */ 'webview' | ChromeOSOnlyPermissions | - FileSystemPermission | KioskOnlyPermissions | MediaGalleriesPermission | SocketPermission | @@ -6201,7 +6231,8 @@ declare namespace chrome { } interface FileSystemPermission { /** - * 'requestFileSystem' is only for ChromeOS + * @enum {string} + * @requires(CrOS) 'requestFileSystem' is only for ChromeOS */ fileSystem: Array<'write' | 'retainEntries' | 'directory' | 'requestFileSystem'>; } @@ -9827,6 +9858,17 @@ declare namespace chrome { interface OnMessageEvent extends chrome.events.Event<(details: OnMessageEventDetails) => void> { } } + ////////////////// + // PLACEHOLDERS // + ////////////////// + + /** + * Chrome experimental apis may be using this namespace. + * Please consult the official documentation. + * @see[Documentation]{@link https://developer.chrome.com/apps/experimental} + */ + const experimental: any; + ///////////// // CLASSES // ///////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 87e091dbef..5575406c84 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -231,7 +231,9 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { "metricsPrivate", "networkingPrivate", "bluetooth", "unlimitedStorage", - { "fileSystem": ["write", "retainEntries", "directory"] }, + { + fileSystem: ["write", "retainEntries", "directory"] + }, "clipboardRead", "desktopCapture", "clipboardWrite", From 9d2629fe0830ac2b9dcc32a7c59efd17411b224f Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 14 Aug 2018 14:52:28 +0200 Subject: [PATCH 048/289] Docs based on json dump of chrome object on chrome os --- types/chrome-apps/index.d.ts | 720 ++++++++++++++++++++++++----------- 1 file changed, 500 insertions(+), 220 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 9a5120e8d7..8efa543cf4 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1877,6 +1877,38 @@ declare namespace chrome { function openTab(options: Options): void; } + ////////////////////////// + // Certificate Provider // + ////////////////////////// + /** + * @requires(CrOS) Chrome OS only. + * @requires Permissions: 'certificateProvider' + * @todo TODO Finish documentation + */ + namespace certificateProvider { + const Hash: { + "MD5_SHA1": "MD5_SHA1", + "SHA1": "SHA1", + "SHA256": "SHA256", + "SHA384": "SHA384", + "SHA512": "SHA512" + }; + const PinRequestType: { + "PIN": "PIN", + "PUK": "PUK" + }; + const PinRequestErrorType: { + "INVALID_PIN": "INVALID_PIN", + "INVALID_PUK": "INVALID_PUK", + "MAX_ATTEMPTS_EXCEEDED": "MAX_ATTEMPTS_EXCEEDED", + "UNKNOWN_ERROR": "UNKNOWN_ERROR" + }; + const requestPin: Function; + const stopPinRequest: Function; + const onCertificatesRequested: chrome.events.Event<(...args: any[]) => any>; + const onSignDigestRequested: chrome.events.Event<(...args: any[]) => any>; + } + /////////////// // Clipboard // /////////////// @@ -1991,29 +2023,34 @@ declare namespace chrome { */ const ACTION_MENU_TOP_LEVEL_LIMIT: integer; /** - * 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. + * 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. **/ - type ContextType = - 'all' | - 'page' | - 'frame' | - 'selection' | - 'link' | - 'editable' | - 'image' | - 'video' | - 'audio' | - 'launcher' | - 'browser_action' | - 'page_action'; + const ContextType: { + "ALL": "all", + "PAGE": "page", + "FRAME": "frame", + "SELECTION": "selection", + "LINK": "link", + "EDITABLE": "editable", + "IMAGE": "image", + "VIDEO": "video", + "AUDIO": "audio", + "LAUNCHER": "launcher", + "BROWSER_ACTION": "browser_action", + "PAGE_ACTION": "page_action" + }; /** * The type of menu item. **/ - type ItemType = - 'normal' | - 'checkbox' | - 'radio' | - 'separator'; + const ItemType: { + "NORMAL": "normal", + "CHECKBOX": "checkbox", + "RADIO": "radio", + "SEPARATOR": "separator" + }; type MediaType = 'image' | @@ -2100,8 +2137,12 @@ declare namespace chrome { } interface CreateProperties { - /** The type of menu item. Defaults to 'normal' if not specified. */ - type?: ItemType; + /** + * The type of menu item. + * @default 'normal' - Defaults to 'normal' if not specified. + * @see ItemType + */ + type?: ToStringLiteral; /** * The unique ID to assign to this item. @@ -2133,9 +2174,10 @@ declare namespace chrome { /** * List of contexts this menu item will appear in. - * Defaults to ['page'] if not specified. + * @default ['page'] - Defaults to ['page'] if not specified. + * @see ContextType **/ - contexts?: ContextType[]; + contexts?: ToStringLiteral[]; /** * Whether the item is visible in the menu. @@ -2174,10 +2216,12 @@ declare namespace chrome { } interface UpdateProperties { - type?: ItemType; + /** @see ItemType */ + type?: ToStringLiteral; title?: string; checked?: boolean; - contexts?: ContextType[]; + /** @see ContextType */ + contexts?: ToStringLiteral[]; /** * Whether the item is visible in the menu. * @since Chrome 62. @@ -2229,9 +2273,21 @@ declare namespace chrome { } - //////////////////// - // DesktopCapture // - //////////////////// + ///////////////// + // Diagnostics // + ///////////////// + /** + * @requires(CrOS) Only Chrome OS. Crashes app on Windows. + * @requires Permissions: 'diagnostics' + */ + namespace diagnostics { + /** @todo TODO PROPER DOCS */ + function sendPacket(options: Object, callback: () => void): void; + } + + ///////////////////// + // Desktop Capture // + ///////////////////// /** * Desktop Capture API that can be used to capture content of screen, * individual windows or tabs. @@ -2263,6 +2319,41 @@ declare namespace chrome { function cancelChooseDesktopMedia(desktopMediaRequestId: integer): void; } + //////////////////// + // Display Source // + //////////////////// + /** + * @requires(dev) Development versions only + * @requires Permissions: 'displaySource' + * Display Source API + * @todo TODO Documentation + */ + namespace displaySource { + const ErrorType: { + "CONNECTION_ERROR": "connection_error", + "CAPABILITIES_NEGOTIATION_ERROR": "capabilities_negotiation_error", + "MEDIA_PIPELINE_ERROR": "media_pipeline_error", + "TIMEOUT_ERROR": "timeout_error", + "UNKNOWN_ERROR": "unknown_error" + }; + const SinkState: { + "CONNECTED": "Connected", + "CONNECTING": "Connecting", + "DISCONNECTED": "Disconnected" + }; + const AuthenticationMethod: { + "PBC": "PBC", + "PIN": "PIN" + }; + const getAvailableSinks: Function; + const requestAuthentication: Function; + const startSession: Function; + const terminateSession: Function; + const onSinksUpdated: chrome.events.Event; + const onSessionTerminated: chrome.events.Event; + const onSessionErrorOccured: chrome.events.Event; + } + /////////////////// // Document Scan // /////////////////// @@ -2600,6 +2691,19 @@ declare namespace chrome { } } + ///////////////////////// + // File Browser Handle // + ///////////////////////// + /** + * @requires(CrOS) Chrome OS Only + * @requires Permissions: 'fileBrowserHandle' + * @todo TODO Documentation + */ + namespace fileBrowserHandler { + const selectFile: Function; + const onExecute: chrome.events.Event; + } + //////////////// // FileSystem // //////////////// @@ -2615,15 +2719,39 @@ declare namespace chrome { * {'fileSystem': ['write', 'retainEntries', 'directory']} */ namespace fileSystem { - type ChildChangeType = - 'created' | - 'removed' | - 'changed'; - type ChooseEntryOptionsTypes = - 'openFile' | - 'openWritableFile' | - 'saveFile' | - 'openDirectory'; + /** @enum */ + const ChildChangeType: { + CREATED: "created", + REMOVED: "removed", + CHANGED: "changed" + }; + /** + * **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. + * **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'. + * **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'. + * **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. + * @enum + */ + const ChooseEntryType: { + OPEN_FILE: "openFile", + OPEN_WRITABLE_FILE: "openWritableFile", + SAVE_FILE: "saveFile", + OPEN_DIRECTORY: "openDirectory" + }; interface AcceptOptions { /** * This is the optional text description for this option. @@ -2643,34 +2771,24 @@ declare namespace chrome { interface ChooseEntryOptions { /** - * 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. - * 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'. - * 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'. - * 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. + * Type of the prompt to show. + * @default 'openFile' + * @see ChooseEntryType + */ + type?: ToStringLiteral; + /** + * The suggested file name that will be presented to the user as the default name to read or write. */ - 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. */ + /** + * 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[]; /** * Whether to accept all file types, in addition to the options specified in the accepts argument. - * The default is true. If the accepts field is unset or contains no valid entries, this will always be reset to true. + * If the accepts field is unset or contains no valid entries, this will always be reset to true. + * @default true */ acceptsAllTypes?: boolean; /** @@ -2755,6 +2873,12 @@ declare namespace chrome { * @since Chrome 44. */ const onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; + /** @todo TODO Document these: */ + const observeDirectory: Function; + const unobserveEntry: Function; + const getObservedEntries: Function; + const onEntrychanged: chrome.events.Event; + const onEntryRemoved: chrome.events.Event; } @@ -2793,32 +2917,35 @@ declare namespace chrome { * 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'; + const ProviderError: { + "OK": "OK", + "FAILED": "FAILED", + "IN_USE": "IN_USE", + "EXISTS": "EXISTS", + "NOT_FOUND": "NOT_FOUND", + "ACCESS_DENIED": "ACCESS_DENIED", + "TOO_MANY_OPENED": "TOO_MANY_OPENED", + "NO_MEMORY": "NO_MEMORY", + "NO_SPACE": "NO_SPACE", + "NOT_A_DIRECTORY": "NOT_A_DIRECTORY", + "INVALID_OPERATION": "INVALID_OPERATION", + "SECURITY": "SECURITY", + "ABORT": "ABORT", + "NOT_A_FILE": "NOT_A_FILE", + "NOT_EMPTY": "NOT_EMPTY", + "INVALID_URL": "INVALID_URL", + "IO": "IO" + }; /** Mode of opening a file. Used by onOpenFileRequested. */ - type OpenFileMode = - 'READ' | - 'WRITE'; + const OpenFileMode: { + "READ": "READ", + "WRITE": "WRITE" + }; /** Type of a change detected on the observed directory. */ - type ChangeType = - 'CHANGED' | - 'DELETED'; + const ChangeType: { + "CHANGED": "CHANGED", + "DELETED": "DELETED" + }; /** * List of common actions. 'SHARE' is for sharing files with others. * 'SAVE_FOR_OFFLINE' for pinning (saving for offline access). @@ -2826,10 +2953,11 @@ declare namespace chrome { * need to be stored for offline access anymore. * Used by onGetActionsRequested and onExecuteActionRequested. */ - type CommonActionId = - 'SAVE_FOR_OFFLINE' | - 'OFFLINE_NOT_NECESSARY' | - 'SHARE'; + const CommonActionId: { + "SAVE_FOR_OFFLINE": "SAVE_FOR_OFFLINE", + "OFFLINE_NOT_NECESSARY": "OFFLINE_NOT_NECESSARY", + "SHARE": "SHARE" + }; interface EntryMetadata { /** True if it is a directory. Must be provided if requested in options */ @@ -2898,8 +3026,11 @@ declare namespace chrome { openRequestId: integer; /** The path of the opened file. */ filePath: string; - /** Whether the file was opened for reading or writing. */ - mode: OpenFileMode; + /** + * Whether the file was opened for reading or writing. + * @see OpenFileMode + */ + mode: ToStringLiteral; } interface FileWatchersInfo { @@ -2927,8 +3058,12 @@ declare namespace chrome { } interface Action { - /** The identifier of the action. Any string or CommonActionId for common actions. */ - id: CommonActionId | string; + /** + * The identifier of the action. + * Any string or CommonActionId for common actions. + * @see CommonActionId + **/ + id: ToStringLiteral | string; /** The title of the action. It may be ignored for common actions. */ title?: string; } @@ -2981,8 +3116,11 @@ declare namespace chrome { interface NotificationChange { /** The path of the changed entry. */ entryPath: string; - /** The type of the change which happened to the entry. */ - changeType: ChangeType; + /** + * The type of the change which happened to the entry. + * @see ChangeType + */ + changeType: ToStringLiteral; } interface NotificationOptions { @@ -2996,8 +3134,9 @@ declare namespace chrome { * 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. + * @see ChangeType */ - changeType: ChangeType; + changeType: ToStringLiteral; /** List of changes to entries within the observed directory (including the entry itself) */ changes?: NotificationChange[]; /** @@ -3114,8 +3253,11 @@ declare namespace chrome { thumbnail: boolean; } interface OpenFileRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { - /** Whether the file will be used for reading or writing. */ - mode: OpenFileMode; + /** + * Whether the file will be used for reading or writing. + * @see ChangeType + */ + mode: ToStringLiteral; } interface CloseFileRequestedEventOptions extends _internal_.RequestedEventOptions { /** A request ID used to open the file. */ @@ -3226,13 +3368,13 @@ declare namespace chrome { function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; /** + * @requires Manifest: 'file_system_provider.notify' = true + * @description * 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, @@ -3263,22 +3405,24 @@ declare namespace chrome { * 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. + * @see ProviderError */ const onUnmountRequested: chrome.events.Event<( options: UnmountRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onGetMetadataRequested: chrome.events.Event<( options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** @@ -3287,124 +3431,138 @@ declare namespace chrome { * 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. + * @see ProviderError * @since Since Chrome 48. **/ const onGetActionsRequested: chrome.events.Event<( options: GetActionsRequestedEventOptions, successCallback: (actions: Action[]) => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onReadDirectoryRequested: chrome.events.Event<( options: ReadDirectoryRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onOpenFileRequested: chrome.events.Event<( options: OpenFileRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when opening a file previously opened * with openRequestId is requested to be closed. + * @see ProviderError */ const onCloseFileRequested: chrome.events.Event<( options: CloseFileRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onReadFileRequested: chrome.events.Event<( options: ReadFileRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onCreateDirectoryRequested: chrome.events.Event<( options: CreateDirectoryRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * @see ProviderError */ const onDeleteEntryRequested: chrome.events.Event<( options: DeleteEntryRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when creating a file is requested. * If the file already exists, then errorCallback must be called with the 'EXISTS' error code. + * @see ProviderError */ const onCreateFileRequested: chrome.events.Event<( options: CreateFileRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when copying an entry (recursively if a directory) is requested. * If an error occurs, then errorCallback must be called. + * @see ProviderError */ const onCopyEntryRequested: chrome.events.Event<( options: CopyEntryRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when moving an entry (recursively if a directory) is requested. * If an error occurs, then errorCallback must be called. + * @see ProviderError */ const onMoveEntryRequested: chrome.events.Event<( options: MoveEntryRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when truncating a file to a desired length is requested. * If an error occurs, then errorCallback must be called. + * @see ProviderError */ const onTruncateRequested: chrome.events.Event<( options: TruncateRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; - /** Raised when writing contents to a file opened previously with openRequestId is requested. */ + /** + * Raised when writing contents to a file opened previously with openRequestId is requested. + * @see ProviderError + */ const onWriteFileRequested: chrome.events.Event<( options: WriteFileRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** @@ -3414,68 +3572,75 @@ declare namespace chrome { * 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. + * @see ProviderError */ const onAbortRequested: chrome.events.Event<( options: AbortRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * If it's handled, the *file_system_provider.configurable* manfiest option must be set to true. + * @requires Manifest: 'file_system_provider.configurable' = true + * @see ProviderError * @since Since Chrome 44. */ const onConfigureRequested: chrome.events.Event<( options: ConfigureRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => 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. + * If the 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. + * @requires Manifest (for multiple mounts): 'file_system_provider.multiple_mounts' = true + * @see ProviderError * @since Since Chrome 44. */ const onMountRequested: chrome.events.Event<( successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when setting a new directory watcher is requested. * If an error occurs, then errorCallback must be called. + * @see ProviderError * @since Since Chrome 45. */ const onAddWatcherRequested: chrome.events.Event<( options: WatcherRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** * Raised when the watcher should be removed. * If an error occurs, then errorCallback must be called. + * @see ProviderError * @since Since Chrome 45. */ const onRemoveWatcherRequested: chrome.events.Event<( options: WatcherRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; /** - * Raised when executing an action for a set of files or directories is\ requested. + * 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. + * @see ProviderError * @since Since Chrome 48. */ const onExecuteActionRequested: chrome.events.Event<( options: ExecuteActionRequestedEventOptions, successCallback: () => void, - errorCallback: (error: ProviderError) => void + errorCallback: (error: ToStringLiteral) => void ) => void>; } @@ -4797,6 +4962,22 @@ declare namespace chrome { const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } + namespace networking { + const NetworkType: { + 'WI_FI': 'WiFi' + }; + const AuthenticationResult: { + UNHANDLED: 'unhandled', + SUCCEEDED: 'succeeded', + REJECTED: 'rejected', + FAILED: 'failed' + } + /** @todo TODO DOCUMENT THESE */ + const setNetworkFilter: Function; + const finishAuthentication: Function; + const onCaptivePortalDetected: any; + } + //////////////////////////////////// // Open Network Configuration (ONC) //////////////////////////////////// @@ -5820,6 +6001,7 @@ declare namespace chrome { /** This will be defined during an API method callback if there was an error */ const lastError: LastError | undefined; + /** The ID of the extension/app. */ const id: string; @@ -8081,6 +8263,17 @@ declare namespace chrome { * @since Chrome 30. */ namespace system.display { + const DisplayPosition: { + TOP: 'top', + RIGHT: 'right', + BOTTOM: 'bottom', + LEFT: 'left' + }; + const MirrorMode: { + OFF: 'off', + NORMAL: 'normal', + MIXED: 'mixed' + }; interface Bounds { /** The x-coordinate of the upper-left corner. */ left: integer; @@ -8152,8 +8345,6 @@ declare namespace chrome { isSelected: boolean; } - type DisplayPosition = 'top' | 'right' | 'bottom' | 'left'; - /** * @since Chrome 53 */ @@ -8162,16 +8353,18 @@ declare namespace chrome { id: string; /** 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: DisplayPosition; + /** + * The layout position of this display relative to the parent. + * This will be ignored for the root. + * @see enum DisplayPosition + */ + position: ToStringLiteral; /** The offset of the display along the connected edge. 0 indicates that the topmost or leftmost corners are aligned. */ offset: integer; } /** - * The pairs of point used to calibrate the display. - * @export - * @interface TouchCalibrationPairs + * The pairs of point used to calibrate the display. */ interface TouchCalibrationPairs { /** First pair of touch and display point required for touch calibration. */ @@ -8185,55 +8378,87 @@ declare namespace chrome { } /** - * Representation of info data to be used in chrome.system.display.setDisplayProperties() - * @export - * @interface DisplayPropertiesInfo + * Representation of info data to be used in chrome.system.display.setDisplayProperties() */ interface DisplayPropertiesInfo { /** - * 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. + * @requires(CrOS) Chrome OS only. + * @description + * If set to true, changes the display mode to unified desktop. + * 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. + * @see(See enableUnifiedDesktop for details). * @since Chrome 59 * */ isUnified?: boolean; /** - * Chrome OS only. If set and not empty, enables mirroring for this display. Otherwise disables mirroring for this display. This value should indicate the id of the source display to mirror, which must not be the same as the id passed to setDisplayProperties. If set, no other property may be set. + * @requires(CrOS) Chrome OS only. + * @description + * If set and not empty, enables mirroring for this display. + * Otherwise disables mirroring for this display. + * This value should indicate the id of the source display to mirror, + * which must not be the same as the id passed to setDisplayProperties. + * If set, no other property may be set. */ mirroringSourceId?: string; - /** If set to true, makes the display primary. No-op if set to false. */ + /** + * If set to true, makes the display primary. + * No-op if set to false. + */ isPrimary?: boolean; - /** If set, sets the display's overscan insets to the provided values. Note that overscan values may not be negative or larger than a half of the screen's size. Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. */ + /** + * If set, sets the display's overscan insets to the provided values. + * Note that overscan values may not be negative or larger than a half of the screen's size. + * Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. + */ overscan?: Insets; - /** If set, updates the display's rotation. Legal values are [0, 90, 180, 270]. The rotation is set clockwise, relative to the display's vertical position. It's applied after overscan paramter. */ + /** + * If set, updates the display's rotation. + * Legal values are [0, 90, 180, 270]. + * The rotation is set clockwise, relative to the display's vertical position. + * It's applied after overscan paramter. + */ rotation?: 0 | 90 | 180 | 270; - /** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */ + /** + * If set, updates the display's logical bounds origin along x-axis. + * Applied together with boundsOriginY, if boundsOriginY is set. + * Note that, when updating the display origin, some constraints will be applied, + * so the final bounds origin may be different than the one set. + * The final bounds can be retrieved using getInfo. The bounds origin is applied + * after rotation. The bounds origin cannot be changed on the primary display. + * Note that is also invalid to set bounds origin values if isPrimary is also set + * (as isPrimary parameter is applied first). + */ boundsOriginX?: integer; - /** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */ + /** + * If set, updates the display's logical bounds origin along y-axis. + * @see[See documentation for boundsOriginX parameter.] + */ boundsOriginY: integer; /** + * If set, updates the display mode to the mode matching this value. * @since Chrome 52 - * If set, updates the display mode to the mode matching this value. */ displayMode?: DisplayMode; } /** - * Options affecting how the information is returned. + * Options affecting how the information is returned. * @since Chrome 59 - * @export - * @interface DisplayInfoFlags */ interface DisplayInfoFlags { /** - * 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 + * If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode. + * @see[enableUnifiedDesktop] + * @default false */ singleUnified?: boolean; } @@ -8266,7 +8491,7 @@ declare namespace chrome { workArea: Bounds; } - /** 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|. */ + /** 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**. */ interface DisplayProps { /** If set and not empty, starts mirroring between this and the display with the provided id (the system will determine which of the displays is actually mirrored). If set and not empty, stops mirroring between this and the display with the specified id (if mirroring is in progress). If set, no other parameter may be set. */ mirroringSourceId?: string; @@ -8283,39 +8508,33 @@ declare namespace chrome { } /** - * Fired when anything changes to the display configuration. - * @export - * @interface DisplayChangedEvent - * @extends {chrome.events.Event<() => void>} - */ - interface DisplayChangedEvent extends chrome.events.Event<() => void> { } - - /** - * Requests the information for all attached display devices. - * @export - * @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results. + * Requests the information for all attached display devices. + * @param callback The callback to invoke with the results. */ function getInfo(callback: (info: DisplayInfo[]) => void): void; /** - * Requests the information for all attached display devices. - * @export + * Requests the information for all attached display devices. * @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. + * @param flags Options affecting how the information is returned. + * @param callback The callback to invoke with the results. */ function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void; /** - * Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. + * @description Requests the layout info for all displays. * @since Chrome 53 * @export - * @param {(layouts: DisplayLayout[]) => void} callback The callback to invoke with the results. + * @param callback The callback to invoke with the results. */ function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; /** - * 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 + * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. + * @description + * Updates the properties for the display specified by **id**, + * according to the information provided in **info**. + * On failure, runtime.lastError will be set. * @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. @@ -8323,91 +8542,104 @@ declare namespace chrome { function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void; /** - * 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. + * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. + * @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. * @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. + * @param layouts The layout information, required for all displays except the primary display. + * @param callback Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void; /** - * 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. + * @requires(CrOS Kiosk apps | WebUI) This is only available to Chrome OS Kiosk apps and Web UI. + * @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) * @since Chrome 46 - * @export * @param {boolean} enabled True if unified desktop should be enabled. */ function enableUnifiedDesktop(enabled: boolean): void; /** - * 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. + * @param id The display's unique identifier. */ function overscanCalibrationStart(id: string): void; /** - * 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. + * @param id The display's unique identifier. + * @param delta The amount to change the overscan insets. */ function overscanCalibrationAdjust(id: string, delta: Insets): void; /** - * 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. + * @param id The display's unique identifier. */ function overscanCalibrationReset(id: string): void; /** - * 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. + * @param id The display's unique identifier. */ function overscanCalibrationComplete(id: string): void; /** - * 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. + * @param id The display's unique identifier. + * @param 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. */ function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; /** - * 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. + * @param id The display's unique identifier. */ function startCustomTouchCalibration(id: string): void; /** - * 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. + * @param pairs The pairs of point used to calibrate the display. + * @param bounds Bounds of the display when the touch calibration was performed. |bounds.left| and |bounds.top| values are ignored. + * @throws Error */ function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void; + /** - * 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. + * @param id The display's unique identifier. */ function clearTouchCalibration(id: string): void; /** - * Fired when anything changes to the display configuration. - * @export + * Fired when anything changes to the display configuration. */ - const onDisplayChanged: DisplayChangedEvent; + const onDisplayChanged: chrome.events.Event<() => void>; } /////////////////// @@ -8415,7 +8647,7 @@ declare namespace chrome { /////////////////// /** * The chrome.system.memory API. - * Permissions: 'system.memory' + * @requires Permissions: 'system.memory' * @since Chrome 32. */ namespace system.memory { @@ -8433,6 +8665,10 @@ declare namespace chrome { ////////////////////// // System - Network // ////////////////////// + /** + * The chrome.system.network API. + * @requires Permissions: 'system.network' + */ namespace system.network { interface NetworkInterface { name: string; @@ -8462,12 +8698,27 @@ declare namespace chrome { //////////////////// /** * Use the chrome.system.storage API to query storage device information and be notified when a removable storage device is attached and detached. - * Permissions: 'system.storage' + * @requires Permissions: 'system.storage' * @since Chrome 30. */ namespace system.storage { + const StorageUnitType: { + FIXED: "fixed", + REMOVABLE: "removable", + UNKNOWN: "unknown" + }; + const EjectDeviceResultCode: { + SUCCESS: "success", + IN_USE: "in_use", + NO_SUCH_DEVICE: "no_such_device", + FAILURE: "failure" + }; interface StorageUnitInfo { - /** The transient ID that uniquely identifies the storage device. This ID will be persistent within the same run of a single application. It will not be a persistent identifier between different runs of an application, or between different applications. */ + /** + * The transient ID that uniquely identifies the storage device. + * This ID will be persistent within the same run of a single application. + * It will not be a persistent identifier between different runs of an application, or between different applications. + */ id: string; /** The name of the storage unit. */ name: string; @@ -8476,31 +8727,37 @@ declare namespace chrome { * fixed: The storage has fixed media, e.g. hard disk or SSD. * removable: The storage is removable, e.g. USB flash drive. * unknown: The storage type is unknown. + * @see enum StorageUnitType */ - type: string; + type: ToStringLiteral; /** The total amount of the storage space, in bytes. */ capacity: integer; } interface StorageCapacityInfo { - /** A copied |id| of getAvailableCapacity function parameter |id|. */ + /** A copied **id** of getAvailableCapacity function parameter **id**. */ id: string; /** The available capacity of the storage device, in bytes. */ availableCapacity: integer; } - interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> { } - - 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. */ 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. + * 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. */ - function ejectDevice(id: string, callback: (result: string) => void): void; + function ejectDevice(id: string, callback: (result: ToStringLiteral) => 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. @@ -8508,9 +8765,9 @@ declare namespace chrome { function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; /** Fired when a new removable storage is attached to the system. */ - const onAttached: SystemStorageAttachedEvent; + const onAttached: chrome.events.Event<(info: StorageUnitInfo) => void>; /** Fired when a removable storage is detached from the system. */ - const onDetached: SystemStorageDetachedEvent; + const onDetached: chrome.events.Event<(id: string) => void>; } //////////////////// @@ -9151,6 +9408,24 @@ declare namespace chrome { * @since Chrome 43. */ namespace vpnProvider { + const PlatformMessage: { + CONNECTED: "connected", + DISCONNECTED: "disconnected", + ERROR: "error", + LINK_DOWN: "linkDown", + LINK_UP: "linkUp", + LINK_CHANGED: "linkChanged", + SUSPEND: "suspend", + RESUME: "resume" + }; + const VpnConnectionState: { + CONNECTED: "connected", + FAILURE: "failure" + }; + const UIEvent: { + SHOW_ADD_DIALOG: "showAddDialog", + SHOW_CONFIGURE_DIALOG: "showConfigureDialog" + }; interface VpnSessionParameters { /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ address: string; @@ -9184,6 +9459,7 @@ declare namespace chrome { dnsServer: string[]; } + /** @todo TODO Move to consts. Implement PlatformMessage enum & check usage of the other enums */ interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> { } interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> { } @@ -9192,7 +9468,7 @@ declare namespace chrome { interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> { } - interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> { } + interface VpnUiEvent extends chrome.events.Event<(event: ToStringLiteral, id?: string) => void> { } /** * Creates a new VPN configuration that persists across multiple login sessions of the user. @@ -9224,9 +9500,10 @@ declare namespace chrome { * @param state The VPN session state of the VPN client. * connected: VPN connection was successful. * failure: VPN connection failed. + * @see enum VpnConnectionState * @param callback Called when the notification is complete or if there is an error. */ - function notifyConnectionStateChanged(state: string, callback?: Function): void; + function notifyConnectionStateChanged(state: ToStringLiteral, callback?: Function): void; /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ const onPlatformMessage: VpnPlatformMessageEvent; @@ -9236,7 +9513,10 @@ declare namespace chrome { const onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ 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. */ + /** + * 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. + */ const onUIEvent: VpnUiEvent; } From 7a6a964cca788799c90353aa3776fbf74c35b7f2 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 14 Aug 2018 15:25:34 +0200 Subject: [PATCH 049/289] Removed unnecessary references to extensions in the documentation. --- types/chrome-apps/index.d.ts | 399 +++++++++++++++++++++++------------ 1 file changed, 259 insertions(+), 140 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 8efa543cf4..758c778498 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -102,8 +102,8 @@ declare namespace chrome { * One of * • not_controllable: cannot be controlled by any extension * • controlled_by_other_extensions: controlled by extensions with higher precedence - * • controllable_by_this_extension: can be controlled by this extension - * • controlled_by_this_extension: controlled by this extension + * • controllable_by_this_extension: can be controlled by this app + * • controlled_by_this_extension: controlled by this app */ 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. */ @@ -261,7 +261,7 @@ declare namespace chrome { * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. * That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. * `when` can be set to less than 1 minute after 'now' without warning but won't actually cause the alarm to fire for at least 1 minute. - * 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. + * To help you debug your app, 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. */ function create(alarmInfo: AlarmCreateInfo): void; @@ -271,7 +271,7 @@ declare namespace chrome { * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. * That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. * `when` can be set to less than 1 minute after 'now' without warning but won't actually cause the alarm to fire for at least 1 minute. - * 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. + * To help you debug your app, when you've loaded it unpacked, there's no limit to how often the alarm can fire. * @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. */ @@ -622,13 +622,15 @@ declare namespace chrome { /** * If true, the window will have its own shelf icon. * Otherwise the window will be grouped in the shelf with other windows that are associated with the app. - * Defaults to false. * If showInShelf is set to true you need to specify an id for the window. + * @default false * @since Since Chrome 54. */ showInShelf?: boolean; /** - * URL of the window icon. A window can have its own icon when showInShelf is set to true. The URL should be a global or an extension local URL. + * URL of the window icon. + * A window can have its own icon when showInShelf is set to true. + * The URL should be a global or an app's local URL. * @since Since Chrome 54. */ icon?: string; @@ -1972,9 +1974,9 @@ declare namespace chrome { */ namespace commands { interface Command { - /** The name of the Extension Command */ + /** The name of the command */ name?: string; - /** The Extension Command description */ + /** The command description */ description?: string; /** The shortcut active for this command, or blank if not active. */ shortcut?: string; @@ -1983,7 +1985,7 @@ declare namespace chrome { interface CommandEvent extends chrome.events.Event<(command: string) => void> { } /** - * Returns all the registered extension commands for this extension and their shortcut (if active). + * Returns all the registered commands for this app and their shortcut (if active). * @param callback Called to return the registered commands. */ function getAll(callback: (commands: Command[]) => void): void; @@ -2018,7 +2020,7 @@ declare namespace chrome { * @default 6 * @description * The maximum number of top level extension items that - * can be added to an extension action context menu. + * can be added to an app's action context menu. * Any items beyond this limit will be ignored. */ const ACTION_MENU_TOP_LEVEL_LIMIT: integer; @@ -2147,7 +2149,7 @@ declare namespace chrome { /** * The unique ID to assign to this item. * Mandatory for event pages. - * Cannot be the same as another ID for this extension. + * Cannot be the same as another ID for this app. */ id?: string; @@ -2263,7 +2265,7 @@ declare namespace chrome { function remove(menuItemId: integer | string, callback?: () => void): void; /** - * Removes all context menu items added by this extension. + * Removes all context menu items added by this app. * @param callback Called when removal is complete. */ function removeAll(callback?: () => void): void; @@ -2289,8 +2291,7 @@ declare namespace chrome { // Desktop Capture // ///////////////////// /** - * Desktop Capture API that can be used to capture content of screen, - * individual windows or tabs. + * Desktop Capture API that can be used to capture content of screen or individual windows. * @since Availability: Since Chrome 34. * @requires Permissions: 'desktopCapture' */ @@ -2760,7 +2761,7 @@ declare namespace chrome { */ description?: string; /** - * Mime-types to accept, e.g. 'image/jpeg' or 'audio/*'. One of mimeTypes or extensions must contain at least one valid element. + * Mime-types to accept, e.g. 'image/jpeg' or 'audio/*'. One of mimeTypess must contain at least one valid element. */ mimeTypes?: string[]; /** @@ -3355,7 +3356,7 @@ declare namespace chrome { function unmount(options: UnmountOptions, callback?: () => void): void; /** - * Returns all file systems mounted by the extension. + * Returns all file systems mounted by the app. * @param callback Callback to receive the result of getAll function. */ function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; @@ -3377,7 +3378,7 @@ declare namespace chrome { * * 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, + * Eg. if the providing app 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. @@ -3648,7 +3649,7 @@ declare namespace chrome { // Google Cloud Messaging // //////////////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and receive + * Use chrome.gcm to enable apps to send and receive * messages through the Google Cloud Messaging Service. * @deprecated * As of April 10, 2018, Google has deprecated GCM. @@ -3945,7 +3946,7 @@ declare namespace chrome { /** * Event generated when a device is added to the system. - * Events are only broadcast to apps and extensions that + * Events are only broadcast to apps that * have permission to access the device. Permission may * have been granted at install time or when the user * accepted an optional permission. @@ -4502,7 +4503,7 @@ declare namespace chrome { //////////////// /** * The chrome.management API provides ways to - * manage the list of extensions/apps + * manage the list of apps * that are installed and running. */ namespace management { @@ -5636,22 +5637,26 @@ declare namespace chrome { * @see[Docs]{@link https://developer.chrome.com/extensions/notifications} */ namespace notifications { - /** @enum */ + /** + * @enum + * @prop BASIC - icon, title, message, expandedMessage, up to two buttons. + * @prop IMAGE - icon, title, message, expandedMessage, image, up to two buttons. + * @prop LIST - icon, title, message, items, up to two buttons. Users on Mac OS X only see the first item. + * @prop PROGRESS - icon, title, message, progress, up to two buttons. + */ const TemplateType: { - /** icon, title, message, expandedMessage, up to two buttons */ BASIC: "basic", - /** icon, title, message, expandedMessage, image, up to two buttons */ IMAGE: "image", - /** icon, title, message, items, up to two buttons. Users on Mac OS X only see the first item. */ LIST: "list", - /** icon, title, message, progress, up to two buttons */ PROGRESS: "progress" } - /** @enum */ + /** + * @enum + * @property GRANTED - User has elected to show notifications from the app . This is the default at install time. + * @property DENIED - User has elected not to show notifications from the app. + */ const PermissionLevel: { - /** User has elected to show notifications from the app or extension. This is the default at install time. */ GRANTED: "granted", - /** User has elected not to show notifications from the app or extension. */ DENIED: "denied" } @@ -5676,7 +5681,7 @@ declare namespace chrome { /** * Optional. * A URL to the sender's avatar, app icon, or a thumbnail for image notifications. - * 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. + * URLs can be a data URL, a blob URL, or a URL relative to a resource within this app's .crx file Required for notifications.create method. */ iconUrl: string; @@ -5811,7 +5816,7 @@ declare namespace chrome { function getAll(callback: (notifications: { [notificationId: string]: true }) => void): void; /** - * Retrieves whether the user has enabled notifications from this app or extension. + * Retrieves whether the user has enabled notifications from this app . * @since Chrome 32. * @param callback Returns the current permission level. * @see enum PermissionLevel @@ -5878,6 +5883,25 @@ declare namespace chrome { const onAdded: PermissionEvent; } + /////////////////// + // Platform Keys // + /////////////////// + /** + * @requires(CrOS) Only for Chrome OS. + * @requires Permissions: 'platformKeys' + * @todo TODO Documentation needed + */ + namespace platformKeys { + const ClientCertificateType: { + "RSA_SIGN": "rsaSign", + "ECDSA_SIGN": "ecdsaSign" + }; + const selectClientCertificates: Function; + const getKeyPair: Function; + const subtleCrypto: Function; + const verifyTLSServerCertificate: Function; + } + /////////// // Power // /////////// @@ -5887,11 +5911,13 @@ declare namespace chrome { * @since Chrome 27. */ namespace power { - /** @enum */ + /** + * @enum + * @property SYSTEM - Prevent the system from sleeping in response to user inactivity. + * @property DISPLAY - Prevent the display from being turned off or dimmed or the system from sleeping in response to user inactivity. + */ const Level: { - /** Prevent the system from sleeping in response to user inactivity. */ SYSTEM: 'system', - /** Prevent the display from being turned off or dimmed or the system from sleeping in response to user inactivity. */ DISPLAY: 'display' } /** @@ -5962,7 +5988,7 @@ declare namespace chrome { // Runtime //////////////////// /** - * Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. + * Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. * @since Chrome 22 */ namespace runtime { @@ -6002,7 +6028,7 @@ declare namespace chrome { /** This will be defined during an API method callback if there was an error */ const lastError: LastError | undefined; - /** The ID of the extension/app. */ + /** The ID of the app. */ const id: string; interface LastError { @@ -6043,7 +6069,7 @@ declare namespace chrome { * @since Chrome 26. */ interface MessageSender { - /** The ID of the extension or app that opened the connection, if any. */ + /** The ID of the app that opened the connection, if any. */ id?: string; /** * The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set. @@ -6056,7 +6082,7 @@ declare namespace chrome { */ url?: string; /** - * The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, and if available. + * The TLS channel ID of the page or frame that opened the connection, if requested by the app, and if available. * @since Chrome 32. */ tlsChannelId?: string; @@ -6285,19 +6311,19 @@ declare namespace chrome { */ 'audioCapture' | /** - * Makes Chrome start up early and and shut down late, so that apps and extensions can have a longer life. + * Makes Chrome start up early and and shut down late, so that apps can have a longer life. * When any installed app has "background" permission, Chrome runs (invisibly) as soon as the user logs * into their computer—before the user launches Chrome. The "background" permission also makes Chrome * continue running (even after its last window is closed) until the user explicitly quits Chrome. - * Note: Disabled apps and extensions are treated as if they aren't installed. + * Note: Disabled apps are treated as if they aren't installed. */ 'background' | /** Gives your app access to the chrome.browser API. */ 'browser' | - /** Required if the extension or app uses document.execCommand('paste'). */ + /** Required if the app uses document.execCommand('paste'). */ 'clipboardRead' | /** - * Indicates the extension or app uses document.execCommand('copy') or document.execCommand('cut'). + * Indicates the app uses document.execCommand('copy') or document.execCommand('cut'). * This permission is recommended for packaged apps. */ 'clipboardWrite' | @@ -6314,7 +6340,7 @@ declare namespace chrome { * Gives your app access to the chrome.gcm API. */ 'gcm' | - /** Allows the extension or app to use the proposed HTML5 geolocation API without prompting the user for permission. */ + /** Allows the app to use the proposed HTML5 geolocation API without prompting the user for permission. */ 'geolocation' | /** Gives your app access to the chrome.hid API. */ 'hid' | @@ -6374,7 +6400,7 @@ declare namespace chrome { 'tts' | /** * Provides an unlimited quota for storing HTML5 client-side data, such as databases and local storage files. - * Without this permission, the extension or app is limited to 5 MB of local storage. + * Without this permission, the app is limited to 5 MB of local storage. * * *Note* * *This permission applies only to Web SQL Database and application cache* @@ -6575,7 +6601,7 @@ declare namespace chrome { */ name: string; /** - * One to four dot-separated integers identifying the version of this extension. + * One to four dot-separated integers identifying the version of this app. * A couple of rules apply to the integers: they must be between 0 and 65535, inclusive, * and non-zero integers can't start with 0. For example, 99999 and 032 are both invalid. * A missing integer is equal to zero. For example, 1.1.9.9999 is newer than 1.1. @@ -6589,7 +6615,7 @@ declare namespace chrome { ///////////////// /** - * Specifies the subdirectory of _locales that contains the default strings for this extension. + * Specifies the subdirectory of _locales that contains the default strings for this app. * This field is required in apps that have a _locales directory; it must be absent in * apps that have no _locales directory. For details, see Internationalization: * @see[Internationalization]{@see https://developer.chrome.com/extensions/i18n} @@ -6810,7 +6836,7 @@ declare namespace chrome { /** One or more mappings from MIME types to the Native Client module that handles each type. */ nacl_modules?: { - /** The location of a Native Client manifest (a .nmf file) within the extension directory. */ + /** The location of a Native Client manifest (a .nmf file) within the app's directory. */ path: string; /** The MIME type for which the Native Client module will be registered as content handler. */ mime_type: string; @@ -6829,7 +6855,7 @@ declare namespace chrome { }; /** - * Whether the app or extension is expected to work offline. + * Whether the app is expected to work offline. * When Chrome detects that it is offline, apps with this field set to true will be highlighted on the New Tab page. */ offline_enabled?: boolean; @@ -6861,7 +6887,7 @@ declare namespace chrome { /** * Technologies required by the app. Hosting sites such * as the Chrome Web Store may use this list to dissuade - * users from installing apps or extensions that will not + * users from installing appss that will not * work on their computer. Supported requirements currently * include '3D' and 'plugins'; additional requirements checks * may be added in the future. @@ -6891,7 +6917,7 @@ declare namespace chrome { * The 'plugins' requirement indicates if an app requires NPAPI to run. * * This requirement is enabled by default when the manifest includes the 'plugins' field. - * For apps and extensions that still work when plugins aren't available, + * For apps that still work when plugins aren't available, * you can disable this requirement by setting NPAPI to false. * You can also enable this requirement manually, * by setting NPAPI to true as shown in this example: @@ -6977,10 +7003,10 @@ declare namespace chrome { // system_indicator?: any; // Deprecated / removed: https://bugs.chromium.org/p/chromium/issues/detail?id=142450 /** * If you publish using the Chrome Developer Dashboard, ignore this field. - * If you host your own extension or app: URL to an update manifest XML file. + * If you host your own app: URL to an update manifest XML file. * **Warning** * As of M33, Windows stable / beta channel users can only - * download extensions hosted in the Chrome Web Store + * download apps hosted in the Chrome Web Store * @requires(not Windows) * (@see[Protecting Windows users from malicious extensions]{@link http://blog.chromium.org/2013/11/protecting-windows-users-from-malicious.html}). * @see[Documentation]{@link https://developer.chrome.com/apps/autoupdate} @@ -7116,15 +7142,21 @@ declare namespace chrome { type Manifest = ValidKioskManifest | ValidNonKioskManifest | InvalidManifest; /** - * 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. + * Attempts to connect to connect listeners within an app (such as the background page), or other apps. + * This is useful for content scripts connecting to their extension processes, inter-app communication, and web messaging. + * Note that this does not connect to any listeners in a content script. * @since Chrome 26. */ 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. + * Attempts to connect to connect listeners within an app (such as the background page), or other apps. + * This is useful for content scripts connecting to their extension processes, inter-app communication, and web messaging. + * Note that this does not connect to any listeners in a content script. * @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. + * @param extensionId Optional; ID of the extension. + * The ID of the extension or app to connect to. + * If omitted, a connection will be attempted with your own app. + * Required if sending messages from a web page for web messaging. */ function connect(extensionId: string, connectInfo?: ConnectInfo): Port; /** @@ -7135,14 +7167,14 @@ declare namespace chrome { function connectNative(application: string): Port; /** - * Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. + * Retrieves the JavaScript 'window' object for the background page running inside the current 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. + * Returns details about the app from the manifest. * The object returned is a serialization of the full manifest file. * @returns The manifest details. */ @@ -7162,19 +7194,19 @@ declare namespace chrome { 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. + * Converts a relative path within an app install directory to a fully-qualified URL. + * @param path A path to a resource within an app expressed relative to its install directory. */ function getURL(path: string): string; /** - * Reloads the app or extension. + * Reloads the app . * @since Chrome 25. */ function reload(): void; /** - * Requests an update check for this app/extension. + * Requests an update check for this app. * @since Chrome 25. * @param callback * Parameter status: Result of the update check. See enum RequestUpdateCheckStatus. @@ -7189,7 +7221,9 @@ declare namespace chrome { 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. + * Sends a single message to event listeners within your app or a different 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. * @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. @@ -7197,7 +7231,7 @@ declare namespace chrome { 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. + * Sends a single message to event listeners within your app or a different 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. * @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. @@ -7205,18 +7239,18 @@ declare namespace chrome { 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. + * Sends a single message to event listeners within your app or a different 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. * @since Chrome 26. - * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. + * @param extensionId The ID of the app to send the message to. If omitted, the message will be sent to your own app. Required if sending messages from a web page for web messaging. * @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. */ 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. + * Sends a single message to event listeners within your app or a different 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. * @since Chrome 32. - * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. + * @param extensionId The ID of the app to send the message to. If omitted, the message will be sent to your own app. Required if sending messages from a web page for web messaging. * @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. */ @@ -7261,7 +7295,7 @@ declare namespace chrome { /** 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. */ 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. + * Fired when a profile that has this app installed first starts up. This event is not fired when an incognito profile is started, even if this app is operating in 'split' incognito mode. * @since Chrome 23. */ const onStartup: RuntimeEvent; @@ -7275,7 +7309,7 @@ declare namespace chrome { */ const onMessage: ExtensionMessageEvent; /** - * Fired when a message is sent from another extension/app. Cannot be used in a content script. + * Fired when a message is sent from another app. Cannot be used in a content script. * @since Chrome 26. */ const onMessageExternal: ExtensionMessageEvent; @@ -8020,7 +8054,12 @@ declare namespace chrome { } interface LocalStorageArea extends StorageArea { - /** The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ + /** The maximum amount (in bytes) of data that can be stored in local storage, + * as measured by the JSON stringification of every value plus every key's length. + * This value will be ignored if the extension has the unlimitedStorage permission. + * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. + * @default 5242880 + */ QUOTA_BYTES: integer; } @@ -8079,6 +8118,7 @@ declare namespace chrome { */ namespace syncFileSystem { /** + * @enum * 'initializing' * - The sync service is being initialized (e.g. restoring data from the database, checking connectivity and authenticating to the service etc). * 'running' @@ -8090,13 +8130,16 @@ declare namespace chrome { * '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'; + const ServiceStatus: { + "INITIALIZING": "initializing", + "RUNNING": "running", + "AUTHENTICATION_REQUIRED": "authentication_required", + "TEMPORARY_UNAVAILABLE": "temporary_unavailable", + "DISABLED": "disabled" + }; + /** + * @enum * 'synced' * - Not conflicting and has no pending local changes. * 'pending' @@ -8104,28 +8147,36 @@ declare namespace chrome { * 'conflicting' * - File conflicts with remote version and must be resolved manually. */ - type FileStatus = - 'synced' | - 'pending' | - 'conflicting'; - type ConflictResolutionPolicy = - 'last_write_win' | - 'manual' + const FileStatus: { + "SYNCED": "synced", + "PENDING": "pending", + "CONFLICTING": "conflicting" + } - type Action = - 'added' | - 'updated' | - 'deleted' + const ConflictResolutionPolicy: { + "LAST_WRITE_WIN": "last_write_win", + "MANUAL": "manual" + }; - type Direction = - 'local_to_remote' | - 'remote_to_local'; + const SyncAction: { + "ADDED": "added", + "UPDATED": "updated", + "DELETED": "deleted" + } + + const SyncDirection: { + "LOCAL_TO_REMOTE": "local_to_remote", + "REMOTE_TO_LOCAL": "remote_to_local" + }; interface FileStatusInfo { /** One of the Entry's originally given to getFileStatuses. */ fileEntry: Entry; - /** Status value */ - status: FileStatus; + /** + * Status value + * @see FileStatus + */ + status: ToStringLiteral; /** Optional error that is only returned if there was a problem retrieving the FileStatus for the given file. */ error?: string; } @@ -8139,21 +8190,21 @@ declare namespace chrome { fileEntry: Entry; /** * Resulting file status after onFileStatusChanged event. - * The status value can be 'synced', 'pending' or 'conflicting'. + * @see FileStatus */ - status: FileStatus; + status: ToStringLiteral; /** * Sync action taken to fire onFileStatusChanged event. - * The action value can be 'added', 'updated' or 'deleted'. * Only applies if status is 'synced'. + * @see SyncAction */ - action?: Action; + action?: ToStringLiteral; /** * Sync direction for the onFileStatusChanged event. - * Sync direction value can be 'local_to_remote' or - * 'remote_to_local'. Only applies if status is 'synced'. + * Only applies if status is 'synced'. + * @see SyncDirection */ - direction?: Direction; + direction?: ToStringLiteral; } /** * Returns a syncable filesystem backed by Google Drive. @@ -8177,11 +8228,15 @@ declare namespace chrome { * resolved next time the file is updated. |callback| can be optionally given to * know if the request has succeeded or not. * @param policy Policy + * @see ConflictResolutionPolicy * @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; + function setConflictResolutionPolicy(policy: ToStringLiteral, callback?: () => void): void; + /** + * Gets the current conflict resolution policy. + * @see ConflictResolutionPolicy + */ + function getConflictResolutionPolicy(callback: (policy: ToStringLiteral) => void): void; /** * Returns the current usage and quota in bytes for the 'syncable' file storage for the app. * @param fileSystem @@ -8192,18 +8247,24 @@ declare namespace chrome { * Returns the FileStatus for the given fileEntry. * Note that 'conflicting' state only happens when * the service's conflict resolution policy is set to 'manual'. + * @see FileStatus * */ - function getFileStatus(fileEntry: Entry, callback: (status: FileStatus) => void): void; + function getFileStatus(fileEntry: Entry, callback: (status: ToStringLiteral) => 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 + * @see ServiceStatus */ - 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>; + function getServiceStatus(callback: (status: ToStringLiteral) => 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). + * @see ServiceStatus + */ + const onServiceStatusChanged: chrome.events.Event<(detail: { state: ToStringLiteral, description: string }) => void>; /** Fired when a file has been updated by the background sync service. */ const onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } @@ -8937,8 +8998,8 @@ declare namespace chrome { * One of * • not_controllable: cannot be controlled by any extension * • controlled_by_other_extensions: controlled by extensions with higher precedence - * • controllable_by_this_extension: can be controlled by this extension - * • controlled_by_this_extension: controlled by this extension + * • controllable_by_this_extension: can be controlled by this app + * • controlled_by_this_extension: controlled by this app */ levelOfControl: string; /** The value of the setting. */ @@ -8993,7 +9054,43 @@ declare namespace chrome { */ namespace usb { /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ - type Direction = 'in' | 'out'; + const Direction: { + "IN": "in", + "OUT": "out" + }; + /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ + const Recipient: { + "DEVICE": "device", + "INTERFACE": "interface", + "ENDPOINT": "endpoint", + "OTHER": "other" + }; + /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ + const RequestType: { + "STANDARD": "standard", + "CLASS": "class", + "VENDOR": "vendor", + "RESERVED": "reserved" + }; + /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ + const TransferType: { + "CONTROL": "control", + "INTERRUPT": "interrupt", + "ISOCHRONOUS": "isochronous", + "BULK": "bulk" + }; + const SynchronizationType: { + "ASYNCHRONOUS": "asynchronous", + "ADAPTIVE": "adaptive", + "SYNCHRONOUS": "synchronous" + }; + const UsageType: { + "DATA": "data", + "FEEDBACK": "feedback", + "EXPLICIT_FEEDBACK": "explicitFeedback", + "PERIODIC": "periodic", + "NOTIFICATION": "notification" + }; interface Device { /** @@ -9042,24 +9139,33 @@ declare namespace chrome { productId: integer; } - type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; - type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; - type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback' | 'periodic' | 'notification'; - /** Since Chrome 29. */ interface EndpointDescriptor { /** Transfer type. */ address: integer; - /** Transfer type. */ - type: EndpointType; - /** Transfer direction. */ - direction: Direction; + /** + * Transfer type. + * @see TransferType + * + */ + type: ToStringLiteral; + /** + * Transfer direction. + * @see Direction + */ + direction: ToStringLiteral; /** Maximum packet size. */ maximumPacketSize: integer; - /** Transfer synchronization mode (isochronous only). */ - synchronization?: EndpointSyncType; - /** Endpoint usage hint */ - usage?: EndpointUsage; + /** + * Transfer synchronization mode (isochronous only). + * @see SynchronizationType + */ + synchronization?: ToStringLiteral; + /** + * Endpoint usage hint + * @see UsageType + */ + usage?: ToStringLiteral; /** Polling interval (interrupt and isochronous only). */ pollingInterval?: integer; /** @@ -9119,8 +9225,11 @@ declare namespace chrome { } interface GenericTransferInfo { - /** The transfer direction ('in' or 'out'). */ - direction: Direction; + /** + * The transfer direction ('in' or 'out'). + * @see Direction + */ + direction: ToStringLiteral; /** The target endpoint address. The interface containing this endpoint must be claimed. */ endpoint: integer; /** The maximum number of bytes to receive (required only by input transfers). */ @@ -9158,17 +9267,23 @@ declare namespace chrome { /** @since Since Chrome 39. */ interface DeviceFilter extends Partial { } - type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; - - type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; - interface TransferInfo { - /** The transfer direction ('in' or 'out'). */ - direction: Direction; - /** The transfer target. The target given by index must be claimed if 'interface' or 'endpoint'. */ - recipient: TransferRecipient; - /** The request type. */ - requestType: TransferRequestType; + /** + * The transfer direction ('in' or 'out'). + * @see Direction + */ + direction: ToStringLiteral; + /** + * The transfer target. + * The target given by index must be claimed if 'interface' or 'endpoint'. + * @see Recipient + */ + recipient: ToStringLiteral; + /** + * The request type. + * @see RequestType + */ + requestType: ToStringLiteral; /** The bRequest field, see *Universal Serial Bus Specification Revision 1.1 § 9.3.* */ request: integer; /** The wValue field, see *Ibid*. */ @@ -9381,7 +9496,7 @@ declare namespace chrome { /** * 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. + * Events are only broadcast to apps that have permission to access the device. * Permission may have been granted at install time, when the user accepted an optional permission * (@see[permissions.request]{https://developer.chrome.com/apps/permissions#method-request}), * or through **getUserSelectedDevices**. @@ -9530,17 +9645,21 @@ declare namespace chrome { * @since Chrome 43. */ namespace wallpaper { - type WallpaperLayout = - 'STRETCH' | - 'CENTER' | - 'CENTER_CROPPED'; + const WallpaperLayout: { + "STRETCH": "STRETCH", + "CENTER": "CENTER", + "CENTER_CROPPED": "CENTER_CROPPED" + }; interface WallpaperDetails { /** The jpeg or png encoded wallpaper image. */ data?: any; /** The URL of the wallpaper to be set. */ url?: string; - /** The supported wallpaper layouts. */ - layout: WallpaperLayout; + /** + * The supported wallpaper layouts. + * @see WallpaperLayout + */ + layout: ToStringLiteral; /** The file name of the saved wallpaper. */ filename: string; /** True if a 128x60 thumbnail should be generated. */ From bbb450bd0a3032b05d4039ab365f0a1b83f1cba0 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 14 Aug 2018 16:04:54 +0200 Subject: [PATCH 050/289] Better api docs --- types/chrome-apps/index.d.ts | 56 ++++++++++++++++++++++++++++++--- types/chrome-apps/test/index.ts | 50 +++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 758c778498..09ab1c530d 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1885,9 +1885,11 @@ declare namespace chrome { /** * @requires(CrOS) Chrome OS only. * @requires Permissions: 'certificateProvider' + * @description Provide certificates for authentication * @todo TODO Finish documentation */ namespace certificateProvider { + /** @enum */ const Hash: { "MD5_SHA1": "MD5_SHA1", "SHA1": "SHA1", @@ -1895,20 +1897,38 @@ declare namespace chrome { "SHA384": "SHA384", "SHA512": "SHA512" }; + /** @enum */ const PinRequestType: { "PIN": "PIN", "PUK": "PUK" }; + /** @enum */ const PinRequestErrorType: { "INVALID_PIN": "INVALID_PIN", "INVALID_PUK": "INVALID_PUK", "MAX_ATTEMPTS_EXCEEDED": "MAX_ATTEMPTS_EXCEEDED", "UNKNOWN_ERROR": "UNKNOWN_ERROR" }; - const requestPin: Function; - const stopPinRequest: Function; - const onCertificatesRequested: chrome.events.Event<(...args: any[]) => any>; - const onSignDigestRequested: chrome.events.Event<(...args: any[]) => any>; + interface RequestOptions { + signRequestId: number; + /** @see PinRequestType */ + requestType?: ToStringLiteral; + /** @see PinRequestErrorType */ + errorType?: ToStringLiteral; + attemptsLeft?: number; + } + interface CodeValue { + userInput?: string; + } + /** @todo TODO Test to find proper types */ + interface SignRequestDigest { + hash?: any; + certificate?: any; + } + function requestPin(opts: RequestOptions, callback: (codeValue: CodeValue) => void): void; + function stopPinRequest(opts: RequestOptions, callback: () => void): void; + const onCertificatesRequested: chrome.events.Event<(param: any) => any>; + const onSignDigestRequested: chrome.events.Event<(signRequest: SignRequestDigest, signCallback: Function) => any>; } /////////////// @@ -2396,6 +2416,29 @@ declare namespace chrome { function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; } + //////////////// + // ENTERPRISE // + //////////////// + /** + * @requires Permissions: 'enterprise.platformKeys' + * @todo TODO Document this? + */ + namespace enterprise.deviceAttributes { + const getDirectoryDeviceId: Function; + const getDeviceSerialNumber: Function; + const getDeviceAssetId: Function; + const getDeviceAnnotatedLocation: Function; + } + /** + * @requires Permissions: 'enterprise.platformKeys' + * @todo TODO Document this? + */ + namespace enterprise.platformKeys { + const getTokens: Function; + const importCertificate: Function; + const removeCertificate: Function; + } + //////////// // Events // //////////// @@ -2701,8 +2744,11 @@ declare namespace chrome { * @todo TODO Documentation */ namespace fileBrowserHandler { + type FileBrowserHandleExecuteId = + 'ReadOnly' | + 'ReadWrite'; const selectFile: Function; - const onExecute: chrome.events.Event; + const onExecute: chrome.events.Event<(id: FileBrowserHandleExecuteId, details: { entries: Entry[] }) => void>; } //////////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 5575406c84..0b8d7f00fe 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -603,6 +603,19 @@ chrome.bluetooth.getDevices((devices) => { }); }); +// CERTIFICATE PROVIDER + +const requestId = 555; +chrome.certificateProvider.requestPin({ signRequestId: requestId }, (codeVal: Object) => { + codeVal +}); + +chrome.certificateProvider.stopPinRequest({ signRequestId: requestId }, () => { + if (chrome.runtime.lastError) { + console.error('Error:', chrome.runtime.lastError); + } +}); + // CONTEXT MENU chrome.contextMenus.onClicked.addListener((info) => { @@ -619,6 +632,26 @@ chrome.contextMenus.onClicked.addListener((info) => { chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); +// ENTERPRISE - DEVICE ATTRIBUTES + +const deviceAttr = chrome.enterprise.deviceAttributes; + +if (deviceAttr.getDirectoryDeviceId && deviceAttr.getDeviceAssetId) { + if (deviceAttr.getDeviceSerialNumber && deviceAttr.getDeviceAnnotatedLocation) { + console.log('API OK :)'); + } +} + +// ENTERPRISE - PLATFORM KEYS + +if (chrome.enterprise.platformKeys.getTokens) { + if (chrome.enterprise.platformKeys.importCertificate) { + if (chrome.enterprise.platformKeys.removeCertificate) { + console.log('API Present'); + } + } +} + // EVENTS const e = new chrome.Event(); // Used const instead of class to be able to return the interface @@ -655,6 +688,23 @@ chrome.hid.getDevices({ }); }); +// File Browser Handle + +chrome.fileBrowserHandler.onExecute.addListener((id, details) => { + /*chrome.fileBrowserHandler.selectFile( + { + suggestedName: 'some_file_name.txt', + allowedFileExtensions: ['txt', 'html'] + }, + (result: any) => { + chrome.test.assertTrue(!!result); + chrome.test.assertTrue(result.success); + chrome.test.assertTrue(!!result.entry); + + ensureFileExists(result.entry, writeToFile, errorCallback); + });*/ +}); + // FILE SYSTEM // https://developer.chrome.com/apps/fileSystem From d860b0497aa40e04a33553e43f1485c8ccfd0943 Mon Sep 17 00:00:00 2001 From: Matthieu Sieben Date: Tue, 14 Aug 2018 17:02:52 +0200 Subject: [PATCH 051/289] Fixed process.emit(Signals) Fixed signature of process's `emit` when used with `Signals` event to match `SignalsListener` 's signature --- types/node/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 7745372a21..2b35343480 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -27,6 +27,7 @@ // Andrew Makarov // Zane Hannan AU // Eugene Y. Q. Shen +// Matthieu Sieben // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -824,7 +825,7 @@ declare namespace NodeJS { emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; emit(event: "warning", warning: Error): boolean; emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals): boolean; + emit(event: Signals, signal: Signals): boolean; emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; From 6288dfa4471512942e5308daa07e4b6dc243691a Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Wed, 15 Aug 2018 14:29:28 +0200 Subject: [PATCH 052/289] Documentation on enterprise namespace --- types/chrome-apps/index.d.ts | 174 +++++++++++++++++++++++++++++++++-- 1 file changed, 164 insertions(+), 10 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 09ab1c530d..0c6fb11887 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2420,23 +2420,177 @@ declare namespace chrome { // ENTERPRISE // //////////////// /** - * @requires Permissions: 'enterprise.platformKeys' - * @todo TODO Document this? + * @requires Permissions: 'enterprise.deviceAttributes' + * @requires Note: This API is only available to apps force-installed by enterprise policy. + * @requires(CrOS) Only available on Chrome OS. + * @since Availability: Since Chrome 46. + * @description + * Use the chrome.enterprise.deviceAttributes API to read device attributes. */ namespace enterprise.deviceAttributes { - const getDirectoryDeviceId: Function; - const getDeviceSerialNumber: Function; - const getDeviceAssetId: Function; - const getDeviceAnnotatedLocation: Function; + /** + * @description + * Fetches the value of the device identifier of the directory API, + * that is generated by the server and identifies the cloud record + * of the device for querying in the cloud directory API. + * If the current user is not affiliated, returns an empty string. + * @param callback Called with the device identifier of the directory API when received. + */ + function getDirectoryDeviceId(callback: (deviceId: string) => void): void; + /** + * @since Since Chrome 66. + * @description + * Fetches the device's serial number. + * Please note the purpose of this API is to administrate the device + * (e.g. generating Certificate Sign Requests for device-wide certificates). + * This API may not be used for tracking devices without the consent of the device's administrator. + * If the current user is not affiliated, returns an empty string. + * @param callback Called with the serial number of the device. + */ + function getDeviceSerialNumber(callback: (serialNumber: string) => void): void; + /** + * @since Since Chrome 66. + * @description + * Fetches the administrator-annotated Asset Id. + * If the current user is not affiliated or no Asset Id has been set by the administrator, returns an empty string. + * @param callback Called with the Asset ID of the device. + */ + function getDeviceAssetId(callback: (assetId: string) => void): void; + /** + * @since Since Chrome 66. + * @description + * Fetches the administrator-annotated Location. + * If the current user is not affiliated or no Annotated Location has been set by the administrator, returns an empty string. + * @param callback Called with the Annotated Location of the device. + */ + function getDeviceAnnotatedLocation(callback: (annotatedLocation: string) => void): void; } /** * @requires Permissions: 'enterprise.platformKeys' - * @todo TODO Document this? + * @requires Note: This API is only available to apps force-installed by enterprise policy. + * @requires(CrOS) Only available on Chrome OS. + * @description + * Use the chrome.enterprise.platformKeys API to generate hardware-backed keys and to install certificates for these keys. + * The certificates will be managed by the platform and can be used for TLS authentication, network access or by other extension through chrome.platformKeys. + * @see[Documentation]{@link https://developer.chrome.com/extensions/enterprise_platformKeys} */ namespace enterprise.platformKeys { - const getTokens: Function; - const importCertificate: Function; - const removeCertificate: Function; + interface Token { + /** + * Uniquely identifies this Token. + * Static IDs are "user" and "system", referring to the platform's user-specific and the system-wide hardware token, respectively. + * Any other tokens (with other identifiers) might be returned by enterprise.platformKeys.getTokens. + */ + id: string; + /** + * Implements the WebCrypto's SubtleCrypto interface. + * The cryptographic operations, including key generation, are hardware-backed. + * Only non-extractable RSASSA-PKCS1-V1_5 keys with modulusLength up to 2048 can be generated. + * Each key can be used for signing data at most once. + * Keys generated on a specific Token cannot be used with any other Tokens, + * nor can they be used with window.crypto.subtle. Equally, + * Key objects created with window.crypto.subtle cannot be used with this interface. + */ + subtleCrypto: SubtleCrypto; + } + /** + * Returns the available Tokens. + * In a regular user's session the list will always contain the user's token with id "user". + * If a system-wide TPM token is available, the returned list will also contain the system-wide token with id "system". + * The system-wide token will be the same for all sessions on this device (device in the sense of e.g. a Chromebook). + * @param callback Invoked by getTokens with the list of available Tokens. + */ + function getTokens(callback: (tokens: Token[]) => void): void; + /** + * Returns the list of all client certificates available from the given token. + * Can be used to check for the existence and expiration of client certificates that are usable for a certain authentication. + * @param tokenId The id of a Token returned by getTokens. + * @param callback Called back with the list of the available certificates. + */ + function getCertificates(tokenId: string, callback: (certificates: ArrayBuffer[]) => void): void; + /** + * Imports certificate to the given token if the certified key is already stored in this token. + * After a successful certification request, this function should be used to store the obtained + * certificate and to make it available to the operating system and browser for authentication. + * @param tokenId The id of a Token returned by getTokens. + * @param certificate The DER encoding of a X.509 certificate. + * @param [callback] Called back when this operation is finished. + */ + function importCertificate(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; + /** + * Removes certificate from the given token if present. + * Should be used to remove obsolete certificates so that they are not + * considered during authentication and do not clutter the certificate choice. + * Should be used to free storage in the certificate store. + * @param tokenId The id of a Token returned by getTokens. + * @param certificate The DER encoding of a X.509 certificate. + * @param [callback] Called back when this operation is finished. + */ + function removeCertificae(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; + /** + * @since Since Chrome 50. + * @description + * Challenges a hardware-backed Enterprise Machine Key and emits the response as part of a remote attestation protocol. + * Only useful on Chrome OS and in conjunction with the Verified Access Web API which both issues challenges and verifies responses. + * A successful verification by the Verified Access Web API is a strong signal of all of the following: + * - The current device is a legitimate Chrome OS device. + * - The current device is managed by the domain specified during verification. + * - The current signed-in user is managed by the domain specified during verification. + * - The current device state complies with enterprise device policy. + * For example, a policy may specify that the device must not be in developer mode. + * - Any device identity emitted by the verification is tightly bound to the hardware of the current device. + * This function is highly restricted and will fail if the current device is not managed, + * the current user is not managed, or if this operation has not explicitly been enabled + * for the caller by enterprise device policy. The Enterprise Machine Key does not reside + * in the "system" token and is not accessible by any other API. + * @param challenge A challenge as emitted by the Verified Access Web API. + * @param callback Called back with the challenge response. + */ + function challengeMachineKey(challenge: ArrayBuffer, callback: (response: ArrayBuffer) => void): void; + /** + * @since **Since Chrome 59.** - Note: the parameter 'registerKey' requires at least Chrome 59 + * @description + * Challenges a hardware-backed Enterprise Machine Key and emits the response as part of a remote attestation protocol. + * Only useful on Chrome OS and in conjunction with the Verified Access Web API which both issues challenges and verifies responses. + * A successful verification by the Verified Access Web API is a strong signal of all of the following: + * - The current device is a legitimate Chrome OS device. + * - The current device is managed by the domain specified during verification. + * - The current signed-in user is managed by the domain specified during verification. + * - The current device state complies with enterprise device policy. + * For example, a policy may specify that the device must not be in developer mode. + * - Any device identity emitted by the verification is tightly bound to the hardware of the current device. + * This function is highly restricted and will fail if the current device is not managed, + * the current user is not managed, or if this operation has not explicitly been enabled + * for the caller by enterprise device policy. The Enterprise Machine Key does not reside + * in the "system" token and is not accessible by any other API. + * @param challenge A challenge as emitted by the Verified Access Web API. + * @param registerKey If set, the current Enterprise Machine Key is registered with the "system" token and relinquishes the Enterprise Machine Key role. + * The key can then be associated with a certificate and used like any other signing key. This key is 2048-bit RSA. + * Subsequent calls to this function will then generate a new Enterprise Machine Key. + * @param callback Called back with the challenge response. + */ + function challengeMachineKey(challenge: ArrayBuffer, registerKey: boolean, callback: (response: ArrayBuffer) => void): void; + /** + * @since Since Chrome 50. + * Challenges a hardware-backed Enterprise User Key and emits the response as part of a remote attestation protocol. + * Only useful on Chrome OS and in conjunction with the Verified Access Web API which both issues challenges and verifies responses. + * A successful verification by the Verified Access Web API is a strong signal of all of the following: + * - The current device is a legitimate Chrome OS device. + * - The current device is managed by the domain specified during verification. + * - The current signed-in user is managed by the domain specified during verification. + * - The current device state complies with enterprise user policy. + * For example, a policy may specify that the device must not be in developer mode. + * - The public key emitted by the verification is tightly bound to the hardware of the current device and to the current signed-in user. + * This function is highly restricted and will fail if the current device is not managed, the current user is not managed, + * or if this operation has not explicitly been enabled for the caller by enterprise user policy. + * The Enterprise User Key does not reside in the "user" token and is not accessible by any other API. + * @param challenge A challenge as emitted by the Verified Access Web API. + * @param registerKey If set, the current Enterprise User Key is registered with the "user" token and relinquishes the Enterprise User Key role. + * The key can then be associated with a certificate and used like any other signing key. + * This key is 2048-bit RSA. Subsequent calls to this function will then generate a new Enterprise User Key. + * @param callback Called back with the challenge response. + */ + function challengeUserKey(challenge: ArrayBuffer, registerKey: boolean, callback: (response: ArrayBuffer) => void): void; } //////////// From d16065adda6c77159e7f3eff292d7cdea5aa3ff7 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Wed, 15 Aug 2018 14:30:35 +0200 Subject: [PATCH 053/289] Fixed typo --- types/chrome-apps/index.d.ts | 2 +- types/chrome-apps/test/index.ts | 12 ++++-------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 0c6fb11887..de65333fa6 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2526,7 +2526,7 @@ declare namespace chrome { * @param certificate The DER encoding of a X.509 certificate. * @param [callback] Called back when this operation is finished. */ - function removeCertificae(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; + function removeCertificate(tokenId: string, certificate: ArrayBuffer, callback: () => void): void; /** * @since Since Chrome 50. * @description diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 0b8d7f00fe..19401a5ccf 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -691,18 +691,14 @@ chrome.hid.getDevices({ // File Browser Handle chrome.fileBrowserHandler.onExecute.addListener((id, details) => { - /*chrome.fileBrowserHandler.selectFile( + chrome.fileBrowserHandler.selectFile( { suggestedName: 'some_file_name.txt', allowedFileExtensions: ['txt', 'html'] }, - (result: any) => { - chrome.test.assertTrue(!!result); - chrome.test.assertTrue(result.success); - chrome.test.assertTrue(!!result.entry); - - ensureFileExists(result.entry, writeToFile, errorCallback); - });*/ + (result) => { + console.log(result.entry); + }); }); // FILE SYSTEM From 79324ed04aa499e7cbbbbe57f44dde76d72a9061 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Wed, 15 Aug 2018 15:49:18 +0200 Subject: [PATCH 054/289] Better docs --- types/chrome-apps/index.d.ts | 681 ++++++++++++++++++++++---------- types/chrome-apps/test/index.ts | 44 +++ 2 files changed, 519 insertions(+), 206 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index de65333fa6..321d5655c5 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1891,23 +1891,23 @@ declare namespace chrome { namespace certificateProvider { /** @enum */ const Hash: { - "MD5_SHA1": "MD5_SHA1", - "SHA1": "SHA1", - "SHA256": "SHA256", - "SHA384": "SHA384", - "SHA512": "SHA512" + 'MD5_SHA1': 'MD5_SHA1', + 'SHA1': 'SHA1', + 'SHA256': 'SHA256', + 'SHA384': 'SHA384', + 'SHA512': 'SHA512' }; /** @enum */ const PinRequestType: { - "PIN": "PIN", - "PUK": "PUK" + 'PIN': 'PIN', + 'PUK': 'PUK' }; /** @enum */ const PinRequestErrorType: { - "INVALID_PIN": "INVALID_PIN", - "INVALID_PUK": "INVALID_PUK", - "MAX_ATTEMPTS_EXCEEDED": "MAX_ATTEMPTS_EXCEEDED", - "UNKNOWN_ERROR": "UNKNOWN_ERROR" + 'INVALID_PIN': 'INVALID_PIN', + 'INVALID_PUK': 'INVALID_PUK', + 'MAX_ATTEMPTS_EXCEEDED': 'MAX_ATTEMPTS_EXCEEDED', + 'UNKNOWN_ERROR': 'UNKNOWN_ERROR' }; interface RequestOptions { signRequestId: number; @@ -2051,27 +2051,27 @@ declare namespace chrome { * Different platforms might put limitations on what is actually supported in a launcher context menu. **/ const ContextType: { - "ALL": "all", - "PAGE": "page", - "FRAME": "frame", - "SELECTION": "selection", - "LINK": "link", - "EDITABLE": "editable", - "IMAGE": "image", - "VIDEO": "video", - "AUDIO": "audio", - "LAUNCHER": "launcher", - "BROWSER_ACTION": "browser_action", - "PAGE_ACTION": "page_action" + 'ALL': 'all', + 'PAGE': 'page', + 'FRAME': 'frame', + 'SELECTION': 'selection', + 'LINK': 'link', + 'EDITABLE': 'editable', + 'IMAGE': 'image', + 'VIDEO': 'video', + 'AUDIO': 'audio', + 'LAUNCHER': 'launcher', + 'BROWSER_ACTION': 'browser_action', + 'PAGE_ACTION': 'page_action' }; /** * The type of menu item. **/ const ItemType: { - "NORMAL": "normal", - "CHECKBOX": "checkbox", - "RADIO": "radio", - "SEPARATOR": "separator" + 'NORMAL': 'normal', + 'CHECKBOX': 'checkbox', + 'RADIO': 'radio', + 'SEPARATOR': 'separator' }; type MediaType = @@ -2295,18 +2295,6 @@ declare namespace chrome { } - ///////////////// - // Diagnostics // - ///////////////// - /** - * @requires(CrOS) Only Chrome OS. Crashes app on Windows. - * @requires Permissions: 'diagnostics' - */ - namespace diagnostics { - /** @todo TODO PROPER DOCS */ - function sendPacket(options: Object, callback: () => void): void; - } - ///////////////////// // Desktop Capture // ///////////////////// @@ -2340,32 +2328,119 @@ declare namespace chrome { function cancelChooseDesktopMedia(desktopMediaRequestId: integer): void; } + ///////////////// + // Diagnostics // + ///////////////// + /** + * @requires(CrOS) Only Chrome OS. Crashes app on Windows. + * @requires Permissions: 'diagnostics' + */ + namespace diagnostics { + /** @todo TODO PROPER DOCS */ + function sendPacket(options: Object, callback: () => void): void; + } + //////////////////// // Display Source // //////////////////// /** * @requires(dev) Development versions only * @requires Permissions: 'displaySource' - * Display Source API - * @todo TODO Documentation + * The *chrome.displaySource* API creates a Display session using WebMediaStreamTrack as sources. */ namespace displaySource { + /** + * @enum + * @description + * **'connection_error'** + * The connection with sink cannot be established or has dropped unexpectedly. + * + * **'capabilities_negotiation_error'** + * The capabilities of this Display Source and the connected + * sink do not fit (e.g. the sink cannot play the media content of + * the formats given by the source). + * + * **'media_pipeline_error'** + * There was an error in media pipeline: while encoding, packetizing or + * sending the media content. + * + * **'timeout_error'** + * The sink became unresponsive. + * + * **'unknown_error'** + * Unspecified error. + */ const ErrorType: { - "CONNECTION_ERROR": "connection_error", - "CAPABILITIES_NEGOTIATION_ERROR": "capabilities_negotiation_error", - "MEDIA_PIPELINE_ERROR": "media_pipeline_error", - "TIMEOUT_ERROR": "timeout_error", - "UNKNOWN_ERROR": "unknown_error" + CONNECTION_ERROR: 'connection_error', + CAPABILITIES_NEGOTIATION_ERROR: 'capabilities_negotiation_error', + MEDIA_PIPELINE_ERROR: 'media_pipeline_error', + TIMEOUT_ERROR: 'timeout_error', + UNKNOWN_ERROR: 'unknown_error' }; + /** + * @enum + * @description + * **'connected'** + * Connected using this Display Source (i.e., there is an active session) + * + * **'connecting'** + * In process of connection to this Display Source + * + * **'disconnected'** + * Disconnected from this Display Source + */ const SinkState: { - "CONNECTED": "Connected", - "CONNECTING": "Connecting", - "DISCONNECTED": "Disconnected" + CONNECTED: 'Connected', + CONNECTING: 'Connecting', + DISCONNECTED: 'Disconnected' }; + /** + * @enum + * @description + * + * **'PBC'** + * Push Button Config authentication method. + * + * **'PIN'** + * PIN authentication method. + */ const AuthenticationMethod: { - "PBC": "PBC", - "PIN": "PIN" + PBC: 'PBC', + PIN: 'PIN' }; + interface ErrorInfo { + /** @see ErrorType */ + type: ToStringLiteral; + description?: string; + } + interface SinkInfo { + /** Id of the sink. It is guaranteed to be unique during the browser session. */ + id: integer; + /** Human readable name of the sink. */ + name: string; + /** + * State of the sink. + * @see SinkState + */ + state: ToStringLiteral; + } + interface AuthenticationInfo { + /** + * Authentication method. + * @see AuthenticationMethod + */ + method?: ToStringLiteral; + /** + * Authentication data (e.g. PIN value). + */ + data?: string; + } + interface StartSessionInfo { + sinkId: integer; + authenticationInfo?: AuthenticationInfo; + audioTrack?: object; + videoTrack?: object; + } const getAvailableSinks: Function; const requestAuthentication: Function; const startSession: Function; @@ -2375,6 +2450,34 @@ declare namespace chrome { const onSessionErrorOccured: chrome.events.Event; } + ///////// + // DNS // + ///////// + /** + * @requires(CrOS) Only Chrome OS. Crashes app on Windows. + * @requires Permissions: 'diagnostics' + * @description + * Use the *chrome.dns* API for dns resolution. + */ + namespace dns { + interface ResolveCallbackResolveInfo { + /** The result code. Zero indicates success. */ + resultCode: integer; + /** + * A string representing the IP address literal. + * Supplied only if resultCode indicates success. + * Note that we presently return only IPv4 addresses. + */ + address?: string; + } + /** + * Resolves the given hostname or IP address literal. + * @param hostname The hostname to resolve. + * @param callback Called when the resolution operation completes. + */ + function resolve(hostname: string, callback: (resolveInfo: ResolveCallbackResolveInfo) => void): void; + } + /////////////////// // Document Scan // /////////////////// @@ -2478,7 +2581,7 @@ declare namespace chrome { interface Token { /** * Uniquely identifies this Token. - * Static IDs are "user" and "system", referring to the platform's user-specific and the system-wide hardware token, respectively. + * Static IDs are 'user' and 'system', referring to the platform's user-specific and the system-wide hardware token, respectively. * Any other tokens (with other identifiers) might be returned by enterprise.platformKeys.getTokens. */ id: string; @@ -2495,8 +2598,8 @@ declare namespace chrome { } /** * Returns the available Tokens. - * In a regular user's session the list will always contain the user's token with id "user". - * If a system-wide TPM token is available, the returned list will also contain the system-wide token with id "system". + * In a regular user's session the list will always contain the user's token with id 'user'. + * If a system-wide TPM token is available, the returned list will also contain the system-wide token with id 'system'. * The system-wide token will be the same for all sessions on this device (device in the sense of e.g. a Chromebook). * @param callback Invoked by getTokens with the list of available Tokens. */ @@ -2542,7 +2645,7 @@ declare namespace chrome { * This function is highly restricted and will fail if the current device is not managed, * the current user is not managed, or if this operation has not explicitly been enabled * for the caller by enterprise device policy. The Enterprise Machine Key does not reside - * in the "system" token and is not accessible by any other API. + * in the 'system' token and is not accessible by any other API. * @param challenge A challenge as emitted by the Verified Access Web API. * @param callback Called back with the challenge response. */ @@ -2562,9 +2665,9 @@ declare namespace chrome { * This function is highly restricted and will fail if the current device is not managed, * the current user is not managed, or if this operation has not explicitly been enabled * for the caller by enterprise device policy. The Enterprise Machine Key does not reside - * in the "system" token and is not accessible by any other API. + * in the 'system' token and is not accessible by any other API. * @param challenge A challenge as emitted by the Verified Access Web API. - * @param registerKey If set, the current Enterprise Machine Key is registered with the "system" token and relinquishes the Enterprise Machine Key role. + * @param registerKey If set, the current Enterprise Machine Key is registered with the 'system' token and relinquishes the Enterprise Machine Key role. * The key can then be associated with a certificate and used like any other signing key. This key is 2048-bit RSA. * Subsequent calls to this function will then generate a new Enterprise Machine Key. * @param callback Called back with the challenge response. @@ -2583,9 +2686,9 @@ declare namespace chrome { * - The public key emitted by the verification is tightly bound to the hardware of the current device and to the current signed-in user. * This function is highly restricted and will fail if the current device is not managed, the current user is not managed, * or if this operation has not explicitly been enabled for the caller by enterprise user policy. - * The Enterprise User Key does not reside in the "user" token and is not accessible by any other API. + * The Enterprise User Key does not reside in the 'user' token and is not accessible by any other API. * @param challenge A challenge as emitted by the Verified Access Web API. - * @param registerKey If set, the current Enterprise User Key is registered with the "user" token and relinquishes the Enterprise User Key role. + * @param registerKey If set, the current Enterprise User Key is registered with the 'user' token and relinquishes the Enterprise User Key role. * The key can then be associated with a certificate and used like any other signing key. * This key is 2048-bit RSA. Subsequent calls to this function will then generate a new Enterprise User Key. * @param callback Called back with the challenge response. @@ -2894,8 +2997,12 @@ declare namespace chrome { ///////////////////////// /** * @requires(CrOS) Chrome OS Only - * @requires Permissions: 'fileBrowserHandle' - * @todo TODO Documentation + * @requires Permissions: 'fileBrowserHandler' + * @requires Manifest: 'file_browser_handlers' + * @description + * Use the chrome.fileBrowserHandler API to extend the Chrome OS file browser. + * For example, you can use this API to enable users to upload files to your website. + * @see[Documentation]{@linkhttps://developer.chrome.com/extensions/fileBrowserHandler} */ namespace fileBrowserHandler { type FileBrowserHandleExecuteId = @@ -2922,9 +3029,9 @@ declare namespace chrome { namespace fileSystem { /** @enum */ const ChildChangeType: { - CREATED: "created", - REMOVED: "removed", - CHANGED: "changed" + CREATED: 'created', + REMOVED: 'removed', + CHANGED: 'changed' }; /** * **openFile** @@ -2948,10 +3055,10 @@ declare namespace chrome { * @enum */ const ChooseEntryType: { - OPEN_FILE: "openFile", - OPEN_WRITABLE_FILE: "openWritableFile", - SAVE_FILE: "saveFile", - OPEN_DIRECTORY: "openDirectory" + OPEN_FILE: 'openFile', + OPEN_WRITABLE_FILE: 'openWritableFile', + SAVE_FILE: 'saveFile', + OPEN_DIRECTORY: 'openDirectory' }; interface AcceptOptions { /** @@ -3119,33 +3226,33 @@ declare namespace chrome { * For success, 'OK' must be used. * */ const ProviderError: { - "OK": "OK", - "FAILED": "FAILED", - "IN_USE": "IN_USE", - "EXISTS": "EXISTS", - "NOT_FOUND": "NOT_FOUND", - "ACCESS_DENIED": "ACCESS_DENIED", - "TOO_MANY_OPENED": "TOO_MANY_OPENED", - "NO_MEMORY": "NO_MEMORY", - "NO_SPACE": "NO_SPACE", - "NOT_A_DIRECTORY": "NOT_A_DIRECTORY", - "INVALID_OPERATION": "INVALID_OPERATION", - "SECURITY": "SECURITY", - "ABORT": "ABORT", - "NOT_A_FILE": "NOT_A_FILE", - "NOT_EMPTY": "NOT_EMPTY", - "INVALID_URL": "INVALID_URL", - "IO": "IO" + 'OK': 'OK', + 'FAILED': 'FAILED', + 'IN_USE': 'IN_USE', + 'EXISTS': 'EXISTS', + 'NOT_FOUND': 'NOT_FOUND', + 'ACCESS_DENIED': 'ACCESS_DENIED', + 'TOO_MANY_OPENED': 'TOO_MANY_OPENED', + 'NO_MEMORY': 'NO_MEMORY', + 'NO_SPACE': 'NO_SPACE', + 'NOT_A_DIRECTORY': 'NOT_A_DIRECTORY', + 'INVALID_OPERATION': 'INVALID_OPERATION', + 'SECURITY': 'SECURITY', + 'ABORT': 'ABORT', + 'NOT_A_FILE': 'NOT_A_FILE', + 'NOT_EMPTY': 'NOT_EMPTY', + 'INVALID_URL': 'INVALID_URL', + 'IO': 'IO' }; /** Mode of opening a file. Used by onOpenFileRequested. */ const OpenFileMode: { - "READ": "READ", - "WRITE": "WRITE" + 'READ': 'READ', + 'WRITE': 'WRITE' }; /** Type of a change detected on the observed directory. */ const ChangeType: { - "CHANGED": "CHANGED", - "DELETED": "DELETED" + 'CHANGED': 'CHANGED', + 'DELETED': 'DELETED' }; /** * List of common actions. 'SHARE' is for sharing files with others. @@ -3155,9 +3262,9 @@ declare namespace chrome { * Used by onGetActionsRequested and onExecuteActionRequested. */ const CommonActionId: { - "SAVE_FOR_OFFLINE": "SAVE_FOR_OFFLINE", - "OFFLINE_NOT_NECESSARY": "OFFLINE_NOT_NECESSARY", - "SHARE": "SHARE" + 'SAVE_FOR_OFFLINE': 'SAVE_FOR_OFFLINE', + 'OFFLINE_NOT_NECESSARY': 'OFFLINE_NOT_NECESSARY', + 'SHARE': 'SHARE' }; interface EntryMetadata { @@ -4708,28 +4815,28 @@ declare namespace chrome { */ namespace management { const ExtensionDisabledReason: { - UNKNOWN: "unknown", - PERMISSIONS_INCREASE: "permissions_increase" + UNKNOWN: 'unknown', + PERMISSIONS_INCREASE: 'permissions_increase' }; const ExtensionInstallType: { - ADMIN: "admin", - DEVELOPMENT: "development", - NORMAL: "normal", - SIDELOAD: "sideload", - OTHER: "other" + ADMIN: 'admin', + DEVELOPMENT: 'development', + NORMAL: 'normal', + SIDELOAD: 'sideload', + OTHER: 'other' }; const ExtensionType: { - EXTENSION: "extension", - HOSTED_APP: "hosted_app", - PACKAGED_APP: "packaged_app", - LEGACY_PACKAGED_APP: "legacy_packaged_app", - THEME: "theme" + EXTENSION: 'extension', + HOSTED_APP: 'hosted_app', + PACKAGED_APP: 'packaged_app', + LEGACY_PACKAGED_APP: 'legacy_packaged_app', + THEME: 'theme' }; const LaunchType: { - OPEN_AS_REGULAR_TAB: "OPEN_AS_REGULAR_TAB", - OPEN_AS_PINNED_TAB: "OPEN_AS_PINNED_TAB", - OPEN_AS_WINDOW: "OPEN_AS_WINDOW", - OPEN_FULL_SCREEN: "OPEN_FULL_SCREEN" + OPEN_AS_REGULAR_TAB: 'OPEN_AS_REGULAR_TAB', + OPEN_AS_PINNED_TAB: 'OPEN_AS_PINNED_TAB', + OPEN_AS_WINDOW: 'OPEN_AS_WINDOW', + OPEN_FULL_SCREEN: 'OPEN_FULL_SCREEN' }; /** Information about an installed extension, app, or theme. */ interface ExtensionInfo { @@ -5163,25 +5270,90 @@ declare namespace chrome { const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } - namespace networking { + /////////////////////// + // NETWORKING CONFIG // + /////////////////////// + /** + * + */ + namespace networking.config { + /** Indicator for the type of network used */ const NetworkType: { 'WI_FI': 'WiFi' }; + /** + * Argument to finishAuthentication indicating the result of the captive portal authentication attempt. + * **'unhandled':** - The extension does not handle this network or captive portal (e.g. server end-point not found or not compatible). + * **'succeeded':** - The extension handled this network and authenticated successfully. + * **'rejected':** - The extension handled this network, tried to authenticate, however was rejected by the server. + * **'failed':** - The extension handled this network, tried to authenticate, however failed due to an unspecified error. + */ const AuthenticationResult: { UNHANDLED: 'unhandled', SUCCEEDED: 'succeeded', REJECTED: 'rejected', FAILED: 'failed' } - /** @todo TODO DOCUMENT THESE */ - const setNetworkFilter: Function; - const finishAuthentication: Function; - const onCaptivePortalDetected: any; + interface NetworkInfo { + /** Currently only WiFi supported. */ + Type: ToStringLiteral; + /** A unique identifier of the network. */ + GUID?: string; + /** + * A hex-encoded byte sequence. + */ + HexSSID?: string; + /** + * The decoded SSID of the network (default encoding is UTF-8). + * To filter for non-UTF-8 SSIDs, use HexSSID instead. + */ + SSID?: string; + /** + * The basic service set identification (BSSID) uniquely identifying the + * basic service set. BSSID is represented as a human readable, + * hex-encoded string with bytes separated by colons, e.g. + * 45:67:89:ab:cd:ef. + */ + BSSID?: string; + /** Identifier indicating the security type of the network. */ + Security?: 'None' | 'WEP-PSK' | 'WPA-PSK' | 'WPA-EAP'; + } + interface NetworkInfoFilterHexSSID { + /** + * A hex-encoded byte sequence. + */ + HexSSID?: string; + } + interface NetworkInfoFilterSSID { + /** + * The decoded SSID of the network (default encoding is UTF-8). + * To filter for non-UTF-8 SSIDs, use HexSSID instead. + */ + SSID?: string; + } + /** + * Allows an extension to define network filters for the networks it can handle. + * A call to this function will remove all filters previously + * installed by the extension before setting the new list. + * @param networks Network filters to set. Array of objects with either HexSSID or SSID set. + * @param callback Called back when this operation is finished. + */ + function setNetworkFilter(networks: Array, callback: () => void): void; + /** + * Called by the extension to notify the network config API that it finished + * a captive portal authentication attempt and hand over the result of the attempt. + * This function must only be called with the GUID of the latest *onCaptivePortalDetected* event. + * @param GUID Unique network identifier obtained from *onCaptivePortalDetected*. + * @param result The result of the authentication attempt. + * @param [callback] Called back when this operation is finished. + */ + function finishAuthentication(GUID: string, result: ToStringLiteral, callback?: () => void): void; + const onCaptivePortalDetected: chrome.events.Event<(networkInfo: NetworkInfo) => void>; } - //////////////////////////////////// - // Open Network Configuration (ONC) - //////////////////////////////////// + ////////////////////////////////////// + // Open Network Configuration (ONC) // + ////////////////////////////////////// /** * @requires(CrOS kiosk mode) This API is available in Chrome OS kiosk sessions. * @requires Permissions: 'networking.onc' @@ -5845,10 +6017,10 @@ declare namespace chrome { * @prop PROGRESS - icon, title, message, progress, up to two buttons. */ const TemplateType: { - BASIC: "basic", - IMAGE: "image", - LIST: "list", - PROGRESS: "progress" + BASIC: 'basic', + IMAGE: 'image', + LIST: 'list', + PROGRESS: 'progress' } /** * @enum @@ -5856,8 +6028,8 @@ declare namespace chrome { * @property DENIED - User has elected not to show notifications from the app. */ const PermissionLevel: { - GRANTED: "granted", - DENIED: "denied" + GRANTED: 'granted', + DENIED: 'denied' } interface ButtonOptions { @@ -6093,8 +6265,8 @@ declare namespace chrome { */ namespace platformKeys { const ClientCertificateType: { - "RSA_SIGN": "rsaSign", - "ECDSA_SIGN": "ecdsaSign" + 'RSA_SIGN': 'rsaSign', + 'ECDSA_SIGN': 'ecdsaSign' }; const selectClientCertificates: Function; const getKeyPair: Function; @@ -6383,12 +6555,12 @@ declare namespace chrome { | 'https://*/*' | 'file:///*/*' /** - * Required if the extension uses the "chrome://favicon/**url**" mechanism to display the favicon of a page. - * For example, to display the favicon of http://www.google.com/, you declare the "chrome://favicon/" + * Required if the extension uses the 'chrome://favicon/**url**' mechanism to display the favicon of a page. + * For example, to display the favicon of http://www.google.com/, you declare the 'chrome://favicon/' * permission and use HTML code like this: * @example *
-             * 
+             * 
              * 
*/ | 'chrome://favicon/' @@ -6402,36 +6574,30 @@ declare namespace chrome { 'certificateProvider' | /** Gives your app access to the chrome.clipboard API. */ 'clipboard' | - /** - * Gives your app access to the chrome.dns API. - * @todo TODO Implement API. - */ + /** Gives your app access to the chrome.dns API. */ 'dns' | /** Gives your app access to the chrome.documentScan API. */ 'documentScan' | /** * Gives your app access to the chrome.enterprise.platformKeys API. - * @todo TODO Implement API. */ 'enterprise.platformKeys' | /** * Gives your app access to the chrome.enterprise.deviceAttributes API. - * @todo TODO Implement API. */ 'enterprise.deviceAttributes' | /** * Gives your app access to the chrome.fileBrowserHandler API. - * @todo TODO Implement API. */ 'fileBrowserHandler' | /** * Gives your app access to the chrome.fileSystemProvider API. - * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. + * Use the chrome.fileSystemProvider API to create file systems, + * that can be accessible from the file manager on Chrome OS. */ 'fileSystemProvider' | /** * Gives your app access to the chrome.networking.config API. - * @todo TODO Implement API. */ 'networking.config' | /** @@ -6512,8 +6678,8 @@ declare namespace chrome { 'audioCapture' | /** * Makes Chrome start up early and and shut down late, so that apps can have a longer life. - * When any installed app has "background" permission, Chrome runs (invisibly) as soon as the user logs - * into their computer—before the user launches Chrome. The "background" permission also makes Chrome + * When any installed app has 'background' permission, Chrome runs (invisibly) as soon as the user logs + * into their computer—before the user launches Chrome. The 'background' permission also makes Chrome * continue running (even after its last window is closed) until the user explicitly quits Chrome. * Note: Disabled apps are treated as if they aren't installed. */ @@ -6886,7 +7052,7 @@ declare namespace chrome { automation?: AutomationOptions | boolean; /** - * Note: The "bluetooth" manifest permission is used by the + * Note: The 'bluetooth' manifest permission is used by the * chrome.bluetooth, chrome.bluetoothSocket and * chrome.bluetoothLowEnergy APIs. * @requires Platforms: Chrome OS, Windows and Mac @@ -6907,9 +7073,9 @@ declare namespace chrome { * Keys can be provided matching this pattern: * ^(Ctrl|Command|MacCtrl|Alt|Option)\\+(Shift\\+)?[A-Z] * @example - * "suggested_key": { - * "default": "Ctrl+Shift+Y", - * "mac": "Command+Shift+Y" + * 'suggested_key': { + * 'default': 'Ctrl+Shift+Y', + * 'mac': 'Command+Shift+Y' * }, */ suggested_key?: { @@ -6982,6 +7148,26 @@ declare namespace chrome { accept_tls_channel_id?: boolean, } + /** + * @requires Permissions: 'fileBrowserHandle' + * @requires Location': 'component' + * You can specify locale-specific strings for the value of 'default_title' + */ + file_browser_handlers?: { + /** Handler id */ + id: string, + /** What the button will display */ + default_title: string, + /** Icon */ + default_icon: string, + /** + * To match all files, use 'filesystem:*.*' + */ + file_filters: string[], + /** ['read'] = read only mode */ + file_access?: ['read'] | string[] + }[]; + /** * Triggers a launch of the app when one of these files are handled. */ @@ -7143,7 +7329,7 @@ declare namespace chrome { sandbox?: { pages: string[]; /** - * @default "sandbox allow-scripts allow-forms" + * @default 'sandbox allow-scripts allow-forms' */ content_security_policy?: string; }; @@ -8331,11 +8517,11 @@ declare namespace chrome { * - 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.) */ const ServiceStatus: { - "INITIALIZING": "initializing", - "RUNNING": "running", - "AUTHENTICATION_REQUIRED": "authentication_required", - "TEMPORARY_UNAVAILABLE": "temporary_unavailable", - "DISABLED": "disabled" + 'INITIALIZING': 'initializing', + 'RUNNING': 'running', + 'AUTHENTICATION_REQUIRED': 'authentication_required', + 'TEMPORARY_UNAVAILABLE': 'temporary_unavailable', + 'DISABLED': 'disabled' }; /** @@ -8348,25 +8534,25 @@ declare namespace chrome { * - File conflicts with remote version and must be resolved manually. */ const FileStatus: { - "SYNCED": "synced", - "PENDING": "pending", - "CONFLICTING": "conflicting" + 'SYNCED': 'synced', + 'PENDING': 'pending', + 'CONFLICTING': 'conflicting' } const ConflictResolutionPolicy: { - "LAST_WRITE_WIN": "last_write_win", - "MANUAL": "manual" + 'LAST_WRITE_WIN': 'last_write_win', + 'MANUAL': 'manual' }; const SyncAction: { - "ADDED": "added", - "UPDATED": "updated", - "DELETED": "deleted" + 'ADDED': 'added', + 'UPDATED': 'updated', + 'DELETED': 'deleted' } const SyncDirection: { - "LOCAL_TO_REMOTE": "local_to_remote", - "REMOTE_TO_LOCAL": "remote_to_local" + 'LOCAL_TO_REMOTE': 'local_to_remote', + 'REMOTE_TO_LOCAL': 'remote_to_local' }; interface FileStatusInfo { @@ -8944,14 +9130,56 @@ declare namespace chrome { // System Power Source // ///////////////////////// /** - * The chrome.system.powerSource API. + * @requires(CrOS Kiosk) Chrome OS kiosk app. * @requires Permissions: 'system.powerSource' + * @description The chrome.system.powerSource API allows Chrome Kiosk Apps to query the state of connected power sources. * @since Latest */ namespace system.powerSource { - /** @todo TODO Document this */ - function getPowerSourceInfo(arg?: any | any[]): any; - function requestStatusUpdate(arg?: any | any[]): any; + enum PowerSourceType { + /** Unspecified type. */ + unknown = 'unknown', + + /** + * Dedicated charger. Typically single-purpose and non-USB + * (e.g. barrel jack plugs) + */ + mains = 'mains', + + /** + * USB charger, including both low-power Type-A chargers and high-power + * Type-C chargers using USB Power Delivery. + */ + usb = 'usb' + } + interface PowerSourceInfo { + /** + * Type of power source + * @see PowerSourceType + */ + type: keyof typeof PowerSourceType | PowerSourceType; + /** + * Maximum power this source is capable of delivering if known. + * Reported in watts, rounded to two significant digits. + */ + maxPower?: double; + /** Whether this power source is connected to the device. */ + active: boolean; + } + /** + * Requests information on attached power sources. + * @param callback The callback to invoke with the results or undefined if the power source information is not known. + */ + function getPowerSourceInfo(callback: (powerSourceInfo?: PowerSourceInfo[]) => void): void; + /** + * Requests a power source status update. + * Resulting power source status updates are observable using *onPowerChanged*. + */ + function requestStatusUpdate(): void; + /** + * Event for changes in the set of connected power sources. + */ + const onPowerChanged: chrome.events.Event<(powerSourceInfo: PowerSourceInfo[]) => void>; } //////////////////// @@ -8964,15 +9192,15 @@ declare namespace chrome { */ namespace system.storage { const StorageUnitType: { - FIXED: "fixed", - REMOVABLE: "removable", - UNKNOWN: "unknown" + FIXED: 'fixed', + REMOVABLE: 'removable', + UNKNOWN: 'unknown' }; const EjectDeviceResultCode: { - SUCCESS: "success", - IN_USE: "in_use", - NO_SUCH_DEVICE: "no_such_device", - FAILURE: "failure" + SUCCESS: 'success', + IN_USE: 'in_use', + NO_SUCH_DEVICE: 'no_such_device', + FAILURE: 'failure' }; interface StorageUnitInfo { /** @@ -9255,41 +9483,41 @@ declare namespace chrome { namespace usb { /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ const Direction: { - "IN": "in", - "OUT": "out" + 'IN': 'in', + 'OUT': 'out' }; /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ const Recipient: { - "DEVICE": "device", - "INTERFACE": "interface", - "ENDPOINT": "endpoint", - "OTHER": "other" + 'DEVICE': 'device', + 'INTERFACE': 'interface', + 'ENDPOINT': 'endpoint', + 'OTHER': 'other' }; /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ const RequestType: { - "STANDARD": "standard", - "CLASS": "class", - "VENDOR": "vendor", - "RESERVED": "reserved" + 'STANDARD': 'standard', + 'CLASS': 'class', + 'VENDOR': 'vendor', + 'RESERVED': 'reserved' }; /** Direction, Recipient, RequestType, and TransferType all map to their namesakes within the USB specification. */ const TransferType: { - "CONTROL": "control", - "INTERRUPT": "interrupt", - "ISOCHRONOUS": "isochronous", - "BULK": "bulk" + 'CONTROL': 'control', + 'INTERRUPT': 'interrupt', + 'ISOCHRONOUS': 'isochronous', + 'BULK': 'bulk' }; const SynchronizationType: { - "ASYNCHRONOUS": "asynchronous", - "ADAPTIVE": "adaptive", - "SYNCHRONOUS": "synchronous" + 'ASYNCHRONOUS': 'asynchronous', + 'ADAPTIVE': 'adaptive', + 'SYNCHRONOUS': 'synchronous' }; const UsageType: { - "DATA": "data", - "FEEDBACK": "feedback", - "EXPLICIT_FEEDBACK": "explicitFeedback", - "PERIODIC": "periodic", - "NOTIFICATION": "notification" + 'DATA': 'data', + 'FEEDBACK': 'feedback', + 'EXPLICIT_FEEDBACK': 'explicitFeedback', + 'PERIODIC': 'periodic', + 'NOTIFICATION': 'notification' }; interface Device { @@ -9712,6 +9940,47 @@ declare namespace chrome { const onDeviceRemoved: DeviceEvent; } + ////////////////////// + // Virtual Keyboard // + ////////////////////// + /** + * @requires(CrOS Kiosk) Important: This API works only in Chrome OS apps. + * @requires Permissions: 'virtualKeyboard' + * @since Chrome 58 + * @description + * The *chrome.virtualKeybaord* API is a kiosk only API used + * to configure virtual keyboard layout and behavior in kiosk sessions. + */ + namespace virtualKeyboard { + /** + * Determines whether advanced virtual keyboard features should be enabled or not. + * They are enabled by default. + * + * On **Chrome 58** all properties are expected to have the same value. + * + * From **Chrome 63** the properties can be distinct and are optional. + * If omitted, the current value is preserved. + */ + interface FeatureRestrictions { + /** Whether virtual keyboards can provide auto-complete. */ + autoCompleteEnabled?: boolean; + /** Whether virtual keyboards can provide auto-correct. */ + autoCorrectEnabled?: boolean; + /** Whether virtual keyboards can provide input via handwriting recognition. */ + handwritingEnabled?: boolean; + /** Whether virtual keyboards can provide spell-check. */ + spellCheckEnabled?: boolean; + /** Whether virtual keyboards can provide voice input. */ + voiceInputEnabled?: boolean; + } + + /** + * Sets restrictions on features provided by the virtual keyboard. + * @param restrictions the preferences to enabled/disabled virtual keyboard features. + * @param [callback] Invoked with the values which were updated. + */ + function restrictFeatures(restrictions: FeatureRestrictions, callback?: (update: FeatureRestrictions) => void): void; + } ////////////////// // VPN Provider // @@ -9724,22 +9993,22 @@ declare namespace chrome { */ namespace vpnProvider { const PlatformMessage: { - CONNECTED: "connected", - DISCONNECTED: "disconnected", - ERROR: "error", - LINK_DOWN: "linkDown", - LINK_UP: "linkUp", - LINK_CHANGED: "linkChanged", - SUSPEND: "suspend", - RESUME: "resume" + CONNECTED: 'connected', + DISCONNECTED: 'disconnected', + ERROR: 'error', + LINK_DOWN: 'linkDown', + LINK_UP: 'linkUp', + LINK_CHANGED: 'linkChanged', + SUSPEND: 'suspend', + RESUME: 'resume' }; const VpnConnectionState: { - CONNECTED: "connected", - FAILURE: "failure" + CONNECTED: 'connected', + FAILURE: 'failure' }; const UIEvent: { - SHOW_ADD_DIALOG: "showAddDialog", - SHOW_CONFIGURE_DIALOG: "showConfigureDialog" + SHOW_ADD_DIALOG: 'showAddDialog', + SHOW_CONFIGURE_DIALOG: 'showConfigureDialog' }; interface VpnSessionParameters { /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ @@ -9846,9 +10115,9 @@ declare namespace chrome { */ namespace wallpaper { const WallpaperLayout: { - "STRETCH": "STRETCH", - "CENTER": "CENTER", - "CENTER_CROPPED": "CENTER_CROPPED" + 'STRETCH': 'STRETCH', + 'CENTER': 'CENTER', + 'CENTER_CROPPED': 'CENTER_CROPPED' }; interface WallpaperDetails { /** The jpeg or png encoded wallpaper image. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 19401a5ccf..523ce4f757 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -198,6 +198,21 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { version: "2.1", minimum_chrome_version: "33.0.1715.0", default_locale: "en", + file_browser_handlers: [ + { + id: "ReadOnly", + default_title: "Test read-only action.", + default_icon: "icon.png", + file_filters: ["filesystem:*.xul"], + file_access: ["read"] + }, + { + id: "ReadWrite", + default_title: "Test read-write action", + default_icon: "icon.png", + file_filters: ["filesystem:*.tiff"] + } + ], file_system_provider_capabilities: { configurable: false, multiple_mounts: true, @@ -632,6 +647,12 @@ chrome.contextMenus.onClicked.addListener((info) => { chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); +// DNS + +chrome.dns.resolve("github.com", (info) => { + console.log([info.resultCode === 0, info.address]); +}); + // ENTERPRISE - DEVICE ATTRIBUTES const deviceAttr = chrome.enterprise.deviceAttributes; @@ -1060,6 +1081,28 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { } }); +// SYSTEM APIs + +function getPowerSourceInfo() { + chrome.system.powerSource.getPowerSourceInfo(info => { + if (info === undefined) { + return true; + } + if (info.length === 1 && info[0].type !== chrome.system.powerSource.PowerSourceType.mains) { + return false; + } + })); +}, + +function onPowerChanged() { + chrome.system.powerSource.onPowerChanged.addListener(info => { + if (info[0].active) { + return true; + } + }); + chrome.system.powerSource.requestStatusUpdate(); +}, + // TTS chrome.tts.isSpeaking((isSpeaking) => { @@ -1072,6 +1115,7 @@ chrome.tts.isSpeaking((isSpeaking) => { }); // USB + const devices: { [key: string]: chrome.usb.Device } = {}; chrome.usb.onDeviceAdded.addListener((device) => { devices[device.device] = device; From f0c37272afe1f0c9b7c63d491e4a742559e57594 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tar=C4=B1k?= Date: Thu, 16 Aug 2018 15:15:04 +0300 Subject: [PATCH 055/289] added missing variables --- types/google-cloud__storage/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts index 18ac093c5d..2053abcc62 100644 --- a/types/google-cloud__storage/index.d.ts +++ b/types/google-cloud__storage/index.d.ts @@ -104,10 +104,12 @@ declare namespace Storage { interface BucketQuery { autoPaginate?: boolean; delimiter?: string; + directory?: string; prefix?: string; maxApiCalls?: number; maxResults?: number; pageToken?: string; + userProject?: string; versions?: boolean; } From 002e3140e5170232c9d91be15860bddb0a0400b2 Mon Sep 17 00:00:00 2001 From: Evan Scott Date: Sat, 18 Aug 2018 01:13:10 -0500 Subject: [PATCH 056/289] add styled-components --- types/styled-components/index.d.ts | 212 +++++++ .../styled-components-tests.tsx | 548 ++++++++++++++++++ types/styled-components/tsconfig.json | 17 + types/styled-components/tslint.json | 1 + 4 files changed, 778 insertions(+) create mode 100644 types/styled-components/index.d.ts create mode 100644 types/styled-components/styled-components-tests.tsx create mode 100644 types/styled-components/tsconfig.json create mode 100644 types/styled-components/tslint.json diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts new file mode 100644 index 0000000000..9654334af2 --- /dev/null +++ b/types/styled-components/index.d.ts @@ -0,0 +1,212 @@ +// Type definitions for styled-components 3.0 +// Project: https://github.com/styled-components/styled-components +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import * as React from 'react'; + +export interface ThemeProps { + theme: T; +} + +export type ThemedStyledProps = P & ThemeProps; +export type StyledProps

= ThemedStyledProps; + +export type ThemedOuterStyledProps = P & { + theme?: T; + innerRef?: + | ((instance: any) => void) + | React.RefObject; +}; +export type OuterStyledProps

= ThemedOuterStyledProps; + +export type FalseyValue = undefined | null | false; +export type Interpolation

= + | FlattenInterpolation

+ | ReadonlyArray< + FlattenInterpolation

| ReadonlyArray> + >; +export type FlattenInterpolation

= + | InterpolationValue + | InterpolationFunction

; +export type InterpolationValue = + | string + | number + | Styles + | FalseyValue + | StyledComponentClass; +export type SimpleInterpolation = + | InterpolationValue + | ReadonlyArray>; +export interface Styles { + [ruleOrSelector: string]: string | number | Styles; +} + +export type InterpolationFunction

= (props: P) => Interpolation

; + +type Attrs, T> = { + [K in keyof A]: ((props: ThemedStyledProps) => A[K]) | A[K] +}; + +export interface StyledComponentClass + extends React.ComponentClass> { + extend: ThemedStyledFunction; + + withComponent( + tag: K, + ): StyledComponentClass< + JSX.IntrinsicElements[K], + T, + JSX.IntrinsicElements[K] & O + >; + withComponent( + element: React.ComponentType, + ): StyledComponentClass; +} + +export interface ThemedStyledFunction { + ( + strings: TemplateStringsArray, + ...interpolations: Array>> + ): StyledComponentClass; + ( + strings: TemplateStringsArray, + ...interpolations: Array>> + ): StyledComponentClass

; + attrs = {}>( + attrs: Attrs

, + ): ThemedStyledFunction, T, DiffBetween>; +} + +export type StyledFunction

= ThemedStyledFunction; + +type ThemedStyledComponentFactories = { + [TTag in keyof JSX.IntrinsicElements]: ThemedStyledFunction< + JSX.IntrinsicElements[TTag], + T + > +}; + +export interface ThemedBaseStyledInterface + extends ThemedStyledComponentFactories { + ( + tag: TTag, + ): ThemedStyledFunction; + (component: StyledComponentClass): ThemedStyledFunction< + P, + T, + O + >; +

( + component: React.ComponentType

, + ): ThemedStyledFunction>; +} +export type BaseStyledInterface = ThemedBaseStyledInterface; + +export type ThemedStyledInterface = ThemedBaseStyledInterface; +export type StyledInterface = ThemedStyledInterface; + +export interface ThemeProviderProps { + theme?: T | ((theme: T) => T); +} +export type ThemeProviderComponent = React.ComponentClass< + ThemeProviderProps +>; + +export interface ThemedCssFunction { + ( + strings: TemplateStringsArray, + ...interpolations: SimpleInterpolation[] + ): InterpolationValue[]; +

( + strings: TemplateStringsArray, + ...interpolations: Array>> + ): Array>>; +} + +// Helper type operators +type KeyofBase = keyof any; +type Diff = ({ [P in T]: P } & + { [P in U]: never })[T]; +type Omit = Pick>; +type DiffBetween = Pick> & + Pick>; +type WithOptionalTheme

= Omit & { + theme?: T; +}; + +export interface ThemedStyledComponentsModule { + default: ThemedStyledInterface; + + css: ThemedCssFunction; + keyframes( + strings: TemplateStringsArray, + ...interpolations: SimpleInterpolation[] + ): string; + injectGlobal( + strings: TemplateStringsArray, + ...interpolations: SimpleInterpolation[] + ): void; + withTheme

( + component: React.ComponentType

, + ): React.ComponentClass>; + + ThemeProvider: ThemeProviderComponent; +} + +declare const styled: StyledInterface; + +export const css: ThemedCssFunction; + +export function withTheme

( + component: React.ComponentType

, +): React.ComponentClass>; + +export function keyframes( + strings: TemplateStringsArray, + ...interpolations: SimpleInterpolation[] +): string; + +export function injectGlobal( + strings: TemplateStringsArray, + ...interpolations: SimpleInterpolation[] +): void; + +export function consolidateStreamedStyles(): void; + +export function isStyledComponent( + target: any, +): target is StyledComponentClass<{}, {}>; + +export const ThemeProvider: ThemeProviderComponent; + +interface StylesheetComponentProps { + sheet: ServerStyleSheet; +} + +interface StyleSheetManagerProps { + sheet?: StyleSheet; + target?: Node; +} + +export class StyleSheetManager extends React.Component< + StyleSheetManagerProps +> {} + +export class ServerStyleSheet { + collectStyles( + tree: React.ReactNode, + ): React.ReactElement; + + getStyleTags(): string; + getStyleElement(): Array>; + interleaveWithNodeStream( + readableStream: NodeJS.ReadableStream, + ): NodeJS.ReadableStream; + instance: StyleSheet; +} + +export default styled; diff --git a/types/styled-components/styled-components-tests.tsx b/types/styled-components/styled-components-tests.tsx new file mode 100644 index 0000000000..d2e6cc04cd --- /dev/null +++ b/types/styled-components/styled-components-tests.tsx @@ -0,0 +1,548 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as ReactDOMServer from 'react-dom/server'; + +import styled, { + css, + injectGlobal, + isStyledComponent, + keyframes, + ServerStyleSheet, + StyleSheetManager, + ThemeProps, + ThemeProvider, + withTheme, +} from 'styled-components'; + +/** + * general usage + */ + +// Create a react component that renders an <h1> which is +// centered, palevioletred and sized at 1.5em +const Title = styled.h1` + font-size: 1.5em; + text-align: center; + color: palevioletred; +`; + +// Create a <Wrapper> react component that renders a <section> with +// some padding and a papayawhip background +const Wrapper = styled.section` + padding: 4em; + background: papayawhip; +`; + +const Input = styled.input` + font-size: 1.25em; + padding: 0.5em; + margin: 0.5em; + color: palevioletred; + background: papayawhip; + border: none; + border-radius: 3px; + + &:hover { + box-shadow: inset 1px 1px 2px rgba(0, 0, 0, 0.1); + } +`; + +interface MyTheme { + primary: string; +} + +interface ButtonProps { + name: string; + primary?: boolean; + theme: MyTheme; +} + +class MyButton extends React.Component<ButtonProps> { + render() { + return <button>Custom button</button>; + } +} + +const TomatoButton = styled(MyButton)` + color: tomato; + border-color: tomato; +`; + +const CustomizableButton = styled(MyButton)` + /* Adapt the colors based on primary prop */ + background: ${props => (props.primary ? 'palevioletred' : 'white')}; + color: ${props => (props.primary ? 'white' : 'palevioletred')}; + + font-size: 1em; + margin: 1em; + padding: 0.25em 1em; + border: 2px solid ${props => props.theme.primary}; + border-radius: 3px; +`; + +const example = css` + font-size: 1.5em; + text-align: center; + color: ${props => props.theme.primary}; + border-color: ${'red'}; +`; + +const fadeIn = keyframes` + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } +`; + +const theme = { + main: 'mediumseagreen', +}; + +injectGlobal` + @font-face { + font-family: 'Operator Mono'; + src: url('../fonts/Operator-Mono.ttf'); + } + + body { + margin: 0; + } +`; + +class Example extends React.Component { + render() { + return ( + <ThemeProvider theme={theme}> + <Wrapper> + <Title> + Hello World, this is my first styled component! + + + + + + ; + + ); + } +} + +// css which only uses simple interpolations without functions +const cssWithValues1 = css` + font-size: ${14} ${'pt'}; +`; +// css which uses other simple interpolations without functions +const cssWithValues2 = css` + ${cssWithValues1} + ${[cssWithValues1, cssWithValues1]} + font-weight: ${'bold'}; +`; +// injectGlobal accepts simple interpolations if they're not using functions +injectGlobal` + ${'font-size'}: ${10}pt; + ${cssWithValues1} + ${[cssWithValues1, cssWithValues2]} +`; + +// css which uses function interpolations with common props +const cssWithFunc1 = css` + font-size: ${props => props.theme.fontSizePt}pt; +`; +const cssWithFunc2 = css` + ${cssWithFunc1} + ${props => cssWithFunc1} + ${[cssWithFunc1, cssWithValues1]} +`; +// such css can be used in styled components +const styledButton = styled.button` + ${cssWithValues1} ${[cssWithValues1, cssWithValues2]} + ${cssWithFunc1} ${[cssWithFunc1, cssWithFunc2]} + ${() => [cssWithFunc1, cssWithFunc2]} +`; +// css with function interpolations cannot be used in injectGlobal +/* +injectGlobal` + ${cssWithFunc1} +`; +*/ + +const name = 'hey'; + +const ThemedMyButton = withTheme(MyButton); + +; + +/** + * nested styles + */ + +const Link = styled.a` + color: red; +`; + +const AlternativeLink = styled.a` + color: blue; +`; + +const freeStyles = css` + background-color: black; + color: white; + ${Link} { + color: blue; + } +`; + +const Article = styled.section` + color: red; + ${freeStyles} + & > ${Link} { + color: green; + } + ${p => (p.theme.useAlternativeLink ? AlternativeLink : Link)} { + color: black + } +`; + +// A Link instance should be backed by an HTMLAnchorElement +const ComposedLink = () => ( + ) => undefined} /> +); + +/** + * construction via string tag + */ + +// Create a react component that renders an which is +// centered, palevioletred and sized at 1.5em +const LinkFromString = styled('a')` + font-size: 1.5em; + text-align: center; + color: palevioletred; +`; + +// A LinkFromString instance should be backed by an HTMLAnchorElement +const MyOtherComponent = () => ( + ) => undefined} + /> +); + +// Create a react component that renders an +// which takes extra props +interface LinkProps { + canClick: boolean; +} + +const LinkFromStringWithProps = styled('a')` + font-size: 1.5em; + text-align: center; + color: ${(a: LinkProps) => (a.canClick ? 'palevioletred' : 'gray')}; +`; + +// A LinkFromStringWithProps instance should be backed by an HTMLAnchorElement +const MyOtherComponentWithProps = () => ( + ) => undefined} + /> +); + +// Create a react component that renders an +// which takes extra props passed as a generic type argument +const LinkFromStringWithPropsAndGenerics = styled('a')` + font-size: 1.5em; + text-align: center; + color: ${a => (a.canClick ? 'palevioletred' : 'gray')}; +`; + +// A LinkFromStringWithPropsAndGenerics instance should be backed by an HTMLAnchorElement +const MyOtherComponentWithPropsAndGenerics = () => ( + ) => undefined} + /> +); + +/** + * object styles + */ + +interface ObjectStyleProps { + size: string; +} + +const functionReturningStyleObject = (props: ObjectStyleProps) => ({ + padding: props.size === 'big' ? '10px' : 2, +}); + +const ObjectStylesBox = styled.div` + ${functionReturningStyleObject} ${{ + backgroundColor: 'red', + + // Supports nested objects (pseudo selectors, media queries, etc) + '@media screen and (min-width: 800px)': { + backgroundColor: 'blue', + }, + + fontSize: 2, + }}; +`; + +; + +/** + * attrs + */ + +const AttrsInput = styled.input.attrs({ + // we can define static props + type: 'password', + + // or we can define dynamic ones + margin: (props: any) => (props.size as string) || '1em', + padding: (props: any) => (props.size as string) || '1em', +})` + color: palevioletred; + font-size: 1em; + border: 2px solid palevioletred; + border-radius: 3px; + + /* here we use the dynamically computed props */ + margin: ${props => props.margin}; + padding: ${props => props.padding}; +`; + +/** + * component type + */ + +declare const A: React.ComponentClass; +declare const B: React.StatelessComponent; +declare const C: React.ComponentType; + +styled(A); // succeeds +styled(B); // succeeds +styled(C); // used to fail; see issue trail linked below + +// https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247 +// https://github.com/mui-org/material-ui/issues/9838 +// https://github.com/styled-components/styled-components/pull/1420 +// https://github.com/Microsoft/TypeScript/issues/21175 +// https://github.com/styled-components/styled-components/pull/1427 + +/** + * extend + */ + +const ExtendButton = styled.button` + color: palevioletred; + font-size: 1em; + margin: 1em; + padding: 0.25em 1em; + border: 2px solid palevioletred; + border-radius: 3px; +`; + +// We're extending Button with some extra styles +const TomatoExtendButton = ExtendButton.extend` + color: tomato; + border-color: tomato; +`; + +/** + * function themes + */ + +// Define our button, but with the use of props.theme this time +const ThemedButton = styled.button` + color: ${props => props.theme.fg}; + border: 2px solid ${props => props.theme.fg}; + background: ${props => props.theme.bg}; + + font-size: 1em; + margin: 1em; + padding: 0.25em 1em; + border-radius: 3px; +`; + +// Define our `fg` and `bg` on the theme +const theme2 = { + fg: 'palevioletred', + bg: 'white', +}; + +// This theme swaps `fg` and `bg` +const invertTheme = ({ fg, bg }: { fg: string; bg: string }) => ({ + fg: bg, + bg: fg, +}); + +const MyApp = ( + +
+ Default Theme + + + Inverted Theme + +
+
+); + +/** + * withTheme HOC + */ + +class MyComponent extends React.Component> { + render() { + const { theme } = this.props; + + console.log('Current theme: ', theme); + + return

Hello

; + } +} + +const ThemedMyComponent = withTheme(MyComponent); + +interface WithThemeProps { + theme: { + color: string; + }; + text: string; +} + +const Component = (props: WithThemeProps) => ( +
{props.text}
+); + +const ComponentWithTheme = withTheme(Component); + +; // ok +; // ok + +/** + * isStyledComponent utility + */ + +const StyledComponent = styled.h1``; + +const StatelessComponent = () =>
; + +class ClassComponent extends React.Component { + render() { + return
; + } +} + +isStyledComponent(StyledComponent); +isStyledComponent(StatelessComponent); +isStyledComponent(ClassComponent); +isStyledComponent('div'); + +/** + * server side rendering + */ + +const SSRTitle = styled.h1` + font-size: 1.5em; + text-align: center; + color: palevioletred; +`; + +const sheet = new ServerStyleSheet(); +const html = sheet.collectStyles(Hello world); +const styleHtml = sheet.getStyleTags(); +const styleElement = sheet.getStyleElement(); + +const sheet2 = new ServerStyleSheet(); +const element = ( + + Hello world + +); + +const css2 = sheet2.getStyleElement(); + +// Wrapping a node stream returned from renderToNodeStream with interleaveWithNodeStream + +const sheet3 = new ServerStyleSheet(); +const appStream = ReactDOMServer.renderToNodeStream(Hello world); +const wrappedCssStream: NodeJS.ReadableStream = sheet3.interleaveWithNodeStream( + appStream, +); + +/** + * StyledComponent.withComponent + */ + +const WithComponentH1 = styled.h1` + color: palevioletred; + font-size: 1em; +`; + +function getRandomInt(min: number, max: number) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min)) + min; +} + +class Random extends React.Component { + render() { + const i = getRandomInt(1, 6); + + switch (i) { + case 1: + return

Hello World

; + case 2: + return

Hello World

; + case 3: + return

Hello World

; + case 4: + return

Hello World

; + case 5: + return
Hello World
; + case 6: + return
Hello World
; + default: + return null; + } + } +} + +const WithComponentH2 = WithComponentH1.withComponent('h2'); +const WithComponentAbbr = WithComponentH1.withComponent('abbr'); + +const WithComponentAnchor = WithComponentH1.withComponent('a'); +const AnchorContainer = () => ( + + withComponent Anchor + +); + +const WithComponentRandomHeading = WithComponentH1.withComponent(Random); + +const WithComponentCompA: React.SFC<{ a: number; className?: string }> = ({ + className, +}) =>
; +const WithComponentCompB: React.SFC<{ b: number; className?: string }> = ({ + className, +}) =>
; +const WithComponentStyledA = styled(WithComponentCompA)` + color: ${(props: { color: string }) => props.color}; +`; + +const WithComponentFirstStyledA = styled(WithComponentStyledA).attrs({ + a: 1, +})``; + +const WithComponentFirstStyledB = WithComponentFirstStyledA.withComponent( + WithComponentCompB, +); + +const test = () => [ + , + , +]; diff --git a/types/styled-components/tsconfig.json b/types/styled-components/tsconfig.json new file mode 100644 index 0000000000..26cb1835d5 --- /dev/null +++ b/types/styled-components/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "lib": ["es6", "dom"], + "module": "commonjs", + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "typeRoots": ["../"], + "types": [] + }, + "files": ["index.d.ts", "styled-components-tests.tsx"] +} diff --git a/types/styled-components/tslint.json b/types/styled-components/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/styled-components/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 77159b4b96175b2ecfabed28d35ffed83017db8c Mon Sep 17 00:00:00 2001 From: Beeno Tung Date: Sat, 18 Aug 2018 17:39:35 +0800 Subject: [PATCH 057/289] added ed25519 in pki --- types/node-forge/index.d.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 65ff4edb47..41c573d5b8 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -73,6 +73,33 @@ declare module "node-forge" { function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } + namespace ed25519 { + + type NativeBuffer = Buffer | Uint8Array; + + namespace constants { + const PUBLIC_KEY_BYTE_LENGTH = 32; + const PRIVATE_KEY_BYTE_LENGTH = 64; + const SEED_BYTE_LENGTH = 32; + const SIGN_BYTE_LENGTH = 64; + const HASH_BYTE_LENGTH = 64; + } + + function generateKeyPair(options?: { seed?: Buffer | Uint8Array | string }): { + publicKey: NativeBuffer; + privateKey: NativeBuffer; + }; + + function publicKeyFromPrivateKey(options: { privateKey: NativeBuffer }): NativeBuffer; + + function sign(options: { privateKey: NativeBuffer }): NativeBuffer; + + function verify(options: { + signature: Buffer | Uint8Array | util.ByteBuffer | string, + publicKey: NativeBuffer + }): boolean; + } + interface CertificateFieldOptions { name?: string; type?: string; From 948f181fee5d1e644da07e1617022cba793886d0 Mon Sep 17 00:00:00 2001 From: Francis Gulotta Date: Fri, 10 Aug 2018 13:16:33 -0400 Subject: [PATCH 058/289] ioredis: doesn't use bluebird by default https://github.com/luin/ioredis#plugging-in-your-own-promises-library Also not in the package.json's deps. --- types/ioredis/index.d.ts | 5 +- types/ioredis/ioredis-tests.ts | 3 - types/ioredis/v3/index.d.ts | 911 ++++++++++++++++++++++++++++++ types/ioredis/v3/ioredis-tests.ts | 153 +++++ types/ioredis/v3/tsconfig.json | 26 + types/ioredis/v3/tslint.json | 1 + 6 files changed, 1093 insertions(+), 6 deletions(-) create mode 100644 types/ioredis/v3/index.d.ts create mode 100644 types/ioredis/v3/ioredis-tests.ts create mode 100644 types/ioredis/v3/tsconfig.json create mode 100644 types/ioredis/v3/tslint.json diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index e593f4dcc3..6fea4469ce 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ioredis 3.2 +// Type definitions for ioredis 4.0 // Project: https://github.com/luin/ioredis // Definitions by: York Yao // Christopher Eck @@ -12,12 +12,11 @@ /* =================== USAGE =================== import * as Redis from "ioredis"; - var redis = new Redis(); + const redis = new Redis(); =============================================== */ /// -import Promise = require('bluebird'); import tls = require('tls'); interface RedisStatic { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 32ae5c24d5..89ed8d1ce0 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -125,9 +125,6 @@ redis.multi([ // results = [[null, 'OK'], [null, 'bar']] }); -redis.Promise.onPossiblyUnhandledRejection((error) => { -}); - const keys = ['foo', 'bar']; redis.mget(...keys); diff --git a/types/ioredis/v3/index.d.ts b/types/ioredis/v3/index.d.ts new file mode 100644 index 0000000000..e593f4dcc3 --- /dev/null +++ b/types/ioredis/v3/index.d.ts @@ -0,0 +1,911 @@ +// Type definitions for ioredis 3.2 +// Project: https://github.com/luin/ioredis +// Definitions by: York Yao +// Christopher Eck +// Yoga Aliarham +// Ebrahim +// Shahar Mor +// Whemoon Jang +// Francis Gulotta +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/* =================== USAGE =================== + import * as Redis from "ioredis"; + var redis = new Redis(); + =============================================== */ + +/// + +import Promise = require('bluebird'); +import tls = require('tls'); + +interface RedisStatic { + new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(options?: IORedis.RedisOptions): IORedis.Redis; + (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + (options?: IORedis.RedisOptions): IORedis.Redis; + Cluster: IORedis.Cluster; + Command: IORedis.Command; +} + +declare var IORedis: RedisStatic; +export = IORedis; + +declare class Commander { + getBuiltinCommands(): string[]; + createBuiltinCommand(commandName: string): {}; + defineCommand(name: string, definition: { + numberOfKeys?: number; + lua?: string; + }): any; + sendCommand(): void; +} + +declare namespace IORedis { + interface Command { + setArgumentTransformer(name: string, fn: (args: any[]) => any[]): void; + setReplyTransformer(name: string, fn: (result: any) => any): void; + } + + interface Redis extends NodeJS.EventEmitter, Commander { + Promise: typeof Promise; + status: string; + connect(callback?: () => void): Promise; + disconnect(): void; + duplicate(): Redis; + + send_command(command: string, ...args: any[]): any; + + bitcount(key: string, callback: (err: Error, res: number) => void): void; + bitcount(key: string, start: number, end: number, callback: (err: Error, res: number) => void): void; + bitcount(key: string): Promise; + bitcount(key: string, start: number, end: number): Promise; + + get(key: string, callback: (err: Error, res: string) => void): void; + get(key: string): Promise; + + getBuffer(key: string, callback: (err: Error, res: Buffer) => void): void; + getBuffer(key: string): Promise; + + set(key: string, value: any, expiryMode?: string | any[], time?: number | string, setMode?: number | string): Promise; + + set(key: string, value: any, callback: (err: Error, res: string) => void): void; + set(key: string, value: any, setMode: string | any[], callback: (err: Error, res: string) => void): void; + set(key: string, value: any, expiryMode: string, time: number | string, callback: (err: Error, res: string) => void): void; + set(key: string, value: any, expiryMode: string, time: number | string, setMode: number | string, callback: (err: Error, res: string) => void): void; + + setBuffer(key: string, value: any, expiryMode?: string | any[], time?: number | string, setMode?: number | string): Promise; + + setBuffer(key: string, value: any, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, setMode: string, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, expiryMode: string, time: number, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, expiryMode: string, time: number | string, setMode: number | string, callback: (err: Error, res: Buffer) => void): void; + + setnx(key: string, value: any, callback: (err: Error, res: any) => void): void; + setnx(key: string, value: any): Promise; + + setex(key: string, seconds: number, value: any, callback: (err: Error, res: any) => void): void; + setex(key: string, seconds: number, value: any): Promise; + + psetex(key: string, milliseconds: number, value: any, callback: (err: Error, res: any) => void): void; + psetex(key: string, milliseconds: number, value: any): Promise; + + append(key: string, value: any, callback: (err: Error, res: number) => void): void; + append(key: string, value: any): Promise; + + strlen(key: string, callback: (err: Error, res: number) => void): void; + strlen(key: string): Promise; + + del(...keys: string[]): any; + + exists(...keys: string[]): any; + + setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setbit(key: string, offset: number, value: any): Promise; + + getbit(key: string, offset: number, callback: (err: Error, res: number) => void): void; + getbit(key: string, offset: number): Promise; + + setrange(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setrange(key: string, offset: number, value: any): Promise; + + getrange(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + getrange(key: string, start: number, end: number): Promise; + + substr(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + substr(key: string, start: number, end: number): Promise; + + incr(key: string, callback: (err: Error, res: number) => void): void; + incr(key: string): Promise; + + decr(key: string, callback: (err: Error, res: number) => void): void; + decr(key: string): Promise; + + mget(...keys: string[]): any; + + rpush(key: string, ...values: any[]): any; + + lpush(key: string, ...values: any[]): any; + + rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + rpushx(key: string, value: any): Promise; + + lpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + lpushx(key: string, value: any): Promise; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback: (err: Error, res: number) => void): void; + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any): Promise; + + rpop(key: string, callback: (err: Error, res: string) => void): void; + rpop(key: string): Promise; + + lpop(key: string, callback: (err: Error, res: string) => void): void; + lpop(key: string): Promise; + + brpop(...keys: string[]): any; + + blpop(...keys: string[]): any; + + brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; + brpoplpush(source: string, destination: string, timeout: number): Promise; + + llen(key: string, callback: (err: Error, res: number) => void): void; + llen(key: string): Promise; + + lindex(key: string, index: number, callback: (err: Error, res: string) => void): void; + lindex(key: string, index: number): Promise; + + lset(key: string, index: number, value: any, callback: (err: Error, res: any) => void): void; + lset(key: string, index: number, value: any): Promise; + + lrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + lrange(key: string, start: number, stop: number): Promise; + + ltrim(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + ltrim(key: string, start: number, stop: number): Promise; + + lrem(key: string, count: number, value: any, callback: (err: Error, res: number) => void): void; + lrem(key: string, count: number, value: any): Promise; + + rpoplpush(source: string, destination: string, callback: (err: Error, res: string) => void): void; + rpoplpush(source: string, destination: string): Promise; + + sadd(key: string, ...members: any[]): any; + + srem(key: string, ...members: any[]): any; + + smove(source: string, destination: string, member: string, callback: (err: Error, res: string) => void): void; + smove(source: string, destination: string, member: string): Promise; + + sismember(key: string, member: string, callback: (err: Error, res: 1 | 0) => void): void; + sismember(key: string, member: string): Promise<1 | 0>; + + scard(key: string, callback: (err: Error, res: number) => void): void; + scard(key: string): Promise; + + spop(key: string, callback: (err: Error, res: any) => void): void; + spop(key: string, count: number, callback: (err: Error, res: any) => void): void; + spop(key: string, count?: number): Promise; + + srandmember(key: string, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count?: number): Promise; + + sinter(...keys: string[]): any; + + sinterstore(destination: string, ...keys: string[]): any; + + sunion(...keys: string[]): any; + + sunionstore(destination: string, ...keys: string[]): any; + + sdiff(...keys: string[]): any; + + sdiffstore(destination: string, ...keys: string[]): any; + + smembers(key: string, callback: (err: Error, res: any) => void): void; + smembers(key: string): Promise; + + zadd(key: string, ...args: string[]): any; + + zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; + zincrby(key: string, increment: number, member: string): Promise; + + zrem(key: string, ...members: any[]): any; + + zremrangebyscore(key: string, min: number | string, max: number | string, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number | string, max: number | string): Promise; + + zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zremrangebyrank(key: string, start: number, stop: number): Promise; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrevrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): any; + + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): any; + + zcount(key: string, min: number | string, max: number | string, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number | string, max: number | string): Promise; + + zcard(key: string, callback: (err: Error, res: number) => void): void; + zcard(key: string): Promise; + + zscore(key: string, member: string, callback: (err: Error, res: string) => void): void; + zscore(key: string, member: string): Promise; + + zrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrank(key: string, member: string): Promise; + + zrevrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrevrank(key: string, member: string): Promise; + + hset(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hset(key: string, field: string, value: any): Promise<0 | 1>; + hsetBuffer(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetBuffer(key: string, field: string, value: any): Promise; + + hsetnx(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetnx(key: string, field: string, value: any): Promise<0 | 1>; + + hget(key: string, field: string, callback: (err: Error, res: string) => void): void; + hget(key: string, field: string): Promise; + hgetBuffer(key: string, field: string, callback: (err: Error, res: Buffer) => void): void; + hgetBuffer(key: string, field: string): Promise; + + hmset(key: string, field: string, value: any, ...args: string[]): Promise<0 | 1>; + hmset(key: string, data: any, callback: (err: Error, res: 0 | 1) => void): void; + hmset(key: string, data: any): Promise<0 | 1>; + + hmget(key: string, ...fields: string[]): any; + + hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrby(key: string, field: string, increment: number): Promise; + + hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrbyfloat(key: string, field: string, increment: number): Promise; + + hdel(key: string, ...fields: string[]): any; + + hlen(key: string, callback: (err: Error, res: number) => void): void; + hlen(key: string): Promise; + + hkeys(key: string, callback: (err: Error, res: any) => void): void; + hkeys(key: string): Promise; + + hvals(key: string, callback: (err: Error, res: any) => void): void; + hvals(key: string): Promise; + + hgetall(key: string, callback: (err: Error, res: any) => void): void; + hgetall(key: string): Promise; + + hexists(key: string, field: string, callback: (err: Error, res: 0 | 1) => void): void; + hexists(key: string, field: string): Promise<0 | 1>; + + incrby(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrby(key: string, increment: number): Promise; + + incrbyfloat(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrbyfloat(key: string, increment: number): Promise; + + decrby(key: string, decrement: number, callback: (err: Error, res: number) => void): void; + decrby(key: string, decrement: number): Promise; + + getset(key: string, value: any, callback: (err: Error, res: string) => void): void; + getset(key: string, value: any): Promise; + + mset(key: string, value: any, ...args: string[]): any; + + msetnx(key: string, value: any, ...args: string[]): any; + + randomkey(callback: (err: Error, res: string) => void): void; + randomkey(): Promise; + + select(index: number, callback: (err: Error, res: string) => void): void; + select(index: number): Promise; + + move(key: string, db: string, callback: (err: Error, res: 0 | 1) => void): void; + move(key: string, db: string): Promise<0 | 1>; + + rename(key: string, newkey: string, callback: (err: Error, res: string) => void): void; + rename(key: string, newkey: string): Promise; + + renamenx(key: string, newkey: string, callback: (err: Error, res: 0 | 1) => void): void; + renamenx(key: string, newkey: string): Promise<0 | 1>; + + expire(key: string, seconds: number, callback: (err: Error, res: 0 | 1) => void): void; + expire(key: string, seconds: number): Promise<0 | 1>; + + pexpire(key: string, milliseconds: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpire(key: string, milliseconds: number): Promise<0 | 1>; + + expireat(key: string, timestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + expireat(key: string, timestamp: number): Promise<0 | 1>; + + pexpireat(key: string, millisecondsTimestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpireat(key: string, millisecondsTimestamp: number): Promise<0 | 1>; + + keys(pattern: string, callback: (err: Error, res: string[]) => void): void; + keys(pattern: string): Promise; + + dbsize(callback: (err: Error, res: number) => void): void; + dbsize(): Promise; + + auth(password: string, callback: (err: Error, res: string) => void): void; + auth(password: string): Promise; + + ping(callback: (err: Error, res: string) => void): void; + ping(message: string, callback: (err: Error, res: string) => void): void; + ping(message?: string): Promise; + + echo(message: string, callback: (err: Error, res: string) => void): void; + echo(message: string): Promise; + + save(callback: (err: Error, res: string) => void): void; + save(): Promise; + + bgsave(callback: (err: Error, res: string) => void): void; + bgsave(): Promise; + + bgrewriteaof(callback: (err: Error, res: string) => void): void; + bgrewriteaof(): Promise; + + shutdown(save: "SAVE" | "NOSAVE", callback: (err: Error, res: any) => void): void; + shutdown(save: "SAVE" | "NOSAVE"): Promise; + + lastsave(callback: (err: Error, res: number) => void): void; + lastsave(): Promise; + + type(key: string, callback: (err: Error, res: string) => void): void; + type(key: string): Promise; + + multi(commands?: string[][], options?: MultiOptions): Pipeline; + multi(options: { pipeline: false }): Promise; + + exec(callback: (err: Error, res: any) => void): void; + exec(): Promise; + + discard(callback: (err: Error, res: any) => void): void; + discard(): Promise; + + sync(callback: (err: Error, res: any) => void): void; + sync(): Promise; + + flushdb(callback: (err: Error, res: string) => void): void; + flushdb(): Promise; + + flushall(callback: (err: Error, res: string) => void): void; + flushall(): Promise; + + sort(key: string, ...args: string[]): any; + + info(callback: (err: Error, res: any) => void): void; + info(section: string, callback: (err: Error, res: any) => void): void; + info(section?: string): Promise; + + time(callback: (err: Error, res: any) => void): void; + time(): Promise; + + monitor(callback: (err: Error, res: NodeJS.EventEmitter) => void): void; + monitor(): Promise; + + ttl(key: string, callback: (err: Error, res: number) => void): void; + ttl(key: string): Promise; + + persist(key: string, callback: (err: Error, res: 0 | 1) => void): void; + persist(key: string): Promise<0 | 1>; + + slaveof(host: string, port: number, callback: (err: Error, res: string) => void): void; + slaveof(host: string, port: number): Promise; + + debug(...args: any[]): any; + + config(...args: any[]): any; + + subscribe(...channels: any[]): any; + + unsubscribe(...channels: string[]): any; + + psubscribe(...patterns: string[]): any; + + punsubscribe(...patterns: string[]): any; + + publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; + publish(channel: string, message: string): Promise; + + watch(...keys: string[]): any; + + unwatch(callback: (err: Error, res: string) => void): void; + unwatch(): Promise; + + cluster(...args: any[]): any; + + restore(...args: any[]): any; + + migrate(...args: any[]): any; + + dump(key: string, callback: (err: Error, res: string) => void): void; + dump(key: string): Promise; + + object(subcommand: string, ...args: any[]): any; + + client(...args: any[]): any; + + eval(...args: any[]): any; + + evalsha(...args: any[]): any; + + script(...args: any[]): any; + + quit(callback: (err: Error, res: string) => void): void; + quit(): Promise; + + scan(cursor: number, ...args: any[]): any; + + sscan(key: string, cursor: number, ...args: any[]): any; + + hscan(key: string, cursor: number, ...args: any[]): any; + + zscan(key: string, cursor: number, ...args: any[]): any; + + pfmerge(destkey: string, ...sourcekeys: string[]): any; + + pfadd(key: string, ...elements: string[]): any; + + pfcount(...keys: string[]): any; + + pipeline(commands?: string[][]): Pipeline; + + scanStream(options?: ScanStreamOption): NodeJS.EventEmitter; + sscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + hscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + zscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + } + + interface Pipeline { + redis: Redis; + isCluster: boolean; + options: RedisOptions; + _queue: Command[]; + _result: any[]; + _transactions: number; + _shaToScript: {}; + bitcount(key: string, callback?: (err: Error, res: number) => void): Pipeline; + bitcount(key: string, start: number, end: number, callback?: (err: Error, res: number) => void): Pipeline; + + get(key: string, callback?: (err: Error, res: string) => void): Pipeline; + getBuffer(key: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + set(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, setMode: string, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, expiryMode: string, time: number, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, expiryMode: string, time: number, setMode: string, callback?: (err: Error, res: string) => void): Pipeline; + + setBuffer(key: string, value: any, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, setMode: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, expiryMode: string, time: number, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, expiryMode: string, time: number, setMode: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + setnx(key: string, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + setex(key: string, seconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + psetex(key: string, milliseconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + append(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + del(...keys: string[]): Pipeline; + + exists(...keys: string[]): Pipeline; + + setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getbit(key: string, offset: number, callback?: (err: Error, res: number) => void): Pipeline; + + setrange(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getrange(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + substr(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + incr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + mget(...keys: string[]): Pipeline; + + rpush(key: string, ...values: any[]): Pipeline; + + lpush(key: string, ...values: any[]): Pipeline; + + rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + lpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + brpop(...keys: string[]): Pipeline; + + blpop(...keys: string[]): Pipeline; + + brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; + + llen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + lindex(key: string, index: number, callback?: (err: Error, res: string) => void): Pipeline; + + lset(key: string, index: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + lrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + ltrim(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + lrem(key: string, count: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpoplpush(source: string, destination: string, callback?: (err: Error, res: string) => void): Pipeline; + + sadd(key: string, ...members: any[]): Pipeline; + + srem(key: string, ...members: any[]): Pipeline; + + smove(source: string, destination: string, member: string, callback?: (err: Error, res: string) => void): Pipeline; + + sismember(key: string, member: string, callback?: (err: Error, res: 1 | 0) => void): Pipeline; + + scard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + spop(key: string, callback?: (err: Error, res: any) => void): Pipeline; + spop(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; + srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + sinter(...keys: string[]): Pipeline; + + sinterstore(destination: string, ...keys: string[]): Pipeline; + + sunion(...keys: string[]): Pipeline; + + sunionstore(destination: string, ...keys: string[]): Pipeline; + + sdiff(...keys: string[]): Pipeline; + + sdiffstore(destination: string, ...keys: string[]): Pipeline; + + smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + zadd(key: string, ...args: string[]): Pipeline; + + zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; + + zrem(key: string, ...members: any[]): Pipeline; + + zremrangebyscore(key: string, min: number | string, max: number | string, callback?: (err: Error, res: any) => void): Pipeline; + + zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): Pipeline; + + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): Pipeline; + + zcount(key: string, min: number | string, max: number | string, callback?: (err: Error, res: number) => void): Pipeline; + + zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + zscore(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrevrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + hset(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + hsetBuffer(key: string, field: string, value: any, callback?: (err: Error, res: Buffer) => void): Pipeline; + + hsetnx(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hget(key: string, field: string, callback?: (err: Error, res: string) => void): Pipeline; + hgetBuffer(key: string, field: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; + hmset(key: string, data: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hmget(key: string, ...fields: string[]): Pipeline; + + hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hdel(key: string, ...fields: string[]): Pipeline; + + hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + hkeys(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hvals(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hgetall(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hexists(key: string, field: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + incrby(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + incrbyfloat(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + decrby(key: string, decrement: number, callback?: (err: Error, res: number) => void): Pipeline; + + getset(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + + mset(key: string, value: any, ...args: string[]): Pipeline; + + msetnx(key: string, value: any, ...args: string[]): Pipeline; + + randomkey(callback?: (err: Error, res: string) => void): Pipeline; + + select(index: number, callback?: (err: Error, res: string) => void): Pipeline; + + move(key: string, db: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + rename(key: string, newkey: string, callback?: (err: Error, res: string) => void): Pipeline; + + renamenx(key: string, newkey: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expire(key: string, seconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpire(key: string, milliseconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expireat(key: string, timestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpireat(key: string, millisecondsTimestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + keys(pattern: string, callback?: (err: Error, res: string[]) => void): Pipeline; + + dbsize(callback?: (err: Error, res: number) => void): Pipeline; + + auth(password: string, callback?: (err: Error, res: string) => void): Pipeline; + + ping(callback?: (err: Error, res: string) => void): Pipeline; + ping(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + echo(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + save(callback?: (err: Error, res: string) => void): Pipeline; + + bgsave(callback?: (err: Error, res: string) => void): Pipeline; + + bgrewriteaof(callback?: (err: Error, res: string) => void): Pipeline; + + shutdown(save: "SAVE" | "NOSAVE", callback?: (err: Error, res: any) => void): Pipeline; + + lastsave(callback?: (err: Error, res: number) => void): Pipeline; + + type(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + multi(callback?: (err: Error, res: string) => void): Pipeline; + + exec(callback?: (err: Error, res: any) => void): Promise; + + discard(callback?: (err: Error, res: any) => void): Pipeline; + + sync(callback?: (err: Error, res: any) => void): Pipeline; + + flushdb(callback?: (err: Error, res: string) => void): Pipeline; + + flushall(callback?: (err: Error, res: string) => void): Pipeline; + + sort(key: string, ...args: string[]): Pipeline; + + info(callback?: (err: Error, res: any) => void): Pipeline; + info(section: string, callback?: (err: Error, res: any) => void): Pipeline; + + time(callback?: (err: Error, res: any) => void): Pipeline; + + monitor(callback?: (err: Error, res: NodeJS.EventEmitter) => void): Pipeline; + + ttl(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + persist(key: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + slaveof(host: string, port: number, callback?: (err: Error, res: string) => void): Pipeline; + + debug(...args: any[]): Pipeline; + + config(...args: any[]): Pipeline; + + subscribe(...channels: any[]): Pipeline; + + unsubscribe(...channels: string[]): Pipeline; + + psubscribe(...patterns: string[]): Pipeline; + + punsubscribe(...patterns: string[]): Pipeline; + + publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; + + watch(...keys: string[]): Pipeline; + + unwatch(callback?: (err: Error, res: string) => void): Pipeline; + + cluster(...args: any[]): Pipeline; + + restore(...args: any[]): Pipeline; + + migrate(...args: any[]): Pipeline; + + dump(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + object(subcommand: string, ...args: any[]): Pipeline; + + client(...args: any[]): Pipeline; + + eval(...args: any[]): Pipeline; + + evalsha(...args: any[]): Pipeline; + + script(...args: any[]): Pipeline; + + quit(callback?: (err: Error, res: string) => void): Pipeline; + + scan(cursor: number, ...args: any[]): Pipeline; + + sscan(key: string, cursor: number, ...args: any[]): Pipeline; + + hscan(key: string, cursor: number, ...args: any[]): Pipeline; + + zscan(key: string, cursor: number, ...args: any[]): Pipeline; + + pfmerge(destkey: string, ...sourcekeys: string[]): Pipeline; + + pfadd(key: string, ...elements: string[]): Pipeline; + + pfcount(...keys: string[]): Pipeline; + } + + interface NodeConfiguration { + host?: string; + port?: number; + } + + type ClusterNode = string | number | NodeConfiguration; + + interface Cluster extends NodeJS.EventEmitter, Commander { + new(nodes: ClusterNode[], options?: ClusterOptions): Redis; + connect(callback: () => void): Promise; + disconnect(): void; + nodes(role: string): Redis[]; + } + + interface RedisOptions { + port?: number; + host?: string; + /** + * 4 (IPv4) or 6 (IPv6), Defaults to 4. + */ + family?: number; + /** + * Local domain socket path. If set the port, host and family will be ignored. + */ + path?: string; + /** + * TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive. + */ + keepAlive?: number; + connectionName?: string; + /** + * If set, client will send AUTH command with the value of this option when connected. + */ + password?: string; + /** + * Database index to use. + */ + db?: number; + /** + * When a connection is established to the Redis server, the server might still be loading + * the database from disk. While loading, the server not respond to any commands. + * To work around this, when this option is true, ioredis will check the status of the Redis server, + * and when the Redis server is able to process commands, a ready event will be emitted. + */ + enableReadyCheck?: boolean; + keyPrefix?: string; + /** + * When the return value isn't a number, ioredis will stop trying to reconnect. + * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858 + */ + retryStrategy?(times: number): number | false; + /** + * 1/true means reconnect, 2 means reconnect and resend failed command. Returning false will ignore + * the error and do nothing. + */ + reconnectOnError?(error: Error): boolean | 1 | 2; + /** + * By default, if there is no active connection to the Redis server, commands are added to a queue + * and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means + * the Redis server has loaded the database from disk, otherwise means the connection to the Redis + * server has been established). If this option is false, when execute the command when the connection + * isn't ready, an error will be returned. + */ + enableOfflineQueue?: boolean; + /** + * The milliseconds before a timeout occurs during the initial connection to the Redis server. + * default: 10000. + */ + connectTimeout?: number; + /** + * After reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels. + * default: true. + */ + autoResubscribe?: boolean; + /** + * If true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected. + * default: true. + */ + autoResendUnfulfilledCommands?: boolean; + lazyConnect?: boolean; + tls?: tls.ConnectionOptions; + sentinels?: Array<{ host: string; port: number; }>; + name?: string; + /** + * Enable READONLY mode for the connection. Only available for cluster mode. + * default: false. + */ + readOnly?: boolean; + /** + * If you are using the hiredis parser, it's highly recommended to enable this option. + * Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string + */ + dropBufferSupport?: boolean; + /** + * Whether to show a friendly error stack. Will decrease the performance significantly. + */ + showFriendlyErrorStack?: boolean; + } + + interface ScanStreamOption { + match?: string; + count?: number; + } + + interface ClusterOptions { + clusterRetryStrategy?(times: number): number; + enableOfflineQueue?: boolean; + enableReadyCheck?: boolean; + scaleReads?: string; + maxRedirections?: number; + retryDelayOnFailover?: number; + retryDelayOnClusterDown?: number; + retryDelayOnTryAgain?: number; + redisOptions?: RedisOptions; + } + + interface MultiOptions { + pipeline: boolean; + } +} diff --git a/types/ioredis/v3/ioredis-tests.ts b/types/ioredis/v3/ioredis-tests.ts new file mode 100644 index 0000000000..32ae5c24d5 --- /dev/null +++ b/types/ioredis/v3/ioredis-tests.ts @@ -0,0 +1,153 @@ +import Redis = require("ioredis"); +const redis = new Redis(); + +redis.set('foo', 'bar'); +redis.get('foo', (err, result) => { + console.log(result); +}); + +// Or using a promise if the last argument isn't a function +redis.get('foo').then((result: any) => { + console.log(result); +}); + +// Arguments to commands are flattened, so the following are the same: +redis.sadd('set', 1, 3, 5, 7); +redis.sadd('set', [1, 3, 5, 7]); + +// All arguments are passed directly to the redis server: +redis.set('key', '100'); +redis.set('key', '100', 'XX'); +redis.set('key', '100', 'PX', 10); +redis.set('key', '100', 'EX', 10, 'NX'); +redis.set('key', '100', 'NX', 'EX', 10); +redis.set('key', '100', ['EX', 10, 'NX']); +redis.setBuffer('key', '100', 'NX', 'EX', 10); + +redis.set('key', '100', (err, data) => {}); +redis.set('key', '100', 'XX', (err, data) => {}); +redis.set('key', '100', 'PX', 10, (err, data) => {}); +redis.set('key', '100', 'EX', 10, 'NX', (err, data) => {}); +redis.set('key', '100', ['EX', 10, 'NX'], (err, data) => {}); +redis.setBuffer('key', '100', 'NX', 'EX', 10, (err, data) => {}); + +new Redis(); // Connect to 127.0.0.1:6379 +new Redis(6380); // 127.0.0.1:6380 +new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379 +new Redis('/tmp/redis.sock'); +new Redis({ + port: 6379, // Redis port + host: '127.0.0.1', // Redis host + family: 4, // 4 (IPv4) or 6 (IPv6) + password: 'auth', + db: 0, + retryStrategy() { return false; }, + showFriendlyErrorStack: true, + tls: { + servername: 'tlsservername' + } +}); + +const pub = new Redis(); +redis.subscribe('news', 'music', (err: any, count: any) => { + // Now we are subscribed to both the 'news' and 'music' channels. + // `count` represents the number of channels we are currently subscribed to. + + pub.publish('news', 'Hello world!'); + pub.publish('music', 'Hello again!'); +}); + +redis.on('message', (channel: any, message: any) => { + // Receive message Hello world! from channel news + // Receive message Hello again! from channel music + console.log('Receive message %s from channel %s', message, channel); +}); + +// There's also an event called 'messageBuffer', which is the same as 'message' except +// it returns buffers instead of strings. +redis.on('messageBuffer', (channel: any, message: any) => { + // Both `channel` and `message` are buffers. +}); + +const pipeline = redis.pipeline(); +pipeline.set('foo', 'bar'); +pipeline.del('cc'); +pipeline.hset('hash', 'foo', 4); +pipeline.hget('hash', 'foo'); +pipeline.hsetBuffer('hash', 'fooBuffer', 4); +pipeline.hgetBuffer('hash', 'fooBuffer'); +pipeline.exec((err, results) => { + // `err` is always null, and `results` is an array of responses + // corresponding to the sequence of queued commands. + // Each response follows the format `[err, result]`. +}); + +// You can even chain the commands: +redis.pipeline().set('foo', 'bar').del('cc').exec((err, results) => { +}); + +// `exec` also returns a Promise: +const promise = redis.pipeline().set('foo', 'bar').get('foo').exec(); +promise.then((result) => { + // result === [[null, 'OK'], [null, 'bar']] +}); + +redis.pipeline().set('foo', 'bar').get('foo', (err, result) => { + // result === 'bar' +}).exec((err, result) => { + // result[1][1] === 'bar' +}); + +redis.pipeline([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec(() => { /* ... */ }); + +Redis.Command.setArgumentTransformer('set', args => { + return args; +}); + +Redis.Command.setReplyTransformer('get', (result: any) => { + return result; +}); + +// multi +redis.multi().set('foo', 'bar').set('foo', 'baz').get('foo', (err, result) => { + // result === 'QUEUED' +}).exec((err, results) => { + // results = [[null, 'OK'], [null, 'OK'], [null, 'baz']] +}); + +redis.multi([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec((err, results) => { + // results = [[null, 'OK'], [null, 'bar']] +}); + +redis.Promise.onPossiblyUnhandledRejection((error) => { +}); + +const keys = ['foo', 'bar']; +redis.mget(...keys); + +new Redis.Cluster([ + 'localhost' +]); + +new Redis.Cluster([ + 6379 +]); + +new Redis.Cluster([{ + host: 'localhost' +}]); + +new Redis.Cluster([{ + port: 6379 +}]); + +new Redis.Cluster([{ + host: 'localhost', + port: 6379 +}]); diff --git a/types/ioredis/v3/tsconfig.json b/types/ioredis/v3/tsconfig.json new file mode 100644 index 0000000000..eb6e042a5d --- /dev/null +++ b/types/ioredis/v3/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ioredis": [ "ioredis/v3" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ioredis-tests.ts" + ] +} diff --git a/types/ioredis/v3/tslint.json b/types/ioredis/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ioredis/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5e471f03c00b89ac358848e9cd66333466297f45 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Sun, 19 Aug 2018 12:37:29 -0700 Subject: [PATCH 059/289] [react-intl] More accurate injectIntl types Use Exclude to be able to correctly exclude intl prop from more complex type definitions that use nested Pick and the like. Also correctly type check the passed in component and do not accept ones that don't have Intl in their props definition. --- types/react-intl/index.d.ts | 6 ++---- types/react-intl/react-intl-tests.tsx | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 53b6de8a80..c1dff99d71 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -28,10 +28,8 @@ declare namespace ReactIntl { withRef?: boolean; } - type ComponentConstructor

= React.ComponentClass

| React.StatelessComponent

; - - function injectIntl

(component: ComponentConstructor

, options?: InjectIntlConfig): - React.ComponentClass

& { WrappedComponent: ComponentConstructor

}; + function injectIntl

(component: React.ComponentType

, options?: InjectIntlConfig): + React.ComponentClass>> & { WrappedComponent: React.ComponentType

}; function addLocaleData(data: Locale[] | Locale): void; diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index 782c4de889..b69c59bd74 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -32,7 +32,7 @@ interface SomeComponentProps { className: string; } -const SomeFunctionalComponentWithIntl: React.ComponentClass = injectIntl(({ +const SomeFunctionalComponentWithIntl: React.ComponentClass = injectIntl(({ intl: { formatDate, formatHTMLMessage, From 2df28b987367e8c93d93bbeac328a5c3bcd553d3 Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Mon, 20 Aug 2018 15:11:47 +0200 Subject: [PATCH 060/289] Added textTracks & remoteTextTracks to video.js --- types/video.js/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 0deb3d5a68..036aa1189b 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3764,6 +3764,18 @@ declare namespace videojs { autoplay(): boolean | string; + /** + * Get the remote {@link TextTrackList} + * @return The current remote text track list + */ + textTracks(): TextTrackList + + /** + * Get the remote {@link TextTrackList} + * @return The current remote text track list + */ + remoteTextTracks(): TextTrackList + /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will * automatically removed from the video element whenever the source changes, unless From 779fe35d1a51e3c0261587bc0a138c2bb5526fca Mon Sep 17 00:00:00 2001 From: felix-hoc Date: Tue, 21 Aug 2018 09:17:30 +0200 Subject: [PATCH 061/289] Update owners list. --- types/winston-syslog/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/winston-syslog/index.d.ts b/types/winston-syslog/index.d.ts index d1517cc957..b0409ad4c4 100644 --- a/types/winston-syslog/index.d.ts +++ b/types/winston-syslog/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for winston-syslog 2.0 // Project: https://github.com/winstonjs/winston-syslog -// Definitions by: Felix Hochgruber +// Definitions by: Chris Barth , Felix Hochgruber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Transport from 'winston-transport'; From ae72479ff03d3650c7b104b1e689f112381cda51 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 13:10:27 +0200 Subject: [PATCH 062/289] Cleanup, documentation and added regions --- types/chrome-apps/index.d.ts | 428 +++++++++++++++++++++++++++----- types/chrome-apps/test/index.ts | 92 +++++-- types/chrome-apps/webview.d.ts | 2 +- 3 files changed, 437 insertions(+), 85 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 321d5655c5..b3a4973426 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -26,6 +26,7 @@ // declare namespace chrome { + // #region internal ////////////// // INTERNAL // ////////////// @@ -68,6 +69,9 @@ declare namespace chrome { */ type double = number | 'double'; + // #endregion internal + + // #region chrome.accessibilityFeatures //////////////////////////// // Accessibility Features // //////////////////////////// @@ -224,7 +228,9 @@ declare namespace chrome { */ const animationPolicy: AccessibilityFeaturesSetting; } + // #endregion + // #region chrome.alarms //////////// // Alarms // //////////// @@ -318,7 +324,9 @@ declare namespace chrome { /** Fired when an alarm has elapsed. Useful for event pages. */ const onAlarm: AlarmEvent; } + // #endregion + // #region chrome.app.* ///////////////// // App Runtime // ///////////////// @@ -453,9 +461,9 @@ declare namespace chrome { const onRestarted: chrome.events.Event<() => void>; } - //////////////////// - // App Window - //////////////////// + //////////////// + // App Window // + //////////////// /** * @since Availability: Since Chrome 24. * @description @@ -544,6 +552,13 @@ declare namespace chrome { * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. */ type: 'none'; + /** + * @requires(dev) Chrome dev only + * @requires Permissions: 'app.window.alpha' + * @description + * Enable alpha on frame 'none' + */ + alphaEnabled?: boolean; } interface FrameOptionsChrome { /** @@ -641,6 +656,13 @@ declare namespace chrome { * @since Use of FrameOptions is new in M36. */ frame?: 'none' | 'chrome' | FrameOptions | FrameOptionsChrome; + /** + * @requires(dev) Chrome dev only + * @requires Permissions: 'app.window.alpha' + * @description + * Enable alpha on frame 'none' + */ + alphaEnabled?: boolean; /** * Size and position of the content in the window (excluding the titlebar). * If an id is also specified and a window with a matching id has been shown before, @@ -746,6 +768,11 @@ declare namespace chrome { setAlwaysOnTop: (alwaysOnTop: boolean) => void; /** Set whether the window is visible on all workspaces. (Only for platforms that support this). */ setVisibleOnAllWorkspaces: (alwaysVisible: boolean) => void; + /** + * @requires Permission: 'app.window.shape' + * Set window shape + */ + setShape: (rects: ContentBounds[]) => void; /** The JavaScript 'window' object for the created child. */ contentWindow: Window; /** The id the window was created with. */ @@ -830,7 +857,9 @@ declare namespace chrome { } const window: ChromeAppWindow; } + // #endregion chrome.app.* + // #region chrome.audio /////////// // Audio // /////////// @@ -952,7 +981,9 @@ declare namespace chrome { */ const onDeviceListChanged: chrome.events.Event<(devices: AudioDeviceInfo[]) => void>; } + // #endregion + // #region chrome.bluetooth* /////////////// // Bluetooth // /////////////// @@ -1843,7 +1874,9 @@ declare namespace chrome { */ const onReceiveError: OnReceiveErrorEvent; } + // #endregion + // #region chrome.browser ///////////// // Browser // ///////////// @@ -1878,7 +1911,9 @@ declare namespace chrome { */ function openTab(options: Options): void; } + // #endregion + // #region chrome.certificateProvider ////////////////////////// // Certificate Provider // ////////////////////////// @@ -1930,7 +1965,9 @@ declare namespace chrome { const onCertificatesRequested: chrome.events.Event<(param: any) => any>; const onSignDigestRequested: chrome.events.Event<(signRequest: SignRequestDigest, signCallback: Function) => any>; } + // #endregion + // #region chrome.clipboard /////////////// // Clipboard // /////////////// @@ -1978,7 +2015,9 @@ declare namespace chrome { */ const onClipboardDataChanged: chrome.events.Event<() => void>; } + // #endregion + // #region chrome.commands ////////////// // Commands // ////////////// @@ -2013,7 +2052,9 @@ declare namespace chrome { /** Fired when a registered command is activated using a keyboard shortcut. */ const onCommand: CommandEvent; } + // #endregion + // #region chrome.contextMenus /////////////////// // Context Menus // /////////////////// @@ -2292,9 +2333,10 @@ declare namespace chrome { /** Fired when a context menu item is clicked. */ const onClicked: MenuClickedEvent; - } + // #endregion + // #region chrome.desktopCapture ///////////////////// // Desktop Capture // ///////////////////// @@ -2327,7 +2369,9 @@ declare namespace chrome { */ function cancelChooseDesktopMedia(desktopMediaRequestId: integer): void; } + // #endregion + // #region chrome.diagnostics ///////////////// // Diagnostics // ///////////////// @@ -2339,7 +2383,9 @@ declare namespace chrome { /** @todo TODO PROPER DOCS */ function sendPacket(options: Object, callback: () => void): void; } + // #endregion + // #region chrome.displaySource //////////////////// // Display Source // //////////////////// @@ -2347,6 +2393,7 @@ declare namespace chrome { * @requires(dev) Development versions only * @requires Permissions: 'displaySource' * The *chrome.displaySource* API creates a Display session using WebMediaStreamTrack as sources. + * @todo TODO Finish documentation and typings */ namespace displaySource { /** @@ -2449,7 +2496,9 @@ declare namespace chrome { const onSessionTerminated: chrome.events.Event; const onSessionErrorOccured: chrome.events.Event; } + // #endregion + // #region chrome.dns ///////// // DNS // ///////// @@ -2477,7 +2526,9 @@ declare namespace chrome { */ function resolve(hostname: string, callback: (resolveInfo: ResolveCallbackResolveInfo) => void): void; } + // #endregion + // #region chrome.documentScan /////////////////// // Document Scan // /////////////////// @@ -2518,7 +2569,9 @@ declare namespace chrome { */ function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; } + // #endregion + // #region chrome.enterprise.* //////////////// // ENTERPRISE // //////////////// @@ -2695,7 +2748,9 @@ declare namespace chrome { */ function challengeUserKey(challenge: ArrayBuffer, registerKey: boolean, callback: (response: ArrayBuffer) => void): void; } + // #endregion chrome.enterprise.* + // #region chrome.events //////////// // Events // //////////// @@ -2878,11 +2933,12 @@ declare namespace chrome { priority?: integer; } } + // #endregion + // #region chrome.extensionTypes ///////////////////// // Extension Types // ///////////////////// - /** * Primary for extensions, but also used in apps. * https://developer.chrome.com/extensions/extensionTypes#type-ImageDetails @@ -2982,16 +3038,18 @@ declare namespace chrome { interface InjectCodeDetails extends _internal_.InjectDetailsBase { /** * JavaScript or CSS code to inject. - * **Warning** + * **⚠ 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} + * @see[More information]{@link https://en.wikipedia.org/wiki/Cross-site_scripting} */ code: string; } } + // #endregion + // #region chrome.fileBrowserHandle ///////////////////////// // File Browser Handle // ///////////////////////// @@ -3002,16 +3060,49 @@ declare namespace chrome { * @description * Use the chrome.fileBrowserHandler API to extend the Chrome OS file browser. * For example, you can use this API to enable users to upload files to your website. - * @see[Documentation]{@linkhttps://developer.chrome.com/extensions/fileBrowserHandler} + * @see[Documentation]{@link https://developer.chrome.com/extensions/fileBrowserHandler} */ namespace fileBrowserHandler { type FileBrowserHandleExecuteId = 'ReadOnly' | 'ReadWrite'; - const selectFile: Function; + interface SelectFileParameters { + /** Suggested name for the file. */ + suggestedName: string; + /** + * List of file extensions that the selected file can have. + * The list is also used to specify what files to be shown in the select file dialog. + * Files with the listed extensions are only shown in the dialog. + * Extensions should not include the leading '.'. + * @example ['jpg', 'png'] + */ + allowedFileExtensions?: string[]; + } + interface SelectionResult { + /** Selected file entry. It will be null if a file hasn't been selected. */ + entry: FileEntry | null; + /** Whether the file has been selected. */ + success: boolean; + } + /** + * Prompts user to select file path under which file should be saved. + * When the file is selected, file access permission required to use + * the file (read, write and create) are granted to the caller. + * The file will not actually get created during the function call, + * so function caller must ensure its existence before using it. + * The function has to be invoked with a user gesture. + * @param params Parameters that will be used while selecting the file. + * @param callback Function called upon completion. + */ + function selectFile(params: SelectFileParameters, callback: (result: SelectionResult) => void): void; + /** + * Fired when file system action is executed from ChromeOS file browser. + */ const onExecute: chrome.events.Event<(id: FileBrowserHandleExecuteId, details: { entries: Entry[] }) => void>; } + // #endregion + // #region chrome.fileSystem //////////////// // FileSystem // //////////////// @@ -3188,8 +3279,9 @@ declare namespace chrome { const onEntrychanged: chrome.events.Event; const onEntryRemoved: chrome.events.Event; } + // #endregion - + // #region chrome.fileSystemProvider ////////////////////////// // File System Provider // ////////////////////////// @@ -3951,7 +4043,9 @@ declare namespace chrome { errorCallback: (error: ToStringLiteral) => void ) => void>; } + // #endregion + // #region chrome.gcm //////////////////////////// // Google Cloud Messaging // //////////////////////////// @@ -4064,7 +4158,9 @@ declare namespace chrome { /** Fired when it was not possible to send a message to the GCM server. */ const onSendError: chrome.events.Event<(error: GcmError) => void>; } + // #endregion + // #region chrome.hid ///////// // HID // ///////// @@ -4270,7 +4366,9 @@ declare namespace chrome { */ const onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; } + // #endregion + // #region chrome.i18n ///////////////////////////////// // i18n - Internationalization // ///////////////////////////////// @@ -4687,7 +4785,9 @@ declare namespace chrome { */ const onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; } + // #endregion + // #region chrome.idle ////////// // Idle // ////////// @@ -4804,7 +4904,9 @@ declare namespace chrome { /** Fired when all the granted tokens need to be refreshed. */ const onTokenRefresh: chrome.events.Event<() => void>; } + // #endregion + // #region chrome.management //////////////// // Management // //////////////// @@ -4981,10 +5083,12 @@ declare namespace chrome { */ function uninstallSelf(options?: UninstallOptions, callback?: () => void): void; } + // #endregion - //////////////////// - // mDNS - //////////////////// + // #region chrome.mdns + ////////// + // mDNS // + ////////// /** * Use the chrome.mdns API to discover services over mDNS. * This comprises a subset of the features of the NSD spec: @@ -5033,10 +5137,12 @@ declare namespace chrome { const onServiceList: chrome.events.Event<(services: Service[]) => void>; } + // #endregion - //////////////////// - // Media Galleries - //////////////////// + // #region chrome.mediaGalleries + ///////////////////// + // 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). @@ -5096,7 +5202,7 @@ declare namespace chrome { */ type: string; /** - * An unfiltered string->string dictionary of tags for the stream. + * An unfiltered string->string interface of tags for the stream. */ tags: { [name: string]: string; }; } @@ -5269,12 +5375,17 @@ declare namespace chrome { */ const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } + // #endregion + // #region chrome.networking.* /////////////////////// // NETWORKING CONFIG // /////////////////////// /** - * + * @requires(CrOS) Chrome OS only. + * @requires Permissions: 'networking.config' + * @description + * Use the *networking.config* API to authenticate to captive portals. */ namespace networking.config { /** Indicator for the type of network used */ @@ -5310,7 +5421,7 @@ declare namespace chrome { SSID?: string; /** * The basic service set identification (BSSID) uniquely identifying the - * basic service set. BSSID is represented as a human readable, + * basic service set. *BSSID* is represented as a human readable, * hex-encoded string with bytes separated by colons, e.g. * 45:67:89:ab:cd:ef. */ @@ -5365,7 +5476,7 @@ declare namespace chrome { * @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 + * Most interface properties and type values use UpperCamelCase to match * the ONC specification instead of the JavaScript lowerCamelCase convention. */ namespace networking.onc { @@ -5914,7 +6025,7 @@ declare namespace chrome { * 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. + * @param callback Called with a interface of networks and their state properties when received. */ function getNetworks(filter: Filter, callback: (result: NetworkStateProperties[]) => void): void; /** @@ -5997,7 +6108,9 @@ declare namespace chrome { */ const onPortalDetectionCompleted: chrome.events.Event<(networkGuid: string, status: CaptivePortalStatus) => void>; } + // #endregion chrome.networking.* + // #region chrome.notifications /////////////////// // Notifications // /////////////////// @@ -6195,10 +6308,12 @@ declare namespace chrome { */ function getPermissionLevel(callback: (level: ToStringLiteral) => void): void; } + // #endregion - //////////////////// - // Permissions - //////////////////// + // #region chrome.permissions + ///////////////// + // Permissions // + ///////////////// /** * Use the chrome.permissions API to request declared optional permissions at run time rather than install time, * so users understand why the permissions are needed and grant only those that are necessary. @@ -6254,26 +6369,184 @@ declare namespace chrome { /** Fired when the app acquires new permissions. */ const onAdded: PermissionEvent; } + // #endregion + // #region chrome.platformKeys /////////////////// // Platform Keys // /////////////////// /** * @requires(CrOS) Only for Chrome OS. * @requires Permissions: 'platformKeys' - * @todo TODO Documentation needed + * @description + * Use the *chrome.platformKeys* API to access client certificates + * managed by the platform. If the user or policy grants the permission, an + * app can use such a certficate in its custom authentication protocol. + * E.g. this allows usage of platform managed certificates in third party VPNs + * @see chrome.vpnProvider */ namespace platformKeys { + /** + * @enum + */ const ClientCertificateType: { 'RSA_SIGN': 'rsaSign', 'ECDSA_SIGN': 'ecdsaSign' }; - const selectClientCertificates: Function; - const getKeyPair: Function; - const subtleCrypto: Function; - const verifyTLSServerCertificate: Function; - } + interface Match { + /** The DER encoding of a X.509 certificate. */ + certificate: ArrayBuffer; + /** + * @see[KeyAlgorithm]{@link http://www.w3.org/TR/WebCryptoAPI/#key-algorithm-interface} + * @description + * The KeyAlgorithm of the certified key. This contains algorithm + * parameters that are inherent to the key of the certificate (e.g. the key + * length). Other parameters like the hash function used by the sign + * function are not included. */ + keyAlgorithm: KeyAlgorithm; + }; + + /** + * Analogous to TLS1.1's CertificateRequest. + * @see{@link http://tools.ietf.org/html/rfc4346#section-7.4.4} + */ + interface ClientCertificateRequest { + /** + * This field is a list of the types of certificates requested, sorted in + * order of the server's preference. Only certificates of a type contained + * in this list will be retrieved. If *certificateTypes* is the + * empty list, however, certificates of any type will be returned. + * @see ClientCertificateType + */ + certificateTypes: ToStringLiteral; + + /** + * List of distinguished names of certificate authorities allowed by the + * server. Each entry must be a DER-encoded X.509 DistinguishedName. + */ + certificateAuthorities: ArrayBuffer[]; + }; + + interface SelectDetails { + /** Only certificates that match this request will be returned. */ + request: ClientCertificateRequest; + + /** + * If given, the *selectClientCertificates* operates on this + * list. Otherwise, obtains the list of all certificates from the platform's + * certificate stores that are available to this extensions. + * Entries that the extension doesn't have permission for or which doesn't + * match the request, are removed. + */ + clientCerts?: ArrayBuffer[]; + + /** If true, the filtered list is presented to the user to manually select a + * certificate and thereby granting the extension access to the + * certificate(s) and key(s).Only the selected certificate(s) will be + * returned. If is false, the list is reduced to all certificates that the + * extension has been granted access to (automatically or manually). */ + interactive: boolean; + }; + + interface VerificationDetails { + // Each chain entry must be the DER encoding of a X.509 certificate, the + // first entry must be the server certificate and each entry must certify + // the entry preceding it. + serverCertificateChain: ArrayBuffer[]; + + // The hostname of the server to verify the certificate for, e.g. the server + // that presented the *serverCertificateChain*. + hostname: string; + }; + + interface VerificationResult { + /** + * The result of the trust verification: true if trust for the given + * verification details could be established and false if trust is rejected + * for any reason* + */ + trusted: boolean; + + /** + * If the trust verification failed, this array contains the errors reported + * by the underlying network layer. Otherwise, this array is empty. + * **Note:** This list is meant for debugging only and may not + * contain all relevant errors. The errors returned may change in future + * revisions of this API, and are not guaranteed to be forwards or backwards + * compatible. + */ + debug_errors: string[]; + }; + + /** + * This function filters from a list of client certificates the ones that + * are known to the platform, match *request* and for which the + * app has permission to access the certificate and its private key. + * If *interactive* is true, the user is presented a dialog where + * they can select from matching certificates and grant the app access + * to the certificate. + * The selected / filtered client certificates will be passed to *callback*. + * @param callback Will provide *matches*: The list of certificates that match the request, that the + * app has permission for and, if *interactive* is true, that were selected by the user. + */ + function selectClientCertificates( + details: SelectDetails, + callback: (matches: Match[]) => void): void; + + /** + * @description + * Passes the key pair of *certificate* for usage with + * platformKeys.subtleCrypto to *callback*. + * + * ❗ Note: + * Currently, this function only supports the "RSASSA-PKCS1-v1_5" + * algorithm with one of the hashing algorithms "none", "SHA-1", "SHA-256", + * "SHA-384", and "SHA-512" + * + * @param certificate The certificate of a *Match* returned by *selectClientCertificates*. + * @param parameters Determines signature/hash algorithm parameters additionally to the parameters fixed by the key itself. + * The same parameters are accepted as by WebCrypto's importKey (see docs). + * function, e.g. *RsaHashedImportParams* for a RSASSA-PKCS1-v1_5 + * key. For RSASSA-PKCS1-v1_5 keys, additionally the parameters *{ + * "hash": { "name": "none" } }* are supported. The sign function will + * then apply PKCS#1 v1.5 padding and but not hash the given data. + * @param callback The public and private CryptoKey of a certificate which can only be used with *subleCrypto*. + * @param callback.privateKey Might be *null* if this app does not have access to it. + * @param callback.privateKey + * @see[WebCrypto's importKey docs]{@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-importKey} + * @see[CryptoKey docs]{@link http://www.w3.org/TR/WebCryptoAPI/#dfn-CryptoKey} + */ + function getKeyPair( + certificate: ArrayBuffer, + parameters: object, + callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void): void; + + /** + * An implementation of WebCrypto's SubtleCrypto + * that allows crypto operations on keys of client + * certificates that are available to this app. + * @see[SubtleCrypto]{@link http://www.w3.org/TR/WebCryptoAPI/#subtlecrypto-interface} + */ + function subtleCrypto(): SubtleCrypto; + + /** + * Checks whether *details.serverCertificateChain* can be trusted + * for *details.hostname* according to the trust settings of the + * platform. + * Note: The actual behavior of the trust verification is not fully + * specified and might change in the future. + * The API implementation verifies certificate expiration, validates the + * certification path and checks trust by a known CA. + * The implementation is supposed to respect the EKU serverAuth and to + * support subject alternative names. + */ + function verifyTLSServerCertificate(details: VerificationDetails, + callback: (result: VerificationResult) => void): void; + } + // #endregion + + // #region chrome.power /////////// // Power // /////////// @@ -6302,7 +6575,9 @@ declare namespace chrome { /** Releases a request previously made via requestKeepAwake(). */ function releaseKeepAwake(): void; } + // #endregion + // #region chrome.printerProvider ////////////////////// // Printer Provider // ////////////////////// @@ -6355,10 +6630,12 @@ declare namespace chrome { /** Event fired when print manager requests printing. */ const onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; } + // #endregion - //////////////////// - // Runtime - //////////////////// + // #region chrome.runtime + ///////////// + // Runtime // + ///////////// /** * Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. * @since Chrome 22 @@ -6569,7 +6846,6 @@ declare namespace chrome { type ChromeOSOnlyPermissions = /** * Gives your app access to the chrome.certificateProvider API. - * @todo TODO Implement API. */ 'certificateProvider' | /** Gives your app access to the chrome.clipboard API. */ @@ -6602,7 +6878,6 @@ declare namespace chrome { 'networking.config' | /** * Gives your app access to the chrome.platformKeys API. - * @todo TODO Implement API. */ 'platformKeys' | /** Gives your app access to the chrome.vpnProvider API. */ @@ -6612,29 +6887,28 @@ declare namespace chrome { FileSystemPermission; type DevOnly = - /** @todo TODO Implement API. */ + /** + * App window enable alpha on chrome.app.window + */ 'app.window.alpha' | /** * Gives your app access to the chrome.diagnostics API. - * @todo TODO Implement API. */ 'diagnostics' | - /** @todo TODO Implement API. */ 'displaySource'; type KioskOnlyPermissions = 'audio' | 'networking.onc' | - /** @todo TODO Implement API. */ 'system.powerSource' | - /** @todo TODO Document? */ 'virtualKeyboard'; /** Undocumented but used permissions */ type UndocumentedPermissions = /** @todo TODO Document these */ 'appview' | - 'app.window.shape' | // Works on stable + /** Works on stable, enables setShape() on chrome.app.window */ + 'app.window.shape' | 'alwaysOnTopWindows' | 'overrideEscFullscreen' | 'app.window.fullscreen' | @@ -7390,7 +7664,7 @@ declare namespace chrome { /** * If you publish using the Chrome Developer Dashboard, ignore this field. * If you host your own app: URL to an update manifest XML file. - * **Warning** + * **⚠ Warning** * As of M33, Windows stable / beta channel users can only * download apps hosted in the Chrome Web Store * @requires(not Windows) @@ -7725,7 +7999,9 @@ declare namespace chrome { */ const onBrowserUpdateAvailable: RuntimeEvent; } + // #endregion + // #region chrome.serial //////////// // Serial // //////////// @@ -7737,7 +8013,9 @@ declare namespace chrome { * @since Chrome 23 */ const serial: chrome.deprecated; + // #endregion + // #region chrome.socket //////////// // Socket // //////////// @@ -7749,8 +8027,16 @@ declare namespace chrome { * and sockets.tcpServer APIs. */ // const socket: chrome.deprecatedButUsable; // Removed to not be confused with chrome.sockets.* + // #endregion - /** chrome.sockets.tcp API */ + // #region chrome.sockets.* + //////////////////// + // Chrome Sockets // + //////////////////// + /** + * Use the chrome.sockets.* APIs to send and receive data over the network using TCP and UDP connections. + * @since Chrome 33. + */ namespace sockets { interface CreateInfo { /** @@ -8371,7 +8657,9 @@ declare namespace chrome { */ const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } + // #endregion chrome.sockets.* + // #region chrome.storage ///////////// // Storage // ///////////// @@ -8424,7 +8712,7 @@ declare namespace chrome { get(callback: (items: { [key: string]: any }) => void): void; /** * Gets one or more items from storage. - * @param keys A single key to get, list of keys to get, or a dictionary specifying default values. + * @param keys A single key to get, list of keys to get, or a interface specifying default values. * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. @@ -8487,9 +8775,11 @@ declare namespace chrome { /** Fired when one or more items change. */ const onChanged: StorageChangedEvent; } + // #endregion + // #region chrome.syncFileSystem //////////////////// - // SyncFileSystem + // SyncFileSystem // //////////////////// /** * Use the chrome.syncFileSystem API to save and synchronize data on Google Drive. @@ -8654,7 +8944,9 @@ declare namespace chrome { /** Fired when a file has been updated by the background sync service. */ const onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } + // #endregion + // #region chrome.system.* //////////////// // System CPU // @@ -9259,6 +9551,9 @@ declare namespace chrome { const onDetached: chrome.events.Event<(id: string) => void>; } + // #endregion chrome.system.* + + // #region chrome.tts //////////////////// // Text to Speech // //////////////////// @@ -9373,13 +9668,14 @@ declare namespace chrome { */ function resume(): void; } + // #endregion - //////////////////// - // Types - //////////////////// + // #region chrome.types + /////////// + // Types // + /////////// /** * The chrome.types API contains type declarations for Chrome. - * @since Chrome 13. */ namespace types { interface ChromeSettingClearDetails { @@ -9465,7 +9761,9 @@ declare namespace chrome { onChange: ChromeSettingChangedEvent; } } + // #endregion + // #region chrome.usb ///////// // USB // ///////// @@ -9939,7 +10237,9 @@ declare namespace chrome { */ const onDeviceRemoved: DeviceEvent; } + // #endregion + // #region chrome.virtualKeyboard ////////////////////// // Virtual Keyboard // ////////////////////// @@ -9981,7 +10281,9 @@ declare namespace chrome { */ function restrictFeatures(restrictions: FeatureRestrictions, callback?: (update: FeatureRestrictions) => void): void; } + // #endregion + // #region chrome.vpnProvider ////////////////// // VPN Provider // ////////////////// @@ -10103,7 +10405,9 @@ declare namespace chrome { */ const onUIEvent: VpnUiEvent; } + // #endregion + // #region chrome.wallpaper /////////////// // Wallpaper // /////////////// @@ -10141,10 +10445,9 @@ declare namespace chrome { */ function setWallpaper(details: WallpaperDetails, callback: (thumbnail?: string) => void): void; } + // #endregion - - - + // #region chrome.webRequest namespace webRequest { type ResourceType = 'main_frame' | 'sub_frame' | 'stylesheet' | @@ -10152,7 +10455,9 @@ declare namespace chrome { 'xmlhttprequest' | 'ping' | 'csp_report' | 'media' | 'websocket' | 'other'; } + // #endregion + // #region chrome.webViewRequest namespace webViewRequest { type Stage = 'onBeforeRequest' | 'onBeforeSendHeaders' | 'onHeadersReceived' | 'onAuthRequired'; type DeclarativeWebRequestEventList = @@ -10420,7 +10725,7 @@ declare namespace chrome { interface SendMessageParams { /** * The value that will be passed in the message attribute - * of the dictionary that is passed to the event handler. + * of the interface that is passed to the event handler. */ message: string; } @@ -10725,7 +11030,9 @@ declare namespace chrome { */ interface OnMessageEvent extends chrome.events.Event<(details: OnMessageEventDetails) => void> { } } + // #endregion + // #region placeholders ////////////////// // PLACEHOLDERS // ////////////////// @@ -10736,7 +11043,9 @@ declare namespace chrome { * @see[Documentation]{@link https://developer.chrome.com/apps/experimental} */ const experimental: any; + // #endregion + // #region classes ///////////// // CLASSES // ///////////// @@ -10749,6 +11058,9 @@ declare namespace chrome { new (): chrome.events.Event; } + // #endregion + + // #region methods ///////////// // METHODS // ///////////// @@ -10772,12 +11084,14 @@ declare namespace chrome { * @see[Deprecation article]{@link https://developers.google.com/web/updates/2017/12/chrome-loadtimes-deprecated} */ function loadTimes(): chrome.deprecatedButUsable; + + // #endregion } -///////////////////// -// EXPORT -///////////////////// +//////////// +// EXPORT // +//////////// interface Window { chrome: typeof chrome; - WebView: HTMLWebViewElement; + WebView: typeof HTMLWebViewElement; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 523ce4f757..a7cd89fbc1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -184,12 +184,13 @@ chrome.app.runtime.onLaunched.addListener(() => { }); }); -// FORBIDDEN APIs +// #region FORBIDDEN APIs document.write('forbidden'); Document.prototype.write.call(document, 'Hello, world'); window.addEventListener('beforeunload', () => { }); +// #endregion -// MANIFEST +// #region MANIFEST const ManifestJSONTest1: chrome.runtime.Manifest = { manifest_version: 2, @@ -498,12 +499,16 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { action_handlers: ["new_note"] } -// ALARMS +// #endregion + +// #region chrome.alarms chrome.alarms.create('name', { delayInMinutes: 10 }) +// #endregion +// #region chrome.bluetooth* // BLUETOOTH // BLUETOOTH SOCKET @@ -618,6 +623,8 @@ chrome.bluetooth.getDevices((devices) => { }); }); +// #endregion + // CERTIFICATE PROVIDER const requestId = 555; @@ -641,18 +648,22 @@ chrome.contextMenus.onClicked.addListener((info) => { }); -// DESKTOP CAPTURE - +// #region chrome.desktopCapture chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { }); chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { }); -// DNS +// #endregion + +// #region chrome.dns chrome.dns.resolve("github.com", (info) => { console.log([info.resultCode === 0, info.address]); }); +// #endregion + +// #region chrome.enterprise.* // ENTERPRISE - DEVICE ATTRIBUTES const deviceAttr = chrome.enterprise.deviceAttributes; @@ -672,13 +683,16 @@ if (chrome.enterprise.platformKeys.getTokens) { } } } +// #endregion chrome.enterprise -// EVENTS +// #region chrome.Event const e = new chrome.Event(); // Used const instead of class to be able to return the interface e.addListener(() => { }); -// HID +// #endregion + +// #region chrome.hid chrome.hid.getDevices({}, () => { }); chrome.hid.onDeviceAdded.addListener(() => { }); @@ -709,6 +723,9 @@ chrome.hid.getDevices({ }); }); +// #endregion + +// #region chrome.fileBrowserHandler // File Browser Handle chrome.fileBrowserHandler.onExecute.addListener((id, details) => { @@ -722,6 +739,9 @@ chrome.fileBrowserHandler.onExecute.addListener((id, details) => { }); }); +// #endregion + +// #region chrome.fileSystem // FILE SYSTEM // https://developer.chrome.com/apps/fileSystem @@ -750,8 +770,9 @@ function test_fileSystem(): void { chrome.fileSystem.isWritableEntry(entry, (isWritable: boolean) => { }); }); } +// #endregion -// IDENTITY +// #region chrome.identity chrome.identity.getAuthToken({ interactive: true }, (token) => { if (chrome.runtime.lastError) { @@ -760,7 +781,10 @@ chrome.identity.getAuthToken({ interactive: true }, (token) => { chrome.identity.removeCachedAuthToken({ token: token }, () => { }); }); -// MEDIA GALLERIES +// #endregion + +// #region chrome.mediaGalleries + chrome.fileSystem.getVolumeList((volumes) => { chrome.fileSystem.requestFileSystem({ volumeId: volumes[0].volumeId @@ -774,8 +798,16 @@ chrome.fileSystem.getVolumeList((volumes) => { }); }); +// #endregion -// MESSAGING +// #region chrome.power + +chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); +chrome.power.requestKeepAwake('display'); + +// #endregion + +// #region chrome.runtime chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => { sendResponse({ "result": "Ops, I don't understand this message" }); @@ -788,13 +820,6 @@ chrome.runtime.sendMessage( } ); -// POWER - -chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); -chrome.power.requestKeepAwake('display'); - -// RUNTIME - chrome.runtime.reload(); chrome.runtime.requestUpdateCheck((status, details) => { if (status === chrome.runtime.RequestUpdateCheckStatus.THROTTLED) { @@ -811,6 +836,9 @@ if (os === 'android') { } const appId = chrome.runtime.id; +// #endregion + +// #region chrome.sockets // SOCKETS // https://developer.chrome.com/apps/sockets_tcp function test_socketsTcp(): void { @@ -1068,8 +1096,9 @@ chrome.sockets.udp.create({}, (createInfo) => { }); }); -// SYNC FILE SYSTEM +// #endregion +// #region chrome.syncFileSystem chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { if (policy === 'manual') { @@ -1080,8 +1109,9 @@ chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { }); } }); +// #endregion -// SYSTEM APIs +// #region chrome.system.* function getPowerSourceInfo() { chrome.system.powerSource.getPowerSourceInfo(info => { @@ -1091,8 +1121,8 @@ function getPowerSourceInfo() { if (info.length === 1 && info[0].type !== chrome.system.powerSource.PowerSourceType.mains) { return false; } - })); -}, + }); +} function onPowerChanged() { chrome.system.powerSource.onPowerChanged.addListener(info => { @@ -1101,9 +1131,11 @@ function onPowerChanged() { } }); chrome.system.powerSource.requestStatusUpdate(); -}, +} -// TTS +// #endregion + +// #region chrome.tts chrome.tts.isSpeaking((isSpeaking) => { if (!isSpeaking) { @@ -1114,7 +1146,9 @@ chrome.tts.isSpeaking((isSpeaking) => { } }); -// USB +// #endregion + +// #region chrome.usb const devices: { [key: string]: chrome.usb.Device } = {}; chrome.usb.onDeviceAdded.addListener((device) => { @@ -1133,9 +1167,11 @@ chrome.usb.getUserSelectedDevices({ } }); -// WEBVIEW +// #endregion -let wve: HTMLWebViewElement = (document.getElementById('webview')); +// #region chrome.webViewRequest & WebView + +const wve = new window.WebView(); wve.name = 'test'; wve.src = 'https://github.com/DefinitelyTyped'; wve.allowtransparency = true; @@ -1208,3 +1244,5 @@ new chrome.webViewRequest.RequestMatcher({ }); wve.request.onRequest.addRules([rule]); + +// #endregion diff --git a/types/chrome-apps/webview.d.ts b/types/chrome-apps/webview.d.ts index 9b81f5821b..78defea9d9 100644 --- a/types/chrome-apps/webview.d.ts +++ b/types/chrome-apps/webview.d.ts @@ -639,7 +639,7 @@ declare namespace WebView { /** * The type of menu item. Defaults to 'normal' if not specified. */ - type?: chrome.contextMenus.ItemType; + type?: chrome.ToStringLiteral; /** * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. From d962f8b98f7b08c277a7a60722c852b4fea86a74 Mon Sep 17 00:00:00 2001 From: felix-hoc Date: Tue, 21 Aug 2018 13:20:15 +0200 Subject: [PATCH 063/289] Set Typescript version to 2.9 for old version (v1). --- types/winston-syslog/v1/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/winston-syslog/v1/index.d.ts b/types/winston-syslog/v1/index.d.ts index 816274ded8..b2d5ecfb90 100644 --- a/types/winston-syslog/v1/index.d.ts +++ b/types/winston-syslog/v1/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/indexzero/winston-syslog#readme // Definitions by: Chris Barth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 import * as winston from "winston"; export interface SyslogTransportOptions extends winston.GenericTextTransportOptions { From a86110373f32c6e1b591a5629df91f6541903b75 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 13:40:36 +0200 Subject: [PATCH 064/289] Updated permission list and also worked on vpnProvider --- types/chrome-apps/index.d.ts | 60 ++--- types/chrome-apps/test/index.ts | 390 +++++++++++++++++--------------- 2 files changed, 235 insertions(+), 215 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index b3a4973426..9b78e740b8 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -691,11 +691,12 @@ declare namespace chrome { */ singleton?: boolean; /** + * @requires Permissions: 'alwaysOnTopWindows' or 'app.window.alwaysOnTop' + * @description * If true, the window will stay above most other windows. * If there are multiple windows of this kind, the currently focused window will be in the foreground. - * @requires alwaysOnTopWindows-permission. - * Defaults to false. * Call setAlwaysOnTop() on the window to change this property after creation. + * @default false */ alwaysOnTop?: boolean; /** If true, the window will be focused when created. Defaults to true. */ @@ -6905,14 +6906,18 @@ declare namespace chrome { /** Undocumented but used permissions */ type UndocumentedPermissions = - /** @todo TODO Document these */ + /** Enable the tag. @todo Document this tag */ 'appview' | - /** Works on stable, enables setShape() on chrome.app.window */ - 'app.window.shape' | - 'alwaysOnTopWindows' | - 'overrideEscFullscreen' | - 'app.window.fullscreen' | - 'app.window.fullscreen.overrideEsc'; + /** + * @deprecated + * @see Permission: 'app.window.fullscreen' + */ + 'fullscreen' | + /** + * @deprecated + * @see Permission: 'app.window.fullscreen.overrideEsc' + */ + 'overrideEscFullscreen'; type NotAllowedAsOptionalPermissions = 'debugger' | @@ -6935,6 +6940,10 @@ declare namespace chrome { 'alarms' | /** Gives your app access to the chrome.audio API. */ 'audio' | + /** Enables the method *setAlwaysOnTop()* on chrome.app.window */ + 'alwaysOnTopWindows' | + /** Enables the method *setAlwaysOnTop()* on chrome.app.window */ + 'app.window.alwaysOnTop' | /** * In Chrome Apps, fullscreen is entered without prompting the user or providing exit instructions. * HTML5 fullscreen requires the app.window.fullscreen permission in the manifest. @@ -6945,6 +6954,8 @@ declare namespace chrome { /** That is also the behavior in Chrome Apps unless the app.window.fullscreen.overrideEsc * permission is used to enable the app to call preventDefault on keydown and keyup events. */ 'app.window.fullscreen.overrideEsc' | + /** Enables setShape() on chrome.app.window. Customize window shape. */ + 'app.window.shape' | /** * Requests that the app be granted permissions to capture audio * directly from the user's Microphone via the getUserMedia API. @@ -10345,17 +10356,6 @@ declare namespace chrome { dnsServer: string[]; } - /** @todo TODO Move to consts. Implement PlatformMessage enum & check usage of the other enums */ - interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> { } - - interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> { } - - interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> { } - - interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> { } - - interface VpnUiEvent extends chrome.events.Event<(event: ToStringLiteral, id?: string) => void> { } - /** * Creates a new VPN configuration that persists across multiple login sessions of the user. * @param name The name of the VPN configuration. @@ -10368,19 +10368,19 @@ declare namespace chrome { * @param id ID of the VPN configuration to destroy. * @param callback Called when the configuration is destroyed or if there is an error. */ - function destroyConfig(id: string, callback?: Function): void; + function destroyConfig(id: string, callback?: () => void): 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. */ - function setParameters(parameters: VpnSessionParameters, callback: Function): void; + function setParameters(parameters: VpnSessionParameters, callback: () => void): 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 Called when the packet is sent or if there is an error. */ - function sendPacket(data: ArrayBuffer, callback?: Function): void; + function sendPacket(data: ArrayBuffer, callback?: () => void): 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. @@ -10389,21 +10389,23 @@ declare namespace chrome { * @see enum VpnConnectionState * @param callback Called when the notification is complete or if there is an error. */ - function notifyConnectionStateChanged(state: ToStringLiteral, callback?: Function): void; + function notifyConnectionStateChanged(state: ToStringLiteral, callback?: () => void): void; + + /** @todo TODO Implement PlatformMessage enum & check usage of the other enums */ /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - const onPlatformMessage: VpnPlatformMessageEvent; + const onPlatformMessage: chrome.events.Event<(id: string, message: ToStringLiteral, error: string) => void>; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - const onPacketReceived: VpnPacketReceptionEvent; + const onPacketReceived: chrome.events.Event<(data: ArrayBuffer) => void>; /** Triggered when a configuration created by the extension is removed by the platform. */ - const onConfigRemoved: VpnConfigRemovalEvent; + const onConfigRemoved: chrome.events.Event<(id: string) => void>; /** Triggered when a configuration is created by the platform for the extension. */ - const onConfigCreated: VpnConfigCreationEvent; + const onConfigCreated: chrome.events.Event<(id: string, name: string, data: Object) => void>; /** * 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. */ - const onUIEvent: VpnUiEvent; + const onUIEvent: chrome.events.Event<(event: ToStringLiteral, id?: string) => void>; } // #endregion diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index a7cd89fbc1..542bfa67e1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,196 +1,13 @@ import runtime = chrome.app.runtime; const cwindow = chrome.app.window; -// APP.WINDOW - -// Test enums -cwindow.WindowType.PANEL; -cwindow.State.FULLSCREEN; - -const createOptions: chrome.app.CreateWindowOptions = { - id: 'My Window', - bounds: { - left: 0, - top: 0, - width: 640, - height: 480 - }, - resizable: true -}; - -//Create new window on app launch -chrome.app.runtime.onLaunched.addListener((launchData: runtime.LaunchData) => { - chrome.app.window.create('app/url', createOptions, (created_window: chrome.app.AppWindow) => { - return; - }); -}); - -chrome.app.runtime.onRestarted.addListener(() => { return; }); - -// retrieving windows -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(() => { return; }); -currentWindow.onClosed.addListener(() => { return; }); -currentWindow.onFullscreened.addListener(() => { return; }); -currentWindow.onMaximized.addListener(() => { return; }); -currentWindow.onMinimized.addListener(() => { return; }); -currentWindow.onRestored.addListener(() => { return; }); - -// check platform capabilities -var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(); - - - -// Sockets - - -function testSystemNetwork() { - chrome.system.network.getNetworkInterfaces((networkInterfaces) => { - var iface: chrome.system.network.NetworkInterface; - for (var i in networkInterfaces) { - iface = networkInterfaces[i]; - } - }); -} - -const gcmMessage = {}; -gcmMessage.data = { - /*goog: 'any', should not be allowed, and it is not :) */ - test: true -}; - - - -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.app.runtime.onEmbedRequested.addListener((request) => { - if (!request.data.message) { - request.allow('default.html'); - } else if (request.data.message == 'camera') { - request.allow('camera.html'); - } else { - request.deny(); - } -}); - -chrome.app.runtime.onLaunched.addListener(() => { - chrome.app.window.create('index.html', { - id: "test", - innerBounds: { - width: 900, - height: 1280, - }, - }); -}); - // #region FORBIDDEN APIs document.write('forbidden'); Document.prototype.write.call(document, 'Hello, world'); window.addEventListener('beforeunload', () => { }); // #endregion -// #region MANIFEST +// #region Manifest const ManifestJSONTest1: chrome.runtime.Manifest = { manifest_version: 2, @@ -501,6 +318,89 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { // #endregion +// #region chrome.app.window + +// Test enums +cwindow.WindowType.PANEL; +cwindow.State.FULLSCREEN; + +const createOptions: chrome.app.CreateWindowOptions = { + id: 'My Window', + bounds: { + left: 0, + top: 0, + width: 640, + height: 480 + }, + resizable: true +}; + +//Create new window on app launch +chrome.app.runtime.onLaunched.addListener((launchData: runtime.LaunchData) => { + chrome.app.window.create('app/url', createOptions, (created_window: chrome.app.AppWindow) => { + return; + }); +}); + +chrome.app.runtime.onRestarted.addListener(() => { return; }); + +// retrieving windows +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(() => { return; }); +currentWindow.onClosed.addListener(() => { return; }); +currentWindow.onFullscreened.addListener(() => { return; }); +currentWindow.onMaximized.addListener(() => { return; }); +currentWindow.onMinimized.addListener(() => { return; }); +currentWindow.onRestored.addListener(() => { return; }); + +// check platform capabilities +var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(); + +let serviceId: any = null; + +const runApp = () => { + var options: chrome.app.CreateWindowOptions = { + id: 'Bluetooth Sample App', + frame: 'none', + alphaEnabled: true, // Permission: 'app.window.alpha' + 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) => { + // Test setShape as provided by the permission 'app.window.shape' + theWindow.setShape([{ left: 100, top: 50, width: 50, height: 100 }]); + theWindow.setShape([{ left: 100, top: 50, width: 50, height: 100 }, + { left: 200, top: 100, width: 50, height: 50 }]); + 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); + +// #endregion + // #region chrome.alarms chrome.alarms.create('name', { @@ -508,6 +408,37 @@ chrome.alarms.create('name', { }) // #endregion +// #region chrome.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.app.runtime.onEmbedRequested.addListener((request) => { + if (!request.data.message) { + request.allow('default.html'); + } else if (request.data.message == 'camera') { + request.allow('camera.html'); + } else { + request.deny(); + } +}); + +chrome.app.runtime.onLaunched.addListener(() => { + chrome.app.window.create('index.html', { + id: "test", + innerBounds: { + width: 900, + height: 1280, + }, + }); +}); +// #endregion + // #region chrome.bluetooth* // BLUETOOTH @@ -625,7 +556,7 @@ chrome.bluetooth.getDevices((devices) => { // #endregion -// CERTIFICATE PROVIDER +// #region chrome.certificateProvider const requestId = 555; chrome.certificateProvider.requestPin({ signRequestId: requestId }, (codeVal: Object) => { @@ -638,7 +569,11 @@ chrome.certificateProvider.stopPinRequest({ signRequestId: requestId }, () => { } }); -// CONTEXT MENU +// #endregion + +// #region chrome.contextMenus + +chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT; chrome.contextMenus.onClicked.addListener((info) => { const isChecked = info.checked; @@ -647,6 +582,7 @@ chrome.contextMenus.onClicked.addListener((info) => { } }); +// #endregion // #region chrome.desktopCapture @@ -692,6 +628,16 @@ e.addListener(() => { }); // #endregion +// #region chrome.gcm + +const gcmMessage = {}; +gcmMessage.data = { + /*goog: 'any', should not be allowed, and it is not :) */ + test: true +}; + +// #endregion + // #region chrome.hid chrome.hid.getDevices({}, () => { }); @@ -725,6 +671,12 @@ chrome.hid.getDevices({ // #endregion +// #region chrome.i18n + +chrome.i18n.getMessage('click_here', ['string1', 'string2']); + +// #endregion + // #region chrome.fileBrowserHandler // File Browser Handle @@ -800,6 +752,62 @@ chrome.fileSystem.getVolumeList((volumes) => { // #endregion +chrome.networking.config; + +// #region chrome.networking.onc + +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' + } + } +} + +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; + }); + } +}); + +// #endregion + // #region chrome.power chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); @@ -841,6 +849,16 @@ const appId = chrome.runtime.id; // #region chrome.sockets // SOCKETS // https://developer.chrome.com/apps/sockets_tcp + +function testSystemNetwork() { + chrome.system.network.getNetworkInterfaces((networkInterfaces) => { + var iface: chrome.system.network.NetworkInterface; + for (var i in networkInterfaces) { + iface = networkInterfaces[i]; + } + }); +} + function test_socketsTcp(): void { var socketId: chrome.integer = 0; var properties: chrome.sockets.SocketProperties = {}; From a21aa0b7adee77e1e76d8b0014d8ee945885c745 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 13:47:47 +0200 Subject: [PATCH 065/289] Finished chrome.vpnProvider docs --- types/chrome-apps/index.d.ts | 44 ++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 9b78e740b8..6942188c7b 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -10305,6 +10305,29 @@ declare namespace chrome { * @since Chrome 43. */ namespace vpnProvider { + /** + * The enum is used by the platform to notify the client of the VPN session status. + * + * **'connected'** + * VPN configuration connected. + * **'disconnected'** + * VPN configuration disconnected. + * **'error'** + * An error occurred in VPN connection, for example a timeout. A description + * of the error is given as the error argument to *onPlatformMessage*. + * **'linkDown'** + * The default physical network connection is down. + * **'linkUp'** + * The default physical network connection is back up. + * **'linkChanged'** + * The default physical network connection changed, e.g. wifi->mobile. + * **'suspend'** + * The OS is preparing to suspend, so the VPN should drop its connection. + * The extension is not guaranteed to receive this event prior to suspending. + * **'resume'** + * The OS has resumed and the user has logged back in, so the VPN should try to reconnect. + * @enum + */ const PlatformMessage: { CONNECTED: 'connected', DISCONNECTED: 'disconnected', @@ -10315,10 +10338,29 @@ declare namespace chrome { SUSPEND: 'suspend', RESUME: 'resume' }; + /** + * The enum is used by the VPN client to inform the platform of its current state. + * This helps provide meaningful messages to the user. + * + * **'connected'** + * VPN connection was successful. + * **'failure'** + * VPN connection failed. + * @enum + */ const VpnConnectionState: { CONNECTED: 'connected', FAILURE: 'failure' }; + /** + * The enum is used by the platform to indicate the event that triggered *onUIEvent* + * + * **'showAddDialog'** + * Request the VPN client to show add configuration dialog to the user. + * **'showConfigureDialog'** + * Request the VPN client to show configuration settings dialog to the user. + * @enum + */ const UIEvent: { SHOW_ADD_DIALOG: 'showAddDialog', SHOW_CONFIGURE_DIALOG: 'showConfigureDialog' @@ -10391,8 +10433,6 @@ declare namespace chrome { */ function notifyConnectionStateChanged(state: ToStringLiteral, callback?: () => void): void; - /** @todo TODO Implement PlatformMessage enum & check usage of the other enums */ - /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ const onPlatformMessage: chrome.events.Event<(id: string, message: ToStringLiteral, error: string) => void>; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ From 8e1d4d6b9aec1c657c505e88ac1575f2615d2909 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 14:32:14 +0200 Subject: [PATCH 066/289] Finished certificateProvider docs --- types/chrome-apps/index.d.ts | 145 +++++++++++++++++++++++++++----- types/chrome-apps/test/index.ts | 14 ++- 2 files changed, 136 insertions(+), 23 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 6942188c7b..2593b2044d 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -587,7 +587,7 @@ declare namespace chrome { inactiveColor?: string; } - interface CreateWindowOptions { + interface CreateWindowOptions extends ContentBounds { /** * Id to identify the window. * @@ -663,6 +663,13 @@ declare namespace chrome { * Enable alpha on frame 'none' */ alphaEnabled?: boolean; + /** + * @requires frame = 'none' + * @requires Permissions: 'app.window.ime' + * @description + * Windows API - ime (No fullscreen window in kiosk mode) + */ + ime?: boolean; /** * Size and position of the content in the window (excluding the titlebar). * If an id is also specified and a window with a matching id has been shown before, @@ -1921,8 +1928,9 @@ declare namespace chrome { /** * @requires(CrOS) Chrome OS only. * @requires Permissions: 'certificateProvider' - * @description Provide certificates for authentication - * @todo TODO Finish documentation + * @description + * Use this API to expose certificates to the platform which + * can use these certificates for TLS authentications. */ namespace certificateProvider { /** @enum */ @@ -1933,38 +1941,130 @@ declare namespace chrome { 'SHA384': 'SHA384', 'SHA512': 'SHA512' }; - /** @enum */ + /** + * The type of code being requested by the extension with requestPin function. + * @enum + */ const PinRequestType: { 'PIN': 'PIN', 'PUK': 'PUK' }; - /** @enum */ + /** + * The types of errors that can be presented to the user through the requestPin function. + * @enum + */ const PinRequestErrorType: { 'INVALID_PIN': 'INVALID_PIN', 'INVALID_PUK': 'INVALID_PUK', 'MAX_ATTEMPTS_EXCEEDED': 'MAX_ATTEMPTS_EXCEEDED', 'UNKNOWN_ERROR': 'UNKNOWN_ERROR' }; - interface RequestOptions { + interface CertificateInfo { + /** + * Must be the DER encoding of a X.509 certificate. Currently, only + * certificates of RSA keys are supported. + */ + certificate?: ArrayBuffer; + /** + * Must be set to all hashes supported for this certificate. This app + * will only be asked for signatures of digests calculated with one of these + * hash algorithms. This should be in order of decreasing hash preference. + * @see Hash + */ + supportedHashes?: ToStringLiteral[]; + } + interface SignRequest { + /** + * The unique ID to be used by the app should it need to call a method + * that requires it, e.g. requestPin. + */ + signRequestId: integer; + /** The digest that must be signed */ + digest: ArrayBuffer; + /** @see Hash */ + hash: ToStringLiteral; + /** + * The DER encoding of a X.509 certificate. The app must sign + * *digest* using the associated private key. + */ + certificate: ArrayBuffer; + } + interface RequestPinDetails { + /** + * The ID given by Chrome in SignRequest. + */ signRequestId: number; - /** @see PinRequestType */ + /** + * The type of code requested. Default is PIN. + * @see PinRequestType + */ requestType?: ToStringLiteral; - /** @see PinRequestErrorType */ + /** + * The error template displayed to the user. This should be set if the + * previous request failed, to notify the user of the failure reason. + * @see PinRequestErrorType + */ errorType?: ToStringLiteral; + /** + * The number of attempts left. This is provided so that any UI can present + * this information to the user. Chrome is not expected to enforce this, + * instead stopPinRequest should be called by the app with + * errorType = MAX_ATTEMPTS_EXCEEDED when the number of pin requests is + * exceeded. + */ attemptsLeft?: number; } - interface CodeValue { + interface StopRequestPinDetails { + /** + * The ID given by Chrome in SignRequest + */ + signRequstId: number; + /** + * The error template. If present it is displayed to user. Intended to + * contain the reason for stopping the flow if it was caused by an error, + * e.g. MAX_ATTEMPTS_EXCEEDED. + * @see PinRequestErrorType + */ + errorType?: ToStringLiteral; + } + interface PinResponseDetails { userInput?: string; } - /** @todo TODO Test to find proper types */ - interface SignRequestDigest { - hash?: any; - certificate?: any; - } - function requestPin(opts: RequestOptions, callback: (codeValue: CodeValue) => void): void; - function stopPinRequest(opts: RequestOptions, callback: () => void): void; - const onCertificatesRequested: chrome.events.Event<(param: any) => any>; - const onSignDigestRequested: chrome.events.Event<(signRequest: SignRequestDigest, signCallback: Function) => any>; + /** + * Requests the PIN from the user. Only one ongoing request at a time is + * allowed. The requests issued while another flow is ongoing are rejected. + * It's the apps's responsibility to try again later if another flow is + * in progress. + * @param details Contains the details about the requested dialog. + * @param callback Is called when the dialog is resolved with the user input, or + * when the dialog request finishes unsuccessfully (e.g. the dialog was + * canceled by the user or was not allowed to be shown). + */ + function requestPin(details: RequestPinDetails, callback: (details?: PinResponseDetails) => void): void; + /** + * @description Stops the pin request started by the *requestPin* function. + * @param details Contains the details about the reason for stopping the request flow. + * @param callback To be used by Chrome to send to the app the status from + * their request to close PIN dialog for user. + */ + function stopPinRequest(details: StopRequestPinDetails, callback: () => void): void; + /** + * This event fires every time the browser requests the current list of + * certificates provided by this app. The app must call *reportCallback* + * exactly once with the current list of certificates. + */ + const onCertificatesRequested: chrome.events.Event<(certificates: CertificateInfo[], callback: (rejectedCertificates: ArrayBuffer[]) => void) => any>; + /** + * This event fires every time the browser needs to sign + * a message using a certificate provided by this app + * in reply to an *onCertificatesRequested* event. + * + * The app must sign the data in *request* using the + * appropriate algorithm and private key and return it by calling + * *reportCallback*. *reportCallback* must be called exactly once. + * @param request: Contains the details about the sign request. + */ + const onSignDigestRequested: chrome.events.Event<(signRequest: SignRequest, signCallback: (signature?: ArrayBuffer) => void) => any>; } // #endregion @@ -6906,6 +7006,7 @@ declare namespace chrome { /** Undocumented but used permissions */ type UndocumentedPermissions = + 'app.window.ime' | /** Enable the tag. @todo Document this tag */ 'appview' | /** @@ -10307,7 +10408,7 @@ declare namespace chrome { namespace vpnProvider { /** * The enum is used by the platform to notify the client of the VPN session status. - * + * * **'connected'** * VPN configuration connected. * **'disconnected'** @@ -10341,9 +10442,9 @@ declare namespace chrome { /** * The enum is used by the VPN client to inform the platform of its current state. * This helps provide meaningful messages to the user. - * + * * **'connected'** - * VPN connection was successful. + * VPN connection was successful. * **'failure'** * VPN connection failed. * @enum @@ -10354,7 +10455,7 @@ declare namespace chrome { }; /** * The enum is used by the platform to indicate the event that triggered *onUIEvent* - * + * * **'showAddDialog'** * Request the VPN client to show add configuration dialog to the user. * **'showConfigureDialog'** diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 542bfa67e1..edb705a7aa 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -318,12 +318,24 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { // #endregion -// #region chrome.app.window +// #region chrome.app.* // Test enums cwindow.WindowType.PANEL; cwindow.State.FULLSCREEN; +chrome.app.runtime.onLaunched.addListener(function () { + chrome.app.window.create('index.html', { + 'left': 10, + 'top': 10, + 'width': 400, + 'height': 500, + 'frame': 'none' + }, (win) => { + win.onClosed.addListener(() => { }); + }); +}); + const createOptions: chrome.app.CreateWindowOptions = { id: 'My Window', bounds: { From c927ce8c7a457cfe4bfa26cf51576b31407a6283 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 14:41:16 +0200 Subject: [PATCH 067/289] certificateProvider: Fixed typo and updated tests --- types/chrome-apps/index.d.ts | 19 +++++++------------ types/chrome-apps/test/index.ts | 22 ++++++++++++++++++++-- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 2593b2044d..ed039e9836 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1933,14 +1933,9 @@ declare namespace chrome { * can use these certificates for TLS authentications. */ namespace certificateProvider { - /** @enum */ - const Hash: { - 'MD5_SHA1': 'MD5_SHA1', - 'SHA1': 'SHA1', - 'SHA256': 'SHA256', - 'SHA384': 'SHA384', - 'SHA512': 'SHA512' - }; + /** Hash type */ + type Hash = 'MD5_SHA1' | 'SHA1' | 'SHA256' | 'SHA384' | 'SHA512'; + /** * The type of code being requested by the extension with requestPin function. * @enum @@ -1971,7 +1966,7 @@ declare namespace chrome { * hash algorithms. This should be in order of decreasing hash preference. * @see Hash */ - supportedHashes?: ToStringLiteral[]; + supportedHashes?: Hash[]; } interface SignRequest { /** @@ -1981,8 +1976,8 @@ declare namespace chrome { signRequestId: integer; /** The digest that must be signed */ digest: ArrayBuffer; - /** @see Hash */ - hash: ToStringLiteral; + /** Refers to the hash algorithm that was used to create *digest*. */ + hash: Hash; /** * The DER encoding of a X.509 certificate. The app must sign * *digest* using the associated private key. @@ -2018,7 +2013,7 @@ declare namespace chrome { /** * The ID given by Chrome in SignRequest */ - signRequstId: number; + signRequestId: number; /** * The error template. If present it is displayed to user. Intended to * contain the reason for stopping the flow if it was caused by an error, diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index edb705a7aa..99444493a2 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -571,8 +571,10 @@ chrome.bluetooth.getDevices((devices) => { // #region chrome.certificateProvider const requestId = 555; -chrome.certificateProvider.requestPin({ signRequestId: requestId }, (codeVal: Object) => { - codeVal +chrome.certificateProvider.requestPin({ signRequestId: requestId }, (codeVal) => { + if (codeVal) { + return codeVal.userInput; + } }); chrome.certificateProvider.stopPinRequest({ signRequestId: requestId }, () => { @@ -581,6 +583,22 @@ chrome.certificateProvider.stopPinRequest({ signRequestId: requestId }, () => { } }); +chrome.certificateProvider.onCertificatesRequested.addListener((certifictes, callback) => { + for (const cert of certifictes) { + if (cert.supportedHashes !== undefined && cert.certificate !== undefined) { + cert.supportedHashes.map(hash => { + return [hash, cert.certificate]; + }); + } + } +}); + +chrome.certificateProvider.onSignDigestRequested.addListener((signRequest, signCallback) => { + if (signRequest.hash == 'SHA1') { + signCallback(signRequest.certificate); + } +}); + // #endregion // #region chrome.contextMenus From 90920faf152b4107bbad74b939da24dd6ce6d2d2 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 14:48:16 +0200 Subject: [PATCH 068/289] networking.config tests + docs --- types/chrome-apps/index.d.ts | 2 +- types/chrome-apps/test/index.ts | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index ed039e9836..f8e8945fca 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5547,7 +5547,7 @@ declare namespace chrome { */ function setNetworkFilter(networks: Array, callback: () => void): void; /** - * Called by the extension to notify the network config API that it finished + * Called by the app to notify the network config API that it finished * a captive portal authentication attempt and hand over the result of the attempt. * This function must only be called with the GUID of the latest *onCaptivePortalDetected* event. * @param GUID Unique network identifier obtained from *onCaptivePortalDetected*. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 99444493a2..3224db5917 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -782,7 +782,16 @@ chrome.fileSystem.getVolumeList((volumes) => { // #endregion -chrome.networking.config; +// #region chrome.networking.config + +const filter: chrome.networking.config.NetworkInfoFilterHexSSID = { + HexSSID: '11:11:11:11:11:00' +} + +chrome.networking.config.setNetworkFilter([filter], () => { }); +chrome.networking.config.finishAuthentication(filter.HexSSID || '', 'rejected'); + +// #endregion // #region chrome.networking.onc From 7bc8daacc248c7658f1d032200121ddf8a8aaae6 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 16:42:45 +0200 Subject: [PATCH 069/289] Cleanup + better chrome.system.display --- types/chrome-apps/index.d.ts | 155 ++++++++++++++++++++++++++------ types/chrome-apps/test/index.ts | 69 ++++++++++++-- 2 files changed, 190 insertions(+), 34 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index f8e8945fca..7ee2419d6c 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -54,7 +54,7 @@ declare namespace chrome { * Chrome uses JS number, but internally requires an integer or double. * This is a helper type to prevent mixup. */ - type integer = number | 'integer'; + type integer = number; // | 'integer'; /// /// BigInt is supported in Chrome now, but not in the api. @@ -67,7 +67,7 @@ declare namespace chrome { * Chrome uses JS number, but internally requires an integer or double. * This is a helper type to prevent mixup. */ - type double = number | 'double'; + type double = number; // | 'double'; // #endregion internal @@ -2078,9 +2078,19 @@ declare namespace chrome { * @see[Docs]{@link https://developer.chrome.com/apps/clipboard} */ namespace clipboard { + /** Image type */ + type ImageType = 'png' | 'jpeg'; + /** @enum */ + const DataItemType: { + TEXT_PLAIN: 'textPlain', + TEXT_HTML: 'textHtml' + } interface AdditionalItems { - /** Type of the additional data item. */ - type: 'textPlain' | 'textHtml'; + /** + * Type of the additional data item. + * @see DataItemType + */ + type: ToStringLiteral; /** * Content of the additional data item. * Either the plain text string if *type* is 'textPlain' or @@ -2092,15 +2102,15 @@ declare namespace chrome { /** * **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 imageData The encoded image data. *Since Chrome 70. Warning: this is the current Beta channel.* + * @param type The type of image being passed. *Since Chrome 70. 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.* + * *Since Chrome 70. Warning: this is the current Beta channel.* * @param [callback] */ - function setImageData(imageData: ArrayBuffer, type: 'png' | 'jpeg', additionalItems?: AdditionalItems, callback?: () => void): void; + function setImageData(imageData: ArrayBuffer, type: ImageType, additionalItems?: AdditionalItems, callback?: () => void): void; /** * **Dev channel only.** @@ -5555,6 +5565,17 @@ declare namespace chrome { * @param [callback] Called back when this operation is finished. */ function finishAuthentication(GUID: string, result: ToStringLiteral, callback?: () => void): void; + /** + * This event fires everytime a captive portal is detected on a network + * matching any of the currently registered network filters and the user + * consents to use the extension for authentication. Network filters may be + * set using the *setNetworkFilter*. + * Upon receiving this event the extension should start its authentication + * attempt with the captive portal. When the extension finishes its attempt, + * it must call *finishAuthentication* with the *GUID*. + * received with this event and the appropriate authentication result. + * @param networkInfo Information about the network on which a captive portal was detected. + */ const onCaptivePortalDetected: chrome.events.Event<(networkInfo: NetworkInfo) => void>; } @@ -6501,7 +6522,7 @@ declare namespace chrome { * length). Other parameters like the hash function used by the sign * function are not included. */ keyAlgorithm: KeyAlgorithm; - }; + } /** * Analogous to TLS1.1's CertificateRequest. @@ -6522,7 +6543,7 @@ declare namespace chrome { * server. Each entry must be a DER-encoded X.509 DistinguishedName. */ certificateAuthorities: ArrayBuffer[]; - }; + } interface SelectDetails { /** Only certificates that match this request will be returned. */ @@ -6543,7 +6564,7 @@ declare namespace chrome { * returned. If is false, the list is reduced to all certificates that the * extension has been granted access to (automatically or manually). */ interactive: boolean; - }; + } interface VerificationDetails { // Each chain entry must be the DER encoding of a X.509 certificate, the @@ -6554,7 +6575,7 @@ declare namespace chrome { // The hostname of the server to verify the certificate for, e.g. the server // that presented the *serverCertificateChain*. hostname: string; - }; + } interface VerificationResult { /** @@ -6573,7 +6594,7 @@ declare namespace chrome { * compatible. */ debug_errors: string[]; - }; + } /** * This function filters from a list of client certificates the ones that @@ -9184,6 +9205,12 @@ declare namespace chrome { /** The display mode device scale factor. */ deviceScaleFactor: integer; + /** + * The display mode refresh rate in hertz. + * @since Chrome 67 + */ + refreshRate: double; + /** True if the mode is the display's native mode. */ isNative: boolean; @@ -9241,6 +9268,8 @@ declare namespace chrome { /** * @requires(CrOS) Chrome OS only. + * @deprecated Deprecated since Chrome 68. Use *setMirrorMode* + * @see setMirrorMode * @description * If set and not empty, enables mirroring for this display. * Otherwise disables mirroring for this display. @@ -9294,6 +9323,16 @@ declare namespace chrome { * @since Chrome 52 */ displayMode?: DisplayMode; + + /** + * @since Chrome 65. + * @description + * If set, updates the zoom associated with the display. + * This zoom performs re-layout and repaint thus resulting + * in a better quality zoom than just performing + * a pixel by pixel stretch enlargement. + */ + displayZoomFactor?: double; } /** @@ -9315,8 +9354,39 @@ declare namespace chrome { id: string; /** The user-friendly name (e.g. 'HP LCD monitor'). */ name: string; - /** Identifier of the display that is being mirrored on the display unit. If mirroring is not in progress, set to an empty string. Currently exposed only on ChromeOS. Will be empty string on other platforms. */ + /** + * @requires(CrOS Kiosk app) Only available in Chrome OS Kiosk apps + */ + edid?: { + /** + * 3 character manufacturer code. + */ + manufacturerId: string; + /** + * 2 byte manufacturer-assigned code. + */ + productId: string; + /** + * Year of manufacturer. + */ + yearOfManufacture?: string; + } + /** + * @requires(CrOS) Only working properly on Chrome OS. + * Identifier of the display that is being mirrored on the display unit. + * If mirroring is not in progress, set to an empty string + * Currently exposed only on ChromeOS. + * Will be empty string on other platforms. + */ mirroringSourceId: string; + /** + * @requires(CrOS) Only available on Chrome OS. + * Identifiers of the displays to which the source display is being mirrored. + * Empty if no displays are being mirrored. This will be set to the same value + * for all displays. + * ❗ This must not include *mirroringSourceId*. ❗ + */ + mirroringDestinationIds: string[]; /** True if this is the primary display. */ isPrimary: boolean; /** True if this is an internal display. */ @@ -9335,22 +9405,42 @@ declare namespace chrome { overscan: Insets; /** The usable work area of the display within the display bounds. The work area excludes areas of the display reserved for OS, for example taskbar and launcher. */ workArea: Bounds; + /** + * @requires(CrOS) Only available on Chrome OS. + * The list of available display modes. + * The current mode will have isSelected=true. + * Only available on Chrome OS. + * Will be set to an empty array on other platforms. + */ + modes: DisplayMode[]; + /** True if this display has a touch input device associated with it. */ + hasTouchSupport: boolean; + /** A list of zoom factor values that can be set for the display. */ + availableDisplayZoomFactors: double[]; + /** + * The ratio between the display's current and default zoom. + * For example, value 1 is equivalent to 100% zoom, and value 1.5 is equivalent to 150% zoom. + * */ + displayZoomFactor: double; } - /** 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**. */ - interface DisplayProps { - /** If set and not empty, starts mirroring between this and the display with the provided id (the system will determine which of the displays is actually mirrored). If set and not empty, stops mirroring between this and the display with the specified id (if mirroring is in progress). If set, no other parameter may be set. */ + interface MirrorModeInfo { + /** + * The mirror mode that should be set. + * **off** + * Use the default mode (extended or unified desktop). + * **normal** + * The default source display will be mirrored to all other displays. + * **mixed** + * The specified source display will be mirrored to the provided destination displays. All other connected displays will be extended. + */ + mode?: 'off' | 'normal' | 'mixed'; + } + interface MirrorModeInfoMixed extends MirrorModeInfo { + mode: 'mixed'; mirroringSourceId?: string; - /** If set to true, makes the display primary. No-op if set to false. */ - isPrimary?: boolean; - /** If set, sets the display's overscan insets to the provided values. Note that overscan values may not be negative or larger than a half of the screen's size. Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. */ - overscan?: Insets; - /** If set, updates the display's rotation. Legal values are [0, 90, 180, 270]. The rotation is set clockwise, relative to the display's vertical position. It's applied after overscan paramter. */ - rotation?: integer; - /** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */ - boundsOriginX?: integer; - /** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */ - boundsOriginY?: integer; + /** The ids of the mirroring destination displays. */ + mirroringDestinationIds?: string[]; } /** @@ -9482,6 +9572,17 @@ declare namespace chrome { */ function clearTouchCalibration(id: string): void; + /** + * @requires(CrOS Kiosk app) Chrome OS Kiosk apps only + * @since Chrome 65. + * @description + * Sets the display mode to the specified mirror mode. + * Each call resets the state from previous calls. + * Calling setDisplayProperties() will fail for the + * mirroring destination displays. + */ + function setMirrorMode(info: MirrorModeInfo | MirrorModeInfoMixed, callback: () => void): void; + /** * Fired when anything changes to the display configuration. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 3224db5917..2a98bbea7f 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -318,6 +318,13 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { // #endregion +// #region chrome.alarms + +chrome.alarms.create('name', { + delayInMinutes: 10 +}) +// #endregion + // #region chrome.app.* // Test enums @@ -413,13 +420,6 @@ chrome.app.runtime.onRestarted.addListener(runApp); // #endregion -// #region chrome.alarms - -chrome.alarms.create('name', { - delayInMinutes: 10 -}) -// #endregion - // #region chrome.audio chrome.audio.getDevices({}, (audioDeviceInfoList) => { @@ -568,6 +568,13 @@ chrome.bluetooth.getDevices((devices) => { // #endregion +// #region chrome.browser + +chrome.browser.openTab({ url: 'https://github.com' }); +chrome.browser.openTab({ url: 'https://github.com' }, () => { }); + +// #endregion + // #region chrome.certificateProvider const requestId = 555; @@ -601,6 +608,54 @@ chrome.certificateProvider.onSignDigestRequested.addListener((signRequest, signC // #endregion +// #region chrome.clipboard + +const copyTextData = (text: string) => { + var input = document.getElementById('copy_text') as HTMLInputElement || new HTMLInputElement(); + input.value = text; + input.focus(); + input.select(); + if (document.execCommand('Copy')) + return true; +} +copyTextData('FooBar'); +copyTextData('GitHub'); + +function setImageDataClipboard( + imageUrl: string, + imageType: chrome.clipboard.ImageType, + additionalItems?: chrome.clipboard.AdditionalItems) { + var oReq = new XMLHttpRequest(); + oReq.open('GET', imageUrl, true); + oReq.responseType = 'arraybuffer'; + oReq.onload = (oEvent) => { + var arrayBuffer = oReq.response; + if (arrayBuffer) { + if (additionalItems) { + chrome.clipboard.setImageData(arrayBuffer, imageType, additionalItems, + () => { + return; + }); + } else { + chrome.clipboard.setImageData(arrayBuffer, imageType); + } + } else { + console.error('Failed to load the image file'); + } + }; + oReq.send(undefined); +} + +setImageDataClipboard('/icon1.png', 'png'); +setImageDataClipboard('/test.jpg', 'jpeg'); +setImageDataClipboard('/redirect_target.gif', 'jpeg'); +setImageDataClipboard('/redirect_target.jpg', 'jpeg', { + data: '

Lorem Ipsum...

', + type: 'textHtml' +}); + +// #endregion + // #region chrome.contextMenus chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT; From 8578b6055326d363574e1b6c7293a236041046e9 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 16:46:50 +0200 Subject: [PATCH 070/289] chrome.system.cpu updates --- types/chrome-apps/index.d.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 7ee2419d6c..fe3bd2376e 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -9087,13 +9087,13 @@ declare namespace chrome { namespace system.cpu { interface ProcessorUsage { /** The cumulative time used by userspace programs on this processor. */ - user: integer; + user: double; /** The cumulative time used by kernel programs on this processor. */ - kernel: integer; + kernel: double; /** The cumulative time spent idle by this processor. */ - idle: integer; + idle: double; /** The total cumulative time for this processor. This value is equal to user + kernel + idle. */ - total: integer; + total: double; } interface ProcessorInfo { @@ -9112,9 +9112,16 @@ declare namespace chrome { * A set of feature codes indicating some of the processor's capabilities. * The currently supported codes are 'mmx', 'sse', 'sse2', 'sse3', 'ssse3', 'sse4_1', 'sse4_2', and 'avx'. */ - features: string[]; + features: 'mmx' | 'sse' | 'sse2' | 'sse3' | 'ssse3' | 'sse4_1' | 'sse4_2' | 'avx'; /** Information about each logical processor. */ processors: ProcessorInfo[]; + /** + * @requires(CrOS) Currently supported on Chrome OS only. + * @description + * List of CPU temperature readings from each thermal zone of the CPU. + * Temperatures are in degrees Celsius. + */ + temperatures?: double[]; } /** Queries basic CPU information of the system. */ From 0453c577062f16e9302a710f9ebfd97c83013bcc Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 16:48:37 +0200 Subject: [PATCH 071/289] chrome.system.memory & chrome.system.network fixes and docs update --- types/chrome-apps/index.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index fe3bd2376e..26f66a0f4c 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -9607,9 +9607,9 @@ declare namespace chrome { namespace system.memory { interface MemoryInfo { /** The total amount of physical memory capacity, in bytes. */ - capacity: integer; + capacity: double; /** The amount of available capacity, in bytes. */ - availableCapacity: integer; + availableCapacity: double; } /** Get physical memory information. */ @@ -9625,11 +9625,14 @@ declare namespace chrome { */ namespace system.network { interface NetworkInterface { + /** The underlying name of the adapter. On *nix, this will typically be "eth0", "wlan0", etc. */ name: string; + /** The available IPv4/6 address. */ address: string; + /** The prefix length */ prefixLength: integer; } - + /** Retrieves information about local adapters on this system. */ function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } From b4631a0448f3bd98ba14346f91c14edcea0e189e Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 21 Aug 2018 16:58:22 +0200 Subject: [PATCH 072/289] Organizing and cleanup + added test todos --- types/chrome-apps/index.d.ts | 4 ++ types/chrome-apps/test/index.ts | 96 +++++++++++++++++---------------- 2 files changed, 53 insertions(+), 47 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 26f66a0f4c..680aa5e2ae 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -4734,7 +4734,9 @@ declare namespace chrome { */ function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; } + // #endregion + // #region chrome.identity ////////////// // Identity // ////////////// @@ -4932,7 +4934,9 @@ declare namespace chrome { */ const onStateChanged: chrome.events.Event<(newState: IdleState) => void>; } + // #endregion + // #region chrome.instanceID //////////////// // InstanceID // //////////////// diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 2a98bbea7f..b9ad34fd0b 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -684,6 +684,8 @@ chrome.dns.resolve("github.com", (info) => { // #endregion +chrome.documentScan; // @todo TODO Tests + // #region chrome.enterprise.* // ENTERPRISE - DEVICE ATTRIBUTES @@ -713,6 +715,53 @@ e.addListener(() => { }); // #endregion +// #region chrome.fileBrowserHandler +// File Browser Handle + +chrome.fileBrowserHandler.onExecute.addListener((id, details) => { + chrome.fileBrowserHandler.selectFile( + { + suggestedName: 'some_file_name.txt', + allowedFileExtensions: ['txt', 'html'] + }, + (result) => { + console.log(result.entry); + }); +}); + +// #endregion + +// #region chrome.fileSystem +// FILE SYSTEM +// https://developer.chrome.com/apps/fileSystem + +function test_fileSystem(): void { + var accepts: chrome.fileSystem.AcceptOptions[] = [ + { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] } + ]; + var chooseOption: chrome.fileSystem.ChooseEntryOptions = { + type: 'openFile', + suggestedName: 'foo.txt', + accepts: accepts, + acceptsAllTypes: false, + acceptsMultiple: false + }; + chrome.fileSystem.chooseEntry(chooseOption, (entry: Entry) => { + chrome.fileSystem.getDisplayPath(entry, (displayPath: string) => { }); + + var retainedId = chrome.fileSystem.retainEntry(entry); + chrome.fileSystem.isRestorable(retainedId, (isRestorable: boolean) => { + if (isRestorable) { + chrome.fileSystem.restoreEntry(retainedId, (restoredEntry: Entry) => { }); + } + }); + + chrome.fileSystem.getWritableEntry(entry, (writableEntry: Entry) => { }); + chrome.fileSystem.isWritableEntry(entry, (isWritable: boolean) => { }); + }); +} +// #endregion + // #region chrome.gcm const gcmMessage = {}; @@ -762,53 +811,6 @@ chrome.i18n.getMessage('click_here', ['string1', 'string2']); // #endregion -// #region chrome.fileBrowserHandler -// File Browser Handle - -chrome.fileBrowserHandler.onExecute.addListener((id, details) => { - chrome.fileBrowserHandler.selectFile( - { - suggestedName: 'some_file_name.txt', - allowedFileExtensions: ['txt', 'html'] - }, - (result) => { - console.log(result.entry); - }); -}); - -// #endregion - -// #region chrome.fileSystem -// FILE SYSTEM -// https://developer.chrome.com/apps/fileSystem - -function test_fileSystem(): void { - var accepts: chrome.fileSystem.AcceptOptions[] = [ - { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] } - ]; - var chooseOption: chrome.fileSystem.ChooseEntryOptions = { - type: 'openFile', - suggestedName: 'foo.txt', - accepts: accepts, - acceptsAllTypes: false, - acceptsMultiple: false - }; - chrome.fileSystem.chooseEntry(chooseOption, (entry: Entry) => { - chrome.fileSystem.getDisplayPath(entry, (displayPath: string) => { }); - - var retainedId = chrome.fileSystem.retainEntry(entry); - chrome.fileSystem.isRestorable(retainedId, (isRestorable: boolean) => { - if (isRestorable) { - chrome.fileSystem.restoreEntry(retainedId, (restoredEntry: Entry) => { }); - } - }); - - chrome.fileSystem.getWritableEntry(entry, (writableEntry: Entry) => { }); - chrome.fileSystem.isWritableEntry(entry, (isWritable: boolean) => { }); - }); -} -// #endregion - // #region chrome.identity chrome.identity.getAuthToken({ interactive: true }, (token) => { From 328448882545bd381ff035858fe2a741c724d027 Mon Sep 17 00:00:00 2001 From: Joel Rosinbum Date: Tue, 21 Aug 2018 14:23:50 -0500 Subject: [PATCH 073/289] Add jsGraph Type --- types/jsgraph/index.d.ts | 174 +++++++++++++++++++++++++++++++++ types/jsgraph/jsgraph-tests.ts | 43 ++++++++ types/jsgraph/tsconfig.json | 24 +++++ types/jsgraph/tslint.json | 79 +++++++++++++++ 4 files changed, 320 insertions(+) create mode 100644 types/jsgraph/index.d.ts create mode 100644 types/jsgraph/jsgraph-tests.ts create mode 100644 types/jsgraph/tsconfig.json create mode 100644 types/jsgraph/tslint.json diff --git a/types/jsgraph/index.d.ts b/types/jsgraph/index.d.ts new file mode 100644 index 0000000000..fe4fa42e2f --- /dev/null +++ b/types/jsgraph/index.d.ts @@ -0,0 +1,174 @@ +// Type definitions for jsgraph 0.7 +// Project: https://github.com/Encapsule/jsgraph +// Definitions by: Joel Rosinbum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace jsgraph { + + interface jsGraphStatic { + directed: Directed; + } + + export interface VertexRequest { + u: string; + p: any + } + + export interface JsGraphResponse { + error?: any; + result?: any; + } + + export interface Edge { + u: string; + v: string + } + + export interface EdgeRequest { + e: Edge; + p: any; + } + + export interface DirectedGraph { + new(): DirectedGraph; + + setGraphName(name: string): JsGraphResponse; + + getGraphName(): string; + + setGraphDescription(description: string): JsGraphResponse; + + getGraphDescription(): string; + + verticesCount(): number; + + getVertices(): string[]; + + getEdgeCount(): number; + + getEdeges(): Edge[]; + + rootVerticesCount(): number; + + getRootVertices(): string[]; + + leafVerticesCount(): number; + + getLeafVertices(): string[]; + + toObject(): string; + + toJSON(): string; + + stringify(replacer: Function, space?: number): string; + + fromObject(graph: any): JsGraphResponse; + + + //Vertex functions + addVertex(vertex: VertexRequest): JsGraphResponse; + + removeVertex(vertex: string): boolean; + + getVertexProperty(vertex: string): any; + + setVertexProperty(vertex: VertexRequest): JsGraphResponse; + + hasVertexProperty(vertex: string): boolean; + + clearVertexProperty(vertex: string): boolean; + + inDegree(vertex: string): number; + + inEdges(vertex: string): Edge[]; + + outDegree(vertex: string): number; + + outEdges(vertex: string): Edge[]; + + //Edge functions + addEdge(request: EdgeRequest): JsGraphResponse; + + isEdge(edge: Edge): boolean; + + removeEdge(edge: Edge): JsGraphResponse; + + getEdgeProperty(edge: Edge): any; + + setEdgeProperty(request: EdgeRequest): JsGraphResponse; + + hasEdgeProperty(edge: Edge): boolean; + + clearEdgeProperty(edge: Edge): boolean; + + + } + + export interface Visitor { + initializeVertex(req: { u: string, g: DirectedGraph }): void; + + startVertex(req: { u: string, g: DirectedGraph }): void; + + discoverVertex(req: { u: string, g: DirectedGraph }): void; + + examineVertex(req: { u: string, g: DirectedGraph }): void; + + examineEdge(req: { e: Edge, g: DirectedGraph }): void; + + nonTreeEdge(req: { e: Edge, g: DirectedGraph }): void; + + grayTarget(req: { e: Edge, g: DirectedGraph }): void; + + blackTarget(req: { e: Edge, g: DirectedGraph }): void; + + finishVertex(req: { u: string, g: DirectedGraph }): void; + } + + export interface TraversalContext { + searchStatus: string; + colorMap: any; + undiscoveredMap: any; + } + + export interface TraversalOptions { + startVector: string | string[]; + allowEmptyStartVector: boolean; + signalStart: boolean; + traverseContext: TraversalContext; + } + + export interface TraversalParams { + digraph: DirectedGraph, + visitor: Visitor, + options?: TraversalOptions + } + + export interface TraversalResult { + error?: any; + result?: TraversalContext + } + + export type colors = { white: 0, gray: 1, black: 2 }; + + export interface Directed { + breadthFirstTraverse(params: TraversalParams): TraversalResult; + + colors: colors; + + create(): { result: DirectedGraph }; + + createTraversalContext(req: { dirgaph: DirectedGraph }): TraversalContext; + + depthFirstTraverse(params: TraversalParams): TraversalResult; + + transpose(graph: DirectedGraph): { error?: any, result?: DirectedGraph }; + + directedGraph: DirectedGraph; + + } +} + +declare var jsgraph: jsgraph.jsGraphStatic; + +export = jsgraph; diff --git a/types/jsgraph/jsgraph-tests.ts b/types/jsgraph/jsgraph-tests.ts new file mode 100644 index 0000000000..2fdab3c0bf --- /dev/null +++ b/types/jsgraph/jsgraph-tests.ts @@ -0,0 +1,43 @@ +import * as jsgraph from 'jsgraph'; +import {Edge, JsGraphResponse} from 'jsgraph'; + +const mygraph = jsgraph.directed.create().result; + +let name: string = 'my name'; +mygraph.setGraphName(name); +name = mygraph.getGraphName(); +let description: string = 'My desc'; +mygraph.setGraphDescription(description); +description = mygraph.getGraphDescription(); + +let count: number = mygraph.verticesCount(); +let verticies: string [] = mygraph.getVertices(); +count = mygraph.getEdgeCount(); +let edges: Edge[] = mygraph.getEdeges(); +count = mygraph.rootVerticesCount(); +verticies = mygraph.getRootVertices(); +count = mygraph.leafVerticesCount(); +verticies = mygraph.getLeafVertices(); +let json: string = mygraph.toObject(); +json = mygraph.toJSON(); +json = mygraph.stringify( () => {return}, 2); +const graph2 = mygraph.fromObject(mygraph); + +let response: JsGraphResponse = mygraph.addVertex({u: 'a', p: 'some data'}); +let bool: boolean = mygraph.removeVertex('a'); +let property: string = mygraph.getVertexProperty('a'); +mygraph.setVertexProperty({u: 'a', p: property}); +bool = mygraph.hasVertexProperty('a'); +bool = mygraph.clearVertexProperty('a'); +count = mygraph.inDegree('a'); +edges = mygraph.inEdges('a'); +count = mygraph.outDegree('a'); +edges = mygraph.outEdges('a'); + +response = mygraph.addEdge({e: {u: 'a', v:'b'}, p: 'some data'}); +bool = mygraph.isEdge({u: 'a', v:'b'}); +response = mygraph.removeEdge({u: 'a', v: 'b'}); +property = mygraph.getEdgeProperty({u: 'a', v: 'b'}); +response = mygraph.setEdgeProperty({e: {u: 'a', v: 'b'}, p: 'some data'}); +bool = mygraph.hasEdgeProperty({u: 'a', v: 'b'}); +bool = mygraph.clearEdgeProperty({u:'a', v: 'b'}); diff --git a/types/jsgraph/tsconfig.json b/types/jsgraph/tsconfig.json new file mode 100644 index 0000000000..22997eae59 --- /dev/null +++ b/types/jsgraph/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsgraph-tests.ts" + ] +} diff --git a/types/jsgraph/tslint.json b/types/jsgraph/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/jsgraph/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} From f08190e2988c71377430f5028d4a663cc39ee8b0 Mon Sep 17 00:00:00 2001 From: spacejack Date: Tue, 21 Aug 2018 15:30:10 -0400 Subject: [PATCH 074/289] Add overloads to aggregate function signatures --- types/knex/index.d.ts | 15 +++++++++++++++ types/knex/knex-tests.ts | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 54dece1068..916ee32326 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -139,12 +139,27 @@ declare namespace Knex { // Aggregation count(columnName?: string): QueryBuilder; + count(columnName: {[key: string]: string}): QueryBuilder; + count(columnName: {[key: string]: string[]}): QueryBuilder; + count(columnName: {[key: string]: Knex.Raw}): QueryBuilder; countDistinct(columnName?: string): QueryBuilder; min(columnName: string): QueryBuilder; + min(columnName: {[key: string]: string}): QueryBuilder; + min(columnName: {[key: string]: string[]}): QueryBuilder; + min(columnName: {[key: string]: Knex.Raw}): QueryBuilder; max(columnName: string): QueryBuilder; + max(columnName: {[key: string]: string}): QueryBuilder; + max(columnName: {[key: string]: string[]}): QueryBuilder; + max(columnName: {[key: string]: Knex.Raw}): QueryBuilder; sum(columnName: string): QueryBuilder; + sum(columnName: {[key: string]: string}): QueryBuilder; + sum(columnName: {[key: string]: string[]}): QueryBuilder; + sum(columnName: {[key: string]: Knex.Raw}): QueryBuilder; sumDistinct(columnName: string): QueryBuilder; avg(columnName: string): QueryBuilder; + avg(columnName: {[key: string]: string}): QueryBuilder; + avg(columnName: {[key: string]: string[]}): QueryBuilder; + avg(columnName: {[key: string]: Knex.Raw}): QueryBuilder; avgDistinct(columnName: string): QueryBuilder; increment(columnName: string, amount?: number): QueryBuilder; decrement(columnName: string, amount?: number): QueryBuilder; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 0037948415..317e5746cc 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -251,6 +251,29 @@ knex('users').whereRaw('id = ?', [1]); knex('users').whereRaw('id = :id', { id: 1 }); knex('users').whereRaw('id = :id', { id: knex('users').select('id').limit(1) }); +// Aggregate functions can use string/object parameters +knex('users').count(); +knex('users').count('*'); +knex('users').count({count: '*'}); +knex('users').count({count: ['id', 'votes']}); +knex('users').count({count: knex.raw('*')}); +knex('users').avg('id'); +knex('users').avg({avg: 'id'}); +knex('users').avg({avg: ['id', 'votes']}); +knex('users').avg({ab: knex.raw('a + b')}); +knex('users').max('id'); +knex('users').max({max: 'id'}); +knex('users').max({max: ['id', 'votes']}); +knex('users').max({ab: knex.raw('a + b')}); +knex('users').min('id'); +knex('users').min({min: 'id'}); +knex('users').min({min: ['id', 'votes']}); +knex('users').min({ab: knex.raw('a + b')}); +knex('users').sum('id'); +knex('users').sum({sum: 'id'}); +knex('users').sum({sum: ['id', 'votes']}); +knex('users').sum({ab: knex.raw('a + b')}); + // Join methods knex('users') .join('contacts', 'users.id', '=', 'contacts.user_id') From 912595482890d220baaf981e19caf861c6794de6 Mon Sep 17 00:00:00 2001 From: Bradley Hill Date: Tue, 21 Aug 2018 16:05:21 -0500 Subject: [PATCH 075/289] Latest fabric 2.3 has Object.skewX, Object.skewY --- types/fabric/fabric-impl.d.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index e5cbfc2432..783a4f41f7 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -1998,7 +1998,17 @@ interface IObjectOptions { */ scaleY?: number; - /** + /** + * Object skew factor (horizontal) + */ + skewX?: number; + + /** + * Object skew factor (vertical) + */ + skewY?: number; + + /** * When true, an object is rendered as flipped horizontally */ flipX?: boolean; @@ -2308,7 +2318,13 @@ export class Object { getScaleY(): number; setScaleY(value: number): Object; - setShadow(options: any): Object; + getSkewX(): number; + setSkewX(value: number): Object; + + getSkewY(): number; + setSkewY(value: number): Object; + + setShadow(options: any): Object; getShadow(): Object; stateProperties: any[]; From fe2e689e508fc4e120cf409849606c20e3ce0bc3 Mon Sep 17 00:00:00 2001 From: Allen Gammel Date: Tue, 21 Aug 2018 16:53:48 -0500 Subject: [PATCH 076/289] added required files. --- .../expired-storage/expired-storage-tests.ts | 67 +++++++++++ types/expired-storage/index.d.ts | 108 ++++++++++++++++++ types/expired-storage/tsconfig.json | 23 ++++ types/expired-storage/tslint.json | 8 ++ 4 files changed, 206 insertions(+) create mode 100644 types/expired-storage/expired-storage-tests.ts create mode 100644 types/expired-storage/index.d.ts create mode 100644 types/expired-storage/tsconfig.json create mode 100644 types/expired-storage/tslint.json diff --git a/types/expired-storage/expired-storage-tests.ts b/types/expired-storage/expired-storage-tests.ts new file mode 100644 index 0000000000..946051e218 --- /dev/null +++ b/types/expired-storage/expired-storage-tests.ts @@ -0,0 +1,67 @@ +import { LocalStorage } from 'node-localstorage'; +import ExpiredStorage = require('expired-storage'); + +const localStorage = new LocalStorage('./scratch', Infinity); +const expiredStorage = new ExpiredStorage(localStorage); + +const mjkModel = { + firstName: 'Maynard', + middleName: 'James', + familyName: 'Keenan', +}; + +expiredStorage.clear(); + +expiredStorage.setItem('tool', '46&2', 10); + +if (expiredStorage.getItem('tool') !== '46&2') { + throw new Error('.setItem method is not working!'); +} + +expiredStorage.setJson('mjk', mjkModel, 1); + +const mjkTest = expiredStorage.getJson('mjk'); + +if (typeof mjkTest === 'undefined' || mjkTest.firstName !== mjkModel.firstName || mjkTest.middleName !== mjkModel.middleName || mjkTest.familyName !== mjkModel.familyName) { + throw new Error('.setJson method is not working!'); +} + +if (expiredStorage.keys(true).length === 2) { + throw new Error('.keys method has failed.'); +} + +expiredStorage.setItem('apc', 'brena', 2); + +const goBackToSleep = expiredStorage.peek('apc'); + +if (!goBackToSleep.isExpired && goBackToSleep.value !== 'brena') { + throw new Error('.peek -- we have expired early... or our value was incorrect...'); +} + +do { + // nothing here to see +} while (!expiredStorage.isExpired('apc')); + +const expiredKeys = expiredStorage.clearExpired(); + +if (typeof expiredKeys['apc'] !== 'undefined') { + throw new Error('.clearExpired did not work..'); +} + +if (expiredStorage.getItem('apc') !== null) { + throw new Error('Expiration as a whole does not work.'); +} + +expiredStorage.setItem('puscifer', 'the humbling river', 10000); + +expiredStorage.updateExpiration('puscifer', 5000); + +if (expiredStorage.getTimeLeft('puscifer') >= 10000) { + throw new Error('.updateExpiration method is broken -- or .getTimeLeft method is broken.'); +} + +if (!expiredStorage.isExpired('mjk')) { + throw new Error('.isExpired or Expiration as a whole is not working...'); +} + +expiredStorage.clear(); diff --git a/types/expired-storage/index.d.ts b/types/expired-storage/index.d.ts new file mode 100644 index 0000000000..c7c113726e --- /dev/null +++ b/types/expired-storage/index.d.ts @@ -0,0 +1,108 @@ +// Type definitions for extended-storage v1.0.2 +// Project: https://github.com/RonenNess/ExpiredStorage/ +// Definitions by: Allen Gammel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "expired-storage" { + + export = ExpiredStorage; + + class ExpiredStorage { + constructor(); + constructor(localStorage?: any); + /** + * Clear the entire storage and all keys in it. + */ + clear(): void; + /** + * Get a json serializable value. This basically calls JSON.parse on the returned value. + * @param key Item key to get (string). + * @return Stored value (JSON.parsed), or undefined if not set / expired. + **/ + getJson(key: string): any; + /** + * Get item. + * @param key: Item key to get (string). + * @return: Stored value, or undefined if not set / expired. + */ + getItem(key: string): string | null; + /** + * Remove an item. + * @param key Item key to remove (string). + * @return Storage.removeItem() return code. + */ + removeItem(key: string): any; + /** + * Set a json serializable value. This basically calls JSON.stringify on 'val' before setting it. + * @param key Item key to set (string). + * @param value Value to store (object, will be JSON.stringified). + * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. + * @param return Storage.setItem() return code. + **/ + setJson(key: string, value: object, expirationTime?: number): any; + /** + * Set item. + * @param key Item key to set (string). + * @param value Value to store (string). + * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. + * @return Storage.setItem() return code. + **/ + setItem(key: string, value: string, expiration?: number): any; + /** + * Get all keys in storage, not including internal keys used to store expiration. + * @param: includeExpired: if true, will also include expired keys. + * @return: Array with keys. + */ + keys(includeExpired: boolean): Array | null; + /** + * Get item time left to live. + * @param key Item key to get (string). + * @return Time left to expire (in seconds), or null if don't have expiration date. + */ + getTimeLeft(key: string): number | null; + /** + * Clear expired keys. + * If you never call this function, expired keys will remain until you try to get them / reset a new value. + * + * @param return: List of removed keys due to expiration. + */ + clearExpired(): Array | null; + /** + * Return if an item is expired (don't remove it, even if expired). + * @param key Item key to check (string). + * @return True if expired, False otherwise. + */ + isExpired(key: string): boolean; + /** + * Get item + metadata such as time left and if expired. + * Even if item expired, will not remove it. + * @param key Item key to get (string). + * @return {ExpiredStorage.PeekInterface} PeekInterface with: {value, timeLeft, isExpired} + */ + peek(key: string): ExpiredStorage.PeekInterface; + /** + * Update expiration time for an item (note: doesn't validate that the item is set). + * @param key: Item key to update expiration for (string). + * @param expiration: New expiration time in seconds to set. + * @return: Storage.setItem() return code for setting new expiration. + **/ + updateExpiration(key: string, expiration: number): any; + } + + namespace ExpiredStorage { + export interface PeekInterface { + /** + * The value of a [key] + */ + value: string | null, + /** + * Time remaining until expiration + */ + timeLeft: number | null, + /** + * Has the [key] expired or not + */ + isExpired: boolean, + } + } +} diff --git a/types/expired-storage/tsconfig.json b/types/expired-storage/tsconfig.json new file mode 100644 index 0000000000..140265cea8 --- /dev/null +++ b/types/expired-storage/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": false, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expired-storage-tests.ts" + ] +} \ No newline at end of file diff --git a/types/expired-storage/tslint.json b/types/expired-storage/tslint.json new file mode 100644 index 0000000000..705507d3a2 --- /dev/null +++ b/types/expired-storage/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-void-expression": false, + "no-duplicate-imports": false, + "no-unnecessary-generics": false + } +} \ No newline at end of file From 625ba4186171c2332b9c58d8bc27150f04425351 Mon Sep 17 00:00:00 2001 From: Allen Gammel Date: Tue, 21 Aug 2018 17:30:57 -0500 Subject: [PATCH 077/289] updated based on npm test results --- .../expired-storage/expired-storage-tests.ts | 8 +- types/expired-storage/index.d.ts | 185 +++++++++--------- types/expired-storage/tsconfig.json | 2 +- 3 files changed, 96 insertions(+), 99 deletions(-) diff --git a/types/expired-storage/expired-storage-tests.ts b/types/expired-storage/expired-storage-tests.ts index 946051e218..269a8a61f3 100644 --- a/types/expired-storage/expired-storage-tests.ts +++ b/types/expired-storage/expired-storage-tests.ts @@ -1,8 +1,8 @@ -import { LocalStorage } from 'node-localstorage'; +// import { LocalStorage } from 'node-localstorage'; import ExpiredStorage = require('expired-storage'); -const localStorage = new LocalStorage('./scratch', Infinity); -const expiredStorage = new ExpiredStorage(localStorage); +// const localStorage = new LocalStorage('./scratch', Infinity); +const expiredStorage = new ExpiredStorage(); const mjkModel = { firstName: 'Maynard', @@ -44,7 +44,7 @@ do { const expiredKeys = expiredStorage.clearExpired(); -if (typeof expiredKeys['apc'] !== 'undefined') { +if (expiredKeys.indexOf('apc') === -1) { throw new Error('.clearExpired did not work..'); } diff --git a/types/expired-storage/index.d.ts b/types/expired-storage/index.d.ts index c7c113726e..bc7f7eb0b5 100644 --- a/types/expired-storage/index.d.ts +++ b/types/expired-storage/index.d.ts @@ -1,108 +1,105 @@ -// Type definitions for extended-storage v1.0.2 +// Type definitions for extended-storage 1.0 // Project: https://github.com/RonenNess/ExpiredStorage/ // Definitions by: Allen Gammel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare module "expired-storage" { +export = ExpiredStorage; - export = ExpiredStorage; +declare class ExpiredStorage { + constructor(localStorage?: any); + /** + * Clear the entire storage and all keys in it. + */ + clear(): void; + /** + * Get a json serializable value. This basically calls JSON.parse on the returned value. + * @param key Item key to get (string). + * @return Stored value (JSON.parsed), or undefined if not set / expired. + */ + getJson(key: string): any; + /** + * Get item. + * @param key: Item key to get (string). + * @return: Stored value, or undefined if not set / expired. + */ + getItem(key: string): string | null; + /** + * Remove an item. + * @param key Item key to remove (string). + * @return Storage.removeItem() return code. + */ + removeItem(key: string): any; + /** + * Set a json serializable value. This basically calls JSON.stringify on 'val' before setting it. + * @param key Item key to set (string). + * @param value Value to store (object, will be JSON.stringified). + * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. + * @param return Storage.setItem() return code. + */ + setJson(key: string, value: object, expirationTime?: number): any; + /** + * Set item. + * @param key Item key to set (string). + * @param value Value to store (string). + * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. + * @return Storage.setItem() return code. + */ + setItem(key: string, value: string, expiration?: number): any; + /** + * Get all keys in storage, not including internal keys used to store expiration. + * @param: includeExpired: if true, will also include expired keys. + * @return: Array with keys. + */ + keys(includeExpired: boolean): string[] | null; + /** + * Get item time left to live. + * @param key Item key to get (string). + * @return Time left to expire (in seconds), or null if don't have expiration date. + */ + getTimeLeft(key: string): number | null; + /** + * Clear expired keys. + * If you never call this function, expired keys will remain until you try to get them / reset a new value. + * + * @param return: List of removed keys due to expiration. + */ + clearExpired(): string[]; + /** + * Return if an item is expired (don't remove it, even if expired). + * @param key Item key to check (string). + * @return True if expired, False otherwise. + */ + isExpired(key: string): boolean; + /** + * Get item + metadata such as time left and if expired. + * Even if item expired, will not remove it. + * @param key Item key to get (string). + * @return PeekInterface with: {value, timeLeft, isExpired} + */ + peek(key: string): ExpiredStorage.PeekInterface; + /** + * Update expiration time for an item (note: doesn't validate that the item is set). + * @param key: Item key to update expiration for (string). + * @param expiration: New expiration time in seconds to set. + * @return: Storage.setItem() return code for setting new expiration. + */ + updateExpiration(key: string, expiration: number): any; +} - class ExpiredStorage { - constructor(); - constructor(localStorage?: any); +declare namespace ExpiredStorage { + interface PeekInterface { /** - * Clear the entire storage and all keys in it. + * The value of a [key] */ - clear(): void; + value: string | null; /** - * Get a json serializable value. This basically calls JSON.parse on the returned value. - * @param key Item key to get (string). - * @return Stored value (JSON.parsed), or undefined if not set / expired. - **/ - getJson(key: string): any; - /** - * Get item. - * @param key: Item key to get (string). - * @return: Stored value, or undefined if not set / expired. + * Time remaining until expiration */ - getItem(key: string): string | null; + timeLeft: number | null; /** - * Remove an item. - * @param key Item key to remove (string). - * @return Storage.removeItem() return code. + * Has the [key] expired or not */ - removeItem(key: string): any; - /** - * Set a json serializable value. This basically calls JSON.stringify on 'val' before setting it. - * @param key Item key to set (string). - * @param value Value to store (object, will be JSON.stringified). - * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. - * @param return Storage.setItem() return code. - **/ - setJson(key: string, value: object, expirationTime?: number): any; - /** - * Set item. - * @param key Item key to set (string). - * @param value Value to store (string). - * @param expiration Expiration time, in seconds. If not provided, will not set expiration time. - * @return Storage.setItem() return code. - **/ - setItem(key: string, value: string, expiration?: number): any; - /** - * Get all keys in storage, not including internal keys used to store expiration. - * @param: includeExpired: if true, will also include expired keys. - * @return: Array with keys. - */ - keys(includeExpired: boolean): Array | null; - /** - * Get item time left to live. - * @param key Item key to get (string). - * @return Time left to expire (in seconds), or null if don't have expiration date. - */ - getTimeLeft(key: string): number | null; - /** - * Clear expired keys. - * If you never call this function, expired keys will remain until you try to get them / reset a new value. - * - * @param return: List of removed keys due to expiration. - */ - clearExpired(): Array | null; - /** - * Return if an item is expired (don't remove it, even if expired). - * @param key Item key to check (string). - * @return True if expired, False otherwise. - */ - isExpired(key: string): boolean; - /** - * Get item + metadata such as time left and if expired. - * Even if item expired, will not remove it. - * @param key Item key to get (string). - * @return {ExpiredStorage.PeekInterface} PeekInterface with: {value, timeLeft, isExpired} - */ - peek(key: string): ExpiredStorage.PeekInterface; - /** - * Update expiration time for an item (note: doesn't validate that the item is set). - * @param key: Item key to update expiration for (string). - * @param expiration: New expiration time in seconds to set. - * @return: Storage.setItem() return code for setting new expiration. - **/ - updateExpiration(key: string, expiration: number): any; - } - - namespace ExpiredStorage { - export interface PeekInterface { - /** - * The value of a [key] - */ - value: string | null, - /** - * Time remaining until expiration - */ - timeLeft: number | null, - /** - * Has the [key] expired or not - */ - isExpired: boolean, - } + isExpired: boolean; } } diff --git a/types/expired-storage/tsconfig.json b/types/expired-storage/tsconfig.json index 140265cea8..035c1af35e 100644 --- a/types/expired-storage/tsconfig.json +++ b/types/expired-storage/tsconfig.json @@ -4,7 +4,7 @@ "lib": [ "es6" ], - "noImplicitAny": false, + "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, From bb69e772283c240e0b29263799686e03cbb6acb1 Mon Sep 17 00:00:00 2001 From: Daniel Lytkin Date: Wed, 22 Aug 2018 12:32:46 +0700 Subject: [PATCH 078/289] Make `wu.find` return `T | undefined` --- types/wu/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/wu/index.d.ts b/types/wu/index.d.ts index 3d44b5140f..354b0303c7 100644 --- a/types/wu/index.d.ts +++ b/types/wu/index.d.ts @@ -30,7 +30,7 @@ declare namespace wu { function enumerate(iter: Iterable): Iterable<[number, T]>; function every(fn: Filter, iter: Iterable): boolean; function filter(fn: Filter, iter: Iterable): WuIterable; - function find(fn: Filter, iter: Iterable): T; + function find(fn: Filter, iter: Iterable): T | undefined; function flatten(iter: Iterable): WuIterable; function flatten(shallow: boolean, iter: Iterable): WuIterable; function forEach(fn: Consumer, iter: Iterable): void; From c51f9514f5232b7f8d40f678b13cad7be7ce2b98 Mon Sep 17 00:00:00 2001 From: Daniel Lytkin Date: Wed, 22 Aug 2018 12:35:32 +0700 Subject: [PATCH 079/289] Make `WuIterable.find` return `T | undefined` --- types/wu/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/wu/index.d.ts b/types/wu/index.d.ts index 354b0303c7..08a1b9f19a 100644 --- a/types/wu/index.d.ts +++ b/types/wu/index.d.ts @@ -79,7 +79,7 @@ declare namespace wu { enumerate(): Iterable<[number, T]>; every(fn: Filter): boolean; filter(fn: Filter): WuIterable; - find(fn: Filter): T; + find(fn: Filter): T | undefined; flatten(shallow?: boolean): WuIterable; forEach(fn: Consumer): void; has(t: T): boolean; From 86c7d8d495aab98be1a264b8247281eed31687ec Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Wed, 22 Aug 2018 10:38:49 +0200 Subject: [PATCH 080/289] fixup! Added textTracks & remoteTextTracks to video.js --- types/video.js/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 036aa1189b..87407dc81d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3768,13 +3768,13 @@ declare namespace videojs { * Get the remote {@link TextTrackList} * @return The current remote text track list */ - textTracks(): TextTrackList + textTracks(): TextTrackList; /** * Get the remote {@link TextTrackList} * @return The current remote text track list */ - remoteTextTracks(): TextTrackList + remoteTextTracks(): TextTrackList; /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will From 4b0c689649a2f17e0d05fd65c1d1ada01a6ef20b Mon Sep 17 00:00:00 2001 From: Aldis Ameriks Date: Wed, 22 Aug 2018 14:32:56 +0300 Subject: [PATCH 081/289] react-dates: update type for disabled prop --- types/react-dates/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 5e0a889384..20739d5918 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -49,7 +49,7 @@ declare namespace ReactDates { // input related props startDatePlaceholderText?: string, endDatePlaceholderText?: string, - disabled?: boolean, + disabled?: DisabledShape, required?: boolean, readOnly?: boolean, screenReaderInputMessage?: string, From b094f321f5ddc4cabfef6b2c4df7e4dbdedceed2 Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Wed, 22 Aug 2018 13:56:00 +0200 Subject: [PATCH 082/289] Fixed Element event handler --- types/video.js/index.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 87407dc81d..75884ffb7d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -2628,7 +2628,8 @@ declare namespace videojs { * the listener function; otherwise, _all_ listeners bound to the * event type(s) will be removed. */ - off(targetOrType?: string | string[], typeOrListener?: (...args: any[]) => void, listener?: (...args: any[]) => void): void; + off(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + off(type?: string | string[], listener?: (...args: any[]) => void): void; /** * Add a listener to an event (or events) on this object or another evented @@ -2653,7 +2654,8 @@ declare namespace videojs { * If the first argument was another evented object, this will be * the listener function. */ - on(targetOrType: string | string[], typeOrListener: (...args: any[]) => void, listener?: (...args: any[]) => void): void; + on(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + on(type?: string | string[], listener?: (...args: any[]) => void): void; /** * Add a listener to an event (or events) on this object or another evented @@ -2678,7 +2680,8 @@ declare namespace videojs { * If the first argument was another evented object, this will be * the listener function. */ - one(targetOrType: string | string[], typeOrListener: (...args: any[]) => void, listener?: (...args: any[]) => void): void; + one(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + one(type?: string | string[], listener?: (...args: any[]) => void): void; /** * Fire an event on this evented object, causing its listeners to be called. From 1f779ef3af4778bcbe6ee351427e60f6d4960af5 Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Wed, 22 Aug 2018 14:31:00 +0200 Subject: [PATCH 083/289] fixup! Fixed Element event handler --- 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 75884ffb7d..db3697b65a 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -2628,7 +2628,7 @@ declare namespace videojs { * the listener function; otherwise, _all_ listeners bound to the * event type(s) will be removed. */ - off(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + off(target?: Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; off(type?: string | string[], listener?: (...args: any[]) => void): void; /** @@ -2654,7 +2654,7 @@ declare namespace videojs { * If the first argument was another evented object, this will be * the listener function. */ - on(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + on(target?: Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; on(type?: string | string[], listener?: (...args: any[]) => void): void; /** @@ -2680,7 +2680,7 @@ declare namespace videojs { * If the first argument was another evented object, this will be * the listener function. */ - one(target?: videojs.Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; + one(target?: Component | Element, type?: string | string[], listener?: (...args: any[]) => void): void; one(type?: string | string[], listener?: (...args: any[]) => void): void; /** From 236fe406c759dfdfae01d03462d0f2b1256b86a3 Mon Sep 17 00:00:00 2001 From: Allen Gammel Date: Wed, 22 Aug 2018 08:40:04 -0500 Subject: [PATCH 084/289] added strictNullChecks, removed addtl tslint rules, added null checks --- types/expired-storage/expired-storage-tests.ts | 13 +++++++++---- types/expired-storage/tsconfig.json | 2 +- types/expired-storage/tslint.json | 7 +------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/types/expired-storage/expired-storage-tests.ts b/types/expired-storage/expired-storage-tests.ts index 269a8a61f3..fa2dd29ef7 100644 --- a/types/expired-storage/expired-storage-tests.ts +++ b/types/expired-storage/expired-storage-tests.ts @@ -1,7 +1,8 @@ -// import { LocalStorage } from 'node-localstorage'; +// import { LocalStorage } from 'node-localstorage'; // Removed since this pkg isn't getting installed. import ExpiredStorage = require('expired-storage'); // const localStorage = new LocalStorage('./scratch', Infinity); +// const expiredStorage = new ExpiredStorage(localStorage); // ExpiredStorage requires a LocalStorage provider const expiredStorage = new ExpiredStorage(); const mjkModel = { @@ -26,7 +27,9 @@ if (typeof mjkTest === 'undefined' || mjkTest.firstName !== mjkModel.firstName | throw new Error('.setJson method is not working!'); } -if (expiredStorage.keys(true).length === 2) { +const keyCheck = expiredStorage.keys(true); + +if (keyCheck && keyCheck.length === 2) { throw new Error('.keys method has failed.'); } @@ -44,7 +47,7 @@ do { const expiredKeys = expiredStorage.clearExpired(); -if (expiredKeys.indexOf('apc') === -1) { +if (expiredKeys.indexOf('apc') !== -1) { throw new Error('.clearExpired did not work..'); } @@ -56,7 +59,9 @@ expiredStorage.setItem('puscifer', 'the humbling river', 10000); expiredStorage.updateExpiration('puscifer', 5000); -if (expiredStorage.getTimeLeft('puscifer') >= 10000) { +const checkKeyTime = expiredStorage.getTimeLeft('puscifer'); + +if (checkKeyTime && checkKeyTime >= 10000) { throw new Error('.updateExpiration method is broken -- or .getTimeLeft method is broken.'); } diff --git a/types/expired-storage/tsconfig.json b/types/expired-storage/tsconfig.json index 035c1af35e..cd1454cca7 100644 --- a/types/expired-storage/tsconfig.json +++ b/types/expired-storage/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/expired-storage/tslint.json b/types/expired-storage/tslint.json index 705507d3a2..e60c15844f 100644 --- a/types/expired-storage/tslint.json +++ b/types/expired-storage/tslint.json @@ -1,8 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-void-expression": false, - "no-duplicate-imports": false, - "no-unnecessary-generics": false - } + "extends": "dtslint/dt.json" } \ No newline at end of file From 1aaec3e4d7c79501b05760c3da39da7964f3e037 Mon Sep 17 00:00:00 2001 From: Giom Date: Wed, 22 Aug 2018 16:41:13 +0200 Subject: [PATCH 085/289] Added missing property in BasicToastrOptions Added onToastrClick property that was missing in BasicToastrOptions --- types/react-redux-toastr/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-redux-toastr/index.d.ts b/types/react-redux-toastr/index.d.ts index 8f18abc73b..cf81d974dd 100644 --- a/types/react-redux-toastr/index.d.ts +++ b/types/react-redux-toastr/index.d.ts @@ -23,6 +23,7 @@ interface BasicToastrOptions { onCloseButtonClick?: () => void; onHideComplete?: () => void; onShowComplete?: () => void; + onToastrClick?: () => void; progressBar?: boolean; removeOnHover?: boolean; showCloseButton?: boolean; From 19afef35b34bc2bb86bc692242c0ae6c45bc6adc Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Wed, 22 Aug 2018 17:44:18 +0200 Subject: [PATCH 086/289] Fix how modules are imported --- types/gulp-jsonmin/gulp-jsonmin-tests.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/gulp-jsonmin/gulp-jsonmin-tests.ts b/types/gulp-jsonmin/gulp-jsonmin-tests.ts index 5c0cf66cc3..3b7fe4ee1c 100644 --- a/types/gulp-jsonmin/gulp-jsonmin-tests.ts +++ b/types/gulp-jsonmin/gulp-jsonmin-tests.ts @@ -1,5 +1,4 @@ -import * as GulpJsonmin from 'gulp-jsonmin'; +import GulpJsonmin = require('gulp-jsonmin'); GulpJsonmin(); -GulpJsonmin({}); GulpJsonmin({ verbose: true }); From c4686947c2f0d8af1699aae54f55af55c2ca0d1d Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Wed, 22 Aug 2018 17:51:39 +0200 Subject: [PATCH 087/289] Bump library version --- types/gulp-jsonmin/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/gulp-jsonmin/index.d.ts b/types/gulp-jsonmin/index.d.ts index 16a4347dd2..b246ead5b4 100644 --- a/types/gulp-jsonmin/index.d.ts +++ b/types/gulp-jsonmin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for gulp-jsonmin 1.1 +// Type definitions for gulp-jsonmin 1.2 // Project: https://github.com/englercj/gulp-jsonmin // Definitions by: Romain Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 78e54b8844b5e4318ff49419dfd9ed3bae20558b Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Wed, 22 Aug 2018 18:21:17 +0200 Subject: [PATCH 088/289] Fix code style --- types/gulp-jsonmin/gulp-jsonmin-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/gulp-jsonmin/gulp-jsonmin-tests.ts b/types/gulp-jsonmin/gulp-jsonmin-tests.ts index 3b7fe4ee1c..23d4ea5427 100644 --- a/types/gulp-jsonmin/gulp-jsonmin-tests.ts +++ b/types/gulp-jsonmin/gulp-jsonmin-tests.ts @@ -1,4 +1,4 @@ -import GulpJsonmin = require('gulp-jsonmin'); +import gulpJsonmin = require('gulp-jsonmin'); -GulpJsonmin(); -GulpJsonmin({ verbose: true }); +gulpJsonmin(); +gulpJsonmin({ verbose: true }); From 6eb5beca3206c88aeda0f9e1a3e032b5ef776ee3 Mon Sep 17 00:00:00 2001 From: Bradley Hill Date: Wed, 22 Aug 2018 13:42:00 -0500 Subject: [PATCH 089/289] Appears latest linter code now fails in test code. Explicit cast to appease linter gods. --- types/fabric/test/index.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/fabric/test/index.ts b/types/fabric/test/index.ts index 1060525a00..9a5c0b24d2 100644 --- a/types/fabric/test/index.ts +++ b/types/fabric/test/index.ts @@ -872,7 +872,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.textDecoration = (activeObject.textDecoration === 'underline' ? '' : 'underline'); - this.className = activeObject.textDecoration ? 'selected' : ''; + (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } }; @@ -885,7 +885,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.textDecoration = (activeObject.textDecoration === 'line-through' ? '' : 'line-through'); - this.className = activeObject.textDecoration ? 'selected' : ''; + (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } }; @@ -898,7 +898,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.textDecoration = (activeObject.textDecoration === 'overline' ? '' : 'overline'); - this.className = activeObject.textDecoration ? 'selected' : ''; + (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } }; @@ -911,7 +911,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.fontWeight = (activeObject.fontWeight === 'bold' ? '' : 'bold'); - this.className = activeObject.fontWeight ? 'selected' : ''; + (this as HTMLElement).className = activeObject.fontWeight ? 'selected' : ''; canvas.renderAll(); } }; @@ -924,7 +924,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.fontStyle = (activeObject.fontStyle === 'italic' ? '' : 'italic'); - this.className = activeObject.fontStyle ? 'selected' : ''; + (this as HTMLElement).className = activeObject.fontStyle ? 'selected' : ''; canvas.renderAll(); } }; @@ -937,7 +937,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.shadow = !activeObject.shadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : ''; - this.className = activeObject.shadow ? 'selected' : ''; + (this as HTMLElement).className = activeObject.shadow ? 'selected' : ''; canvas.renderAll(); } }; From 9b711fb5ee5875be7263e774c1b6f2b95ee26997 Mon Sep 17 00:00:00 2001 From: Megan Riel-Mehan Date: Wed, 22 Aug 2018 17:01:40 -0700 Subject: [PATCH 090/289] added histogram as plot type option --- types/plotly.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 7bdf862ea2..e4904fff98 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -423,7 +423,7 @@ export type Color = string | Array | Array Date: Wed, 22 Aug 2018 17:08:54 -0700 Subject: [PATCH 091/289] Add aphrodite-specific animationName types. Aphrodite supports definition animationNames not just as the shorthand, but also as full-fledged definition objects: https://github.com/Khan/aphrodite#animations --- types/aphrodite/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index bd2749f737..3e7807b6b6 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -14,12 +14,13 @@ type FontFamily = type Omit = Pick; -type CSSProperties = Omit & { +type CSSProperties = Omit & { fontFamily?: FontFamily | FontFamily[]; + animationName?: string | OpenCSSProperties | OpenCSSProperties[]; }; // For pseudo selectors and media queries -interface OpenCSSProperties extends CSSProperties { +interface OpenCSSProperties extends CSSProperties { [k: string]: CSSProperties[keyof CSSProperties] | CSSProperties; } From 37bf104dc87b962c5366714999788d4745d4f25d Mon Sep 17 00:00:00 2001 From: Megan Riel-Mehan Date: Wed, 22 Aug 2018 18:21:15 -0700 Subject: [PATCH 092/289] added transform interface --- types/plotly.js/index.d.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index e4904fff98..a14ba14aba 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -470,8 +470,39 @@ export interface ScatterData { name: string; connectgaps: boolean; visible: boolean | 'legendonly'; + transforms: Transform[]; } +/** + * These interfaces are based on attribute descriptions in + * https://github.com/plotly/plotly.js/tree/9d6144304308fc3007f0facf2535d38ea3e9b26c/src/transforms + */ + +export interface TransformStyle { + target: number | string | number[] | string[]; + value: Partial; +} + +export interface TransformAggregation { + target: string; + func?: 'count' | 'sum' | 'avg' | 'median' | 'mode' | 'rms' | 'stddev' | 'min' | 'max' | 'first' | 'last'; + funcmode?: 'sample' | 'population'; + enabled?: boolean; +} + +export interface Transform { + type: 'aggregate' | 'filter' | 'groupby' | 'sort'; + enabled?: boolean; + target?: number | string | number[] | string[]; + operation?: string; + aggregations?: TransformAggregation[]; + preservegaps?: boolean; + groups?: string | number[] | string[]; + nameformat: string; + styles?: TransformStyle[]; + value?: any; + order?: 'ascending' | 'descending'; +} /** * Any combination of "x", "y", "z", "text", "name" joined with a "+" OR "all" or "none" or "skip". * examples: "x", "y", "x+y", "x+y+z", "all" From bd493ea22415d7abf3feaa56428d4a3fc2c040b4 Mon Sep 17 00:00:00 2001 From: Megan Riel-Mehan Date: Wed, 22 Aug 2018 18:21:59 -0700 Subject: [PATCH 093/289] added additional x axes in layout interface --- types/plotly.js/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index a14ba14aba..84cad93b48 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -192,6 +192,14 @@ export interface Layout { separators: string; hidesources: boolean; xaxis: Partial; + xaxis2: Partial; + xaxis3: Partial; + xaxis4: Partial; + xaxis5: Partial; + xaxis6: Partial; + xaxis7: Partial; + xaxis8: Partial; + xaxis9: Partial; yaxis: Partial; yaxis2: Partial; yaxis3: Partial; From 00e6ba45f2e05e9b14277394b22a5d5622e3cc89 Mon Sep 17 00:00:00 2001 From: DimaMukhin Date: Wed, 22 Aug 2018 20:38:15 -0700 Subject: [PATCH 094/289] implemented koa2-session-redis type definitions --- types/koa2-session-redis/index.d.ts | 45 +++++++++++++++++++ .../koa2-session-redis-tests.ts | 15 +++++++ types/koa2-session-redis/tsconfig.json | 23 ++++++++++ types/koa2-session-redis/tslint.json | 1 + 4 files changed, 84 insertions(+) create mode 100644 types/koa2-session-redis/index.d.ts create mode 100644 types/koa2-session-redis/koa2-session-redis-tests.ts create mode 100644 types/koa2-session-redis/tsconfig.json create mode 100644 types/koa2-session-redis/tslint.json diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts new file mode 100644 index 0000000000..39707be4da --- /dev/null +++ b/types/koa2-session-redis/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for koa2-session-redis 0.0 +// Project: https://github.com/lonord/koa2-session-redis +// Definitions by: Dima Mukhin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ Note that ES6 modules cannot directly export class objects. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +import * as Redis from 'redis'; +import * as session from 'koa-session'; + +/*~ This declaration specifies that the class constructor function + *~ is the exported object from the file + */ +export = RedisStore; + +/*~ Write your module's methods and properties in this class */ +declare class RedisStore implements session.stores { + constructor(config?: Redis.ClientOpts); + + /** + * get session object by key + */ + get(key: string): any; + + /** + * set session object for key, with a maxAge (in ms) + */ + set(key: string, sess: Partial & { _expire?: number, _maxAge?: number }, maxAge: session.opts["maxAge"]): any; + + /** + * destroy session for key + */ + destroy(key: string): any; + + /** + * sends the quit command to the redis server and ends cleanly right after all running commands were properly handled + */ + quit(): void; +} diff --git a/types/koa2-session-redis/koa2-session-redis-tests.ts b/types/koa2-session-redis/koa2-session-redis-tests.ts new file mode 100644 index 0000000000..5a72ebcecd --- /dev/null +++ b/types/koa2-session-redis/koa2-session-redis-tests.ts @@ -0,0 +1,15 @@ +import * as session from 'koa-session'; +import * as Koa from 'koa'; +import RedisStore = require('koa2-session-redis'); + +const app = new Koa(); + +const CONFIG = { + store: new RedisStore({ + host: '127.0.0.1', + port: 6379, + max_attempts: 0 + }) +} + +app.use(session(CONFIG, app)); diff --git a/types/koa2-session-redis/tsconfig.json b/types/koa2-session-redis/tsconfig.json new file mode 100644 index 0000000000..e96bc50af3 --- /dev/null +++ b/types/koa2-session-redis/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", + "koa2-session-redis-tests.ts" + ] +} diff --git a/types/koa2-session-redis/tslint.json b/types/koa2-session-redis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa2-session-redis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From abb10c80a7632524e983b32532193d194bce4b61 Mon Sep 17 00:00:00 2001 From: Kyle Roach Date: Thu, 23 Aug 2018 01:02:26 -0400 Subject: [PATCH 095/289] [storybook__react-native] Add getStorybookUI --- types/storybook__react-native/index.d.ts | 18 +++++++- .../storybook__react-native-tests.tsx | 45 +++++++++++++++---- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/types/storybook__react-native/index.d.ts b/types/storybook__react-native/index.d.ts index 1a0d0bee48..3f46866129 100644 --- a/types/storybook__react-native/index.d.ts +++ b/types/storybook__react-native/index.d.ts @@ -3,9 +3,23 @@ // Definitions by: Joscha Feth // Anton Izmailov // Alec Hill +// Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as Storybook from '@storybook/react'; +import * as React from 'react'; -export = Storybook; +export interface StorybookUIOptions { + onDeviceUI?: boolean; + disableWebsockets?: boolean; + secured?: boolean; + host?: string; + port?: number; + query?: string; +} + +export function getStorybookUI( + options: StorybookUIOptions +): React.ComponentClass; + +export * from '@storybook/react'; diff --git a/types/storybook__react-native/storybook__react-native-tests.tsx b/types/storybook__react-native/storybook__react-native-tests.tsx index 7540a2f3e8..0afa37c1d6 100644 --- a/types/storybook__react-native/storybook__react-native-tests.tsx +++ b/types/storybook__react-native/storybook__react-native-tests.tsx @@ -1,12 +1,21 @@ import * as React from 'react'; -import { storiesOf, setAddon, addDecorator, configure, getStorybook, RenderFunction, Story } from '@storybook/react-native'; +import { + storiesOf, + setAddon, + addDecorator, + configure, + getStorybook, + RenderFunction, + getStorybookUI, + Story +} from '@storybook/react-native'; const Decorator = (story: RenderFunction) =>
{story()}
; storiesOf('Welcome', module) // local addDecorator .addDecorator(Decorator) - .add('to Storybook', () =>
) + .add('to Storybook', () =>
) .add('to Storybook as Array', () => [
,
]); // global addDecorator @@ -14,24 +23,42 @@ addDecorator(Decorator); // setAddon interface AnyAddon { - addWithSideEffect(this: Story & T, storyName: string, storyFn: RenderFunction): Story & T; + addWithSideEffect( + this: Story & T, + storyName: string, + storyFn: RenderFunction + ): Story & T; } const AnyAddon: AnyAddon = { - addWithSideEffect(this: Story & T, storyName: string, storyFn: RenderFunction): Story & T { + addWithSideEffect( + this: Story & T, + storyName: string, + storyFn: RenderFunction + ): Story & T { console.log(this.kind === 'withAnyAddon'); return this.add(storyName, storyFn); } }; setAddon(AnyAddon); storiesOf('withAnyAddon', module) - .addWithSideEffect('custom story', () =>
) - .addWithSideEffect('more', () =>
) - .add('another story', () =>
) + .addWithSideEffect('custom story', () =>
) + .addWithSideEffect('more', () =>
) + .add('another story', () =>
) .add('to Storybook as Array', () => [
,
]) - .addWithSideEffect('even more', () =>
); + .addWithSideEffect('even more', () =>
); // configure configure(() => undefined, module); // getStorybook -getStorybook().forEach(({ kind, stories }) => stories.forEach(({ name, render }) => render())); +getStorybook().forEach(({ kind, stories }) => + stories.forEach(({ name, render }) => render()) +); + +const StorybookUI = getStorybookUI({ + port: 9001, + host: 'localhost', + onDeviceUI: true +}); + +const TestRender = () => ; From c334034df9c749abd4e4b7b1ffe9ecb9199bb4ad Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Tue, 21 Aug 2018 12:02:55 +0200 Subject: [PATCH 096/289] jss: Add definitions for createGenerateClassName --- types/jss/index.d.ts | 5 +++++ types/jss/jss-tests.ts | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/types/jss/index.d.ts b/types/jss/index.d.ts index 3318f9a565..b19b82ab0e 100644 --- a/types/jss/index.d.ts +++ b/types/jss/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Brenton Simpson // Oleg Slobodskoi // Thomas Crockett +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -137,6 +138,10 @@ export declare class JSS { * Creates a new instance of JSS. */ export function create(options?: Partial): JSS; +/** + * Creates a GenerateClassName function + */ +export function createGenerateClassName(): GenerateClassName; declare const sharedInstance: JSS; /** * A global JSS instance. diff --git a/types/jss/jss-tests.ts b/types/jss/jss-tests.ts index 5e9a876036..8822264282 100644 --- a/types/jss/jss-tests.ts +++ b/types/jss/jss-tests.ts @@ -2,11 +2,12 @@ import { create as createJSS, + createGenerateClassName, SheetsRegistry, default as sharedInstance, } from 'jss'; -const jss = createJSS().setup({}); +const jss = createJSS().setup({ createGenerateClassName }); jss.use({}, {}); // $ExpectType JSS const styleSheet = jss.createStyleSheet( @@ -46,6 +47,9 @@ const rule = attachedStyleSheet.addRule('dynamicRule', { color: 'indigo' }); rule.prop('border-radius', 5).prop('color'); // $ExpectType string attachedStyleSheet.classes.dynamicRule; // $ExpectType string +const generateClassName = createGenerateClassName(); +const dynamicRuleClassName = generateClassName(rule, attachedStyleSheet); + attachedStyleSheet.deleteRule('dynamicRule'); // test that `addRule` supports the shorthand signature From 7ace836a1671cf2e57d56a9f515db5ba95a77de8 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 10:22:18 +0200 Subject: [PATCH 097/289] AppView added --- types/chrome-apps/appview.d.ts | 47 +++++++++++++++++++++++++++++++++ types/chrome-apps/index.d.ts | 30 +++++++-------------- types/chrome-apps/test/index.ts | 37 +++++++++++++++++++++++++- types/chrome-apps/webview.d.ts | 4 +++ 4 files changed, 96 insertions(+), 22 deletions(-) create mode 100644 types/chrome-apps/appview.d.ts diff --git a/types/chrome-apps/appview.d.ts b/types/chrome-apps/appview.d.ts new file mode 100644 index 0000000000..6924f9ca21 --- /dev/null +++ b/types/chrome-apps/appview.d.ts @@ -0,0 +1,47 @@ +// Type definitions for Chrome packaged application development +// Project: http://developer.chrome.com/apps/ +// 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.8 + +///////////////// +// AppView Tag // +///////////////// +/** + * Use the appview tag to embed other Chrome Apps within your Chrome App. + * The appview runs in a separate process from your app, + * it doesn't inherit the same permissions and is only allowed + * to interact with your app through asynchronous APIs. + * Not all apps can be embedded; apps have to explicitly allow themselves to be embedded. + * @since Chrome 43. + * @requires Permissions: 'appview' + * @see[Documentation]{@link https://developer.chrome.com/apps/tags/appview} + */ +declare class HTMLAppViewElement extends HTMLElement { + /** + * Requests another app to be embedded. + * @param app The extension id of the app to be embedded. + * @param [data] Optional developer specified data that the app to be embedded can use when making an embedding decision. + * @param [callback] Optional callback when the embedding request is completed. Will provide the result. + */ + connect(app: string, data?: any, callback?: (success: boolean) => void): void; +} +declare namespace AppView { + interface EmbedRequest { + /** The ID of the app that sent the embedding request. */ + embedderId: string; + /** Optional developer specified data that the app to be embedded can use when making an embedding decision. */ + data?: Object; + /** + * Allows the embedding request + * @param url Specifies the content to be embedded. + */ + allow(url: string): void; + /** Prevents the embedding request */ + deny(): void; + } +} + +declare interface Document { + createElement(element: 'appview'): HTMLAppViewElement; +} diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 680aa5e2ae..24a2142b4d 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5,6 +5,7 @@ // TypeScript Version: 2.8 /// +/// /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -373,21 +374,6 @@ declare namespace chrome { URL_HANDLER: 'url_handler' } - interface EmbedRequested { - /** - * Optional developer specified data that the app to be embedded can use when making an embedding decision. - */ - data?: any; - /** - * Allows embedderId to embed this app in an element. The url specifies the content to embed. - */ - allow: (url: string) => void; - /** - * Prevents embedderId from embedding this app in an element. - */ - deny: () => void; - } - interface LaunchData { /** * The ID of the file or URL handler that the app is being invoked with. @@ -444,10 +430,10 @@ declare namespace chrome { /** * Fired when an embedding app requests to embed this app. - * @requires(dev) This event is only available on dev channel with the flag --enable-app-view. - * @since Since Chrome 38. + * @since Since Chrome 43. + * @see[Documentation]{@link https://developer.chrome.com/apps/tags/appview} */ - const onEmbedRequested: chrome.events.Event<(request: EmbedRequested) => void>; + const onEmbedRequested: chrome.events.Event<(request: AppView.EmbedRequest) => void>; /** * Fired when an app is launched from the launcher. */ @@ -6962,7 +6948,7 @@ declare namespace chrome { * */ | 'chrome://favicon/' - | 'chrome://extension-icon/'; + // | 'chrome://extension-icon/'; // Doesn't need permission yet? type ChromeOSOnlyPermissions = /** @@ -7027,8 +7013,6 @@ declare namespace chrome { /** Undocumented but used permissions */ type UndocumentedPermissions = 'app.window.ime' | - /** Enable the tag. @todo Document this tag */ - 'appview' | /** * @deprecated * @see Permission: 'app.window.fullscreen' @@ -7059,6 +7043,8 @@ declare namespace chrome { type Permission = /** Gives your app access to the chrome.alarms API. */ 'alarms' | + /** Enables the tag. @todo Document this tag */ + 'appview' | /** Gives your app access to the chrome.audio API. */ 'audio' | /** Enables the method *setAlwaysOnTop()* on chrome.app.window */ @@ -7153,6 +7139,7 @@ declare namespace chrome { /** @deprecated Serial is deprecated */ 'serial' | /** Gives your app access to the chrome.signedInDevices API. */ + /** @todo TODO */ 'signedInDevices' | /** Gives your app access to the chrome.storage API. */ 'storage' | @@ -11347,4 +11334,5 @@ declare namespace chrome { interface Window { chrome: typeof chrome; WebView: typeof HTMLWebViewElement; + AppView: typeof HTMLAppViewElement; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index b9ad34fd0b..b2dbc60f0b 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -822,6 +822,14 @@ chrome.identity.getAuthToken({ interactive: true }, (token) => { // #endregion +chrome.idle; // @todo TODO Tests + +chrome.instanceID; // @todo TODO Tests + +chrome.management; // @todo TODO Tests + +chrome.mdns; // @todo TODO Tests + // #region chrome.mediaGalleries chrome.fileSystem.getVolumeList((volumes) => { @@ -904,6 +912,12 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { // #endregion +chrome.notifications; // @todo TODO Tests + +chrome.platformKeys; // @todo TODO Tests + +chrome.permissions; // @todo TODO Tests + // #region chrome.power chrome.power.requestKeepAwake(chrome.power.Level.DISPLAY); @@ -1212,6 +1226,8 @@ chrome.sockets.udp.create({}, (createInfo) => { // #endregion +chrome.storage; // @todo TODO Tests + // #region chrome.syncFileSystem chrome.syncFileSystem.getConflictResolutionPolicy((policy) => { @@ -1283,9 +1299,15 @@ chrome.usb.getUserSelectedDevices({ // #endregion +chrome.virtualKeyboard; // @todo TODO Tests +chrome.vpnProvider; // @todo TODO Tests +chrome.wallpaper; // @todo TODO Tests +chrome.webViewRequest; // @todo TODO Tests + // #region chrome.webViewRequest & WebView -const wve = new window.WebView(); +let wve = document.createElement('webview'); +wve = new window.WebView(); wve.name = 'test'; wve.src = 'https://github.com/DefinitelyTyped'; wve.allowtransparency = true; @@ -1360,3 +1382,16 @@ new chrome.webViewRequest.RequestMatcher({ wve.request.onRequest.addRules([rule]); // #endregion + +//#region Embedding & AppView +chrome.app.runtime.onEmbedRequested.addListener((request) => { + request.allow('foobar.html'); +}); +// Creates an element. +var appview = document.createElement('appview'); +// Appends the element to the document body. +document.body.appendChild(appview); +// Connects the appview to appToEmbed. +appview.connect('id of app'); +document.appendChild(appview); +//#endregion diff --git a/types/chrome-apps/webview.d.ts b/types/chrome-apps/webview.d.ts index 78defea9d9..2e12065c0f 100644 --- a/types/chrome-apps/webview.d.ts +++ b/types/chrome-apps/webview.d.ts @@ -1366,3 +1366,7 @@ declare namespace WebView { newzoomFactor: chrome.double; } } + +declare interface Document { + createElement(element: 'webview'): HTMLWebViewElement; +} From cc4c27210b2f5d81a88fbd17408c6cf1a31f14c9 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 11:26:00 +0200 Subject: [PATCH 098/289] chrome.mdns fixes - added extra filter parameter + tests --- types/chrome-apps/index.d.ts | 52 +++++++++++++++++++++++++++++++-- types/chrome-apps/test/index.ts | 29 ++++++++++++++++-- 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 24a2142b4d..748e1db4a0 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -2935,7 +2935,7 @@ declare namespace chrome { ports?: Array; } /** An object which allows the addition and removal of listeners for a Chrome event. */ - interface Event { + interface Event { /** * Registers an event listener callback to an event. * @param callback Called when an event occurs. The parameters of this function depend on the type of event. @@ -2997,6 +2997,25 @@ declare namespace chrome { hasListeners(): boolean; } + interface EventFilter { + [key: string]: string; + } + + /** + * An object which allows the addition and removal of listeners for a Chrome event. + * Also provides the possibility to provide a filter + * @template T Callback function. + * @template F Filter interface, leave this for default + */ + interface FilteredEvent extends Event { + /** + * Registers an event listener callback to an event. + * @param callback Called when an event occurs. The parameters of this function depend on the type of event. + * @param [filter] Optional key/value dictionary you can provide to filter the events + */ + addListener(callback: T, filter?: F): void; + } + /** * Description of a declarative rule for handling events. * @template T Type for conditions array, default: any. @@ -5203,6 +5222,21 @@ declare namespace chrome { /** Metadata for an mDNS advertised service. */ serviceData: string[]; } + + /** + * Locked to this because it's the only one that can be used. + * + * const char kEventFilterServiceTypeKey[] = "serviceType"; + * @see[Source: event_matcher.cc, line 19]{@link https://github.com/chromium/chromium/tree/master/extensions/common/event_matcher.cc} + */ + type ValidServiceTypes = 'serviceType'; + + /** + * Dictionary + * [key in ValidServiceTypes]: string + */ + type ServiceTypes = Record; + /** * The maximum number of service instances that will be * included in onServiceList events. If more instances @@ -5229,8 +5263,12 @@ declare namespace chrome { * discovering should be specified as the event filter * with the 'serviceType' key. Not specifying an event * filter will not start any discovery listeners. + * @example + * Filter example: + * chrome.mdns.onServiceList.addListener(() => { }, + * { 'serviceType': 'definitelyTyped._tcp.local' }); */ - const onServiceList: chrome.events.Event<(services: Service[]) => void>; + const onServiceList: chrome.events.FilteredEvent<(services: Service[]) => void, ServiceTypes>; } // #endregion @@ -10698,6 +10736,14 @@ declare namespace chrome { // #endregion // #region chrome.webViewRequest + ///////////////////// + // WebView Request // + ///////////////////// + /** + * @requires Permissions: 'webview' + * @description + * Use the *chrome.webViewRequest* API to intercept, block, or modify requests in-flight. + */ namespace webViewRequest { type Stage = 'onBeforeRequest' | 'onBeforeSendHeaders' | 'onHeadersReceived' | 'onAuthRequired'; type DeclarativeWebRequestEventList = @@ -11295,7 +11341,7 @@ declare namespace chrome { * @constructor */ const Event: { - new (): chrome.events.Event; + new (): chrome.events.Event; } // #endregion diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index b2dbc60f0b..dfae00f342 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -828,7 +828,14 @@ chrome.instanceID; // @todo TODO Tests chrome.management; // @todo TODO Tests -chrome.mdns; // @todo TODO Tests +// #region chrome.mdns +chrome.mdns.onServiceList.addListener( + () => { }, + { 'serviceType': 'definitelyTyped._tcp.local' }); +chrome.mdns.onServiceList.addListener(function (services) { + chrome.mdns.forceDiscovery(() => { return true; }); +}, { 'serviceType': '_googlecast._tcp.local' }); +// #endregion // #region chrome.mediaGalleries @@ -1299,7 +1306,23 @@ chrome.usb.getUserSelectedDevices({ // #endregion -chrome.virtualKeyboard; // @todo TODO Tests +// #region chrome.virtualKeyboard +chrome.virtualKeyboard.restrictFeatures( + { + autoCompleteEnabled: false, + autoCorrectEnabled: false, + spellCheckEnabled: false, + voiceInputEnabled: false, + handwritingEnabled: false + }, + (update) => { + if (update.autoCompleteEnabled = false) { + return true; + } + } +); +// #endregion + chrome.vpnProvider; // @todo TODO Tests chrome.wallpaper; // @todo TODO Tests chrome.webViewRequest; // @todo TODO Tests @@ -1383,7 +1406,7 @@ wve.request.onRequest.addRules([rule]); // #endregion -//#region Embedding & AppView +// #region Embedding & AppView chrome.app.runtime.onEmbedRequested.addListener((request) => { request.allow('foobar.html'); }); From 888a13a60843a3b35be13496c5cff983dde85273 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 11:54:47 +0200 Subject: [PATCH 099/289] chrome.storage Updated typings and tests --- types/chrome-apps/index.d.ts | 94 +++++++++++++++++++++------------ types/chrome-apps/test/index.ts | 41 +++++++++++++- 2 files changed, 100 insertions(+), 35 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 748e1db4a0..1becbe95a6 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5246,6 +5246,7 @@ declare namespace chrome { * @since Chrome 44. */ const MAX_SERVICE_INSTANCES_PER_EVENT: integer; + /** * Immediately issues a multicast DNS query for all service types. * |callback| is invoked immediately. @@ -8826,7 +8827,21 @@ declare namespace chrome { * @since Chrome 20. */ namespace storage { - interface StorageArea { + interface StorageAreaRead { + /** + * Gets one or more items from storage. + * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). + * Parameter items: Object with items in their key-value mappings. + */ + get(callback: (items: { [key: string]: any }) => void): void; + /** + * Gets one or more items from storage. + * @param keys A single key to get, list of keys to get, or a interface specifying default values. + * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. + * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). + * Parameter items: Object with items in their key-value mappings. + */ + get(keys: string | string[] | Object | null, callback: (items: { [key: string]: any }) => void): void; /** * Gets the amount of space (in bytes) being used by one or more items. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). @@ -8840,6 +8855,8 @@ declare namespace chrome { * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: integer) => void): void; + } + interface StorageAreaWrite { /** * Removes all items from storage. * @param callback Optional. @@ -8861,22 +8878,10 @@ declare namespace chrome { * Callback on success, or on failure (in which case runtime.lastError will be set). */ remove(keys: string | string[], callback?: () => void): void; - /** - * Gets one or more items from storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param keys A single key to get, list of keys to get, or a interface specifying default values. - * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(keys: string | string[] | Object | null, callback: (items: { [key: string]: any }) => void): void; } + interface StorageArea extends StorageAreaRead, StorageAreaWrite { } + interface StorageChange { /** The new value of the item, if there is a new value. */ newValue?: any; @@ -8885,38 +8890,59 @@ declare namespace chrome { } interface LocalStorageArea extends StorageArea { - /** The maximum amount (in bytes) of data that can be stored in local storage, + /** + * The maximum amount (in bytes) of data that can be stored in local storage, * as measured by the JSON stringification of every value plus every key's length. * This value will be ignored if the extension has the unlimitedStorage permission. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. + * @see Permissions: 'unlimitedStorage' * @default 5242880 */ - QUOTA_BYTES: integer; + readonly QUOTA_BYTES: 5242880; } interface SyncStorageArea extends StorageArea { - /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: chrome.deprecated; - /** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: integer; - /** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */ - QUOTA_BYTES_PER_ITEM: integer; - /** The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set runtime.lastError. */ - MAX_ITEMS: integer; + /** The maximum total amount (in bytes) of data that can be stored in + * sync storage, as measured by the JSON stringification of every value + * plus every key's length. Updates that would cause this limit to be + * exceeded fail immediately and set runtime.lastError. + */ + readonly QUOTA_BYTES: 102400; /** - * The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. + * The maximum size (in bytes) of each individual item in sync storage, + * as measured by the JSON stringification of its value plus its key length. + * Updates containing items larger than this limit will fail immediately and + * set runtime.lastError. + */ + readonly QUOTA_BYTES_PER_ITEM: 8192; + /** + * The maximum number of items that can be stored in sync storage. + * Updates that would cause this limit to be exceeded will fail immediately + * and set runtime.lastError. + */ + readonly MAX_ITEMS: 512; + /** + * The maximum number of set, remove, or clear operations that can be performed each hour. + * This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - MAX_WRITE_OPERATIONS_PER_HOUR: integer; + readonly MAX_WRITE_OPERATIONS_PER_HOUR: 1800; /** - * The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. + * The maximum number of set, remove, or clear operations that can be performed each minute. + * This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. * @since Chrome 40. */ - MAX_WRITE_OPERATIONS_PER_MINUTE: integer; + readonly MAX_WRITE_OPERATIONS_PER_MINUTE: 120; + /** + * @deprecated since Chrome 40. + * The storage.sync API no longer has a sustained write operation quota. + */ + readonly MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: chrome.deprecated; } + interface ManagedStorageArea extends StorageAreaRead { } - interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> { } + type StorageAreas = 'local' | 'sync' | 'managed'; /** Items in the local storage area are local to each machine. */ const local: LocalStorageArea; @@ -8924,13 +8950,15 @@ declare namespace chrome { 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. + * 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. */ - const managed: StorageArea; + const managed: ManagedStorageArea; /** Fired when one or more items change. */ - const onChanged: StorageChangedEvent; + const onChanged: chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: StorageAreas) => void>; } // #endregion diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index dfae00f342..a08a6cc833 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -833,7 +833,7 @@ chrome.mdns.onServiceList.addListener( () => { }, { 'serviceType': 'definitelyTyped._tcp.local' }); chrome.mdns.onServiceList.addListener(function (services) { - chrome.mdns.forceDiscovery(() => { return true; }); + chrome.mdns.forceDiscovery(() => { return chrome.mdns.MAX_SERVICE_INSTANCES_PER_EVENT === 2048; }); }, { 'serviceType': '_googlecast._tcp.local' }); // #endregion @@ -1233,7 +1233,44 @@ chrome.sockets.udp.create({}, (createInfo) => { // #endregion -chrome.storage; // @todo TODO Tests +// #region chrome.storage + +// LOCAL +chrome.storage.local.clear(); +chrome.storage.local.clear(() => { }); +chrome.storage.local.get('test', () => { }); +chrome.storage.local.get(() => { }); +chrome.storage.local.getBytesInUse((bytesInUse) => { + return (bytesInUse > 100); +}); +chrome.storage.local.set({ data: 'example' }, () => { console.log('done'); }); + +// SYNC +chrome.storage.sync.clear(); +chrome.storage.sync.clear(() => { }); +chrome.storage.sync.get('test', () => { }); +chrome.storage.sync.get(() => { }); +chrome.storage.sync.getBytesInUse((bytesInUse) => { + return (bytesInUse > 100); +}); +chrome.storage.sync.set({ data: 'example' }, () => { console.log('done'); }); + +// MANAGED +chrome.storage.managed.get('test', () => { }); +chrome.storage.managed.get(() => { }); +chrome.storage.managed.getBytesInUse((bytesInUse) => { + return (bytesInUse > 100); +}); +// chrome.storage.managed.set({ data: 'example' }, () => { console.log('done'); }); // Should not be allowed + +// EVENT +chrome.storage.onChanged.addListener((changes, areaName) => { + if (changes.length > 0) { + return areaName === 'managed'; + } +}); + +// #endregion // #region chrome.syncFileSystem From e9e984c161c6bdab117be542b2bf8e09ea4c87cc Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 13:12:04 +0200 Subject: [PATCH 100/289] More tests added + credits for source + fixed typings --- types/chrome-apps/index.d.ts | 81 +++++++++------ types/chrome-apps/test/index.ts | 172 +++++++++++++++++++++++++++++++- 2 files changed, 219 insertions(+), 34 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 1becbe95a6..2d63dc6330 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -6468,13 +6468,11 @@ declare namespace chrome { namespace permissions { interface Permissions { /** - * Optional. * List of named permissions (does not include hosts or origins). * Anything listed here must appear in the optional_permissions list in the manifest. */ - origins?: chrome.runtime.OptionalPermissions[]; + permissions?: chrome.runtime.OptionalPermission[]; /** - * Optional. * List of origin permissions. * Anything listed here must be a subset of a host that appears in the * optional_permissions list in the manifest. For example, if @@ -6482,33 +6480,33 @@ declare namespace chrome { * you can request an origin of http://help.example.com/. * Any path is ignored. */ - permissions?: chrome.runtime.UrlMatches[] | string[]; + origins?: chrome.runtime.UrlMatches[] | string[]; } - interface PermissionEvent extends chrome.events.Event<(permissions: chrome.runtime.Permission[]) => void> { } + interface PermissionEvent extends chrome.events.Event<(permissions: Permissions) => void> { } /** * Checks if the app has the specified permissions. - * @param callback Parameter result: True if the app has the specified permissions. + * @param callback Parameter *result*: True if the app has the specified permissions. */ - function contains(permissions: chrome.runtime.Permission[], callback: (result: boolean) => void): void; + function contains(permissions: Permissions, callback: (result: boolean) => void): void; /** * Gets the app's current set of permissions. - * @param callback Parameter permissions: The app's active permissions. + * @param callback Parameter *permissions*: The app's active permissions. */ - function getAll(callback: (permissions: chrome.runtime.Permission[]) => 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] Parameter granted: True if the user granted the specified permissions. + * @param [callback] Parameter *granted*: True if the user granted the specified permissions. */ - function request(permissions: chrome.runtime.Permission[], 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] Parameter removed: True if the permissions were removed. + * @param [callback] Parameter *removed*: True if the permissions were removed. */ - function remove(permissions: chrome.runtime.Permission[], callback?: (removed: boolean) => void): void; + function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; /** Fired when access to permissions has been removed from the app. */ const onRemoved: PermissionEvent; @@ -6565,7 +6563,7 @@ declare namespace chrome { * empty list, however, certificates of any type will be returned. * @see ClientCertificateType */ - certificateTypes: ToStringLiteral; + certificateTypes: ToStringLiteral[]; /** * List of distinguished names of certificate authorities allowed by the @@ -7072,12 +7070,11 @@ declare namespace chrome { 'tts' | 'wallpaper'; - type OptionalPermission = Exclude; /** * Optional permissions - * @see NotAllowedAsOptionalPermissions for permissions that you're not allowed to set. + * @see NotAllowedAsOptionalPermissions for permissions that you're not allowed to set on demand. */ - type OptionalPermissions = Array | Array; + type OptionalPermission = Exclude; type Permission = /** Gives your app access to the chrome.alarms API. */ @@ -7683,7 +7680,7 @@ declare namespace chrome { * at run time rather than install time, so users understand why the * permissions are needed and grant only those that are necessary. */ - optional_permissions?: OptionalPermissions; + optional_permissions?: OptionalPermission[] | Array | Array; /** * Permissions help to limit damage if your app is compromised by malware. @@ -10630,11 +10627,20 @@ declare namespace chrome { SHOW_CONFIGURE_DIALOG: 'showConfigureDialog' }; interface VpnSessionParameters { - /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ + /** + * IP address for the VPN interface in CIDR notation. + * IPv4 is currently the only supported mode. + */ address: string; - /** 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; - /** MTU setting for the VPN interface. (default: 1500 bytes) */ + /** + * MTU setting for the VPN interface (default 1500 bytes). + * @default '1500' + */ mtu?: string; /** * Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. @@ -10659,7 +10665,22 @@ declare namespace chrome { /** A list of search domains. (default: no search domain) */ domainSearch?: string[]; /** A list of IPs for the DNS servers. */ - dnsServer: string[]; + dnsServers: string[]; + /** + * @since Chrome 51. + * Whether or not the VPN extension implements auto-reconnection. + * If true, the *linkDown*, *linkUp*, *linkChanged*, *suspend*, and *resume* + * platform messages will be used to signal the respective events. + * + * If false, the system will forcibly disconnect the VPN if the network + * topology changes, and the user will need to reconnect manually. + * + * This property is new in Chrome 51; it will generate an exception in + * earlier versions. try/catch can be used to conditionally enable the + * feature based on browser support. + * @default false + */ + reconnect: boolean; } /** @@ -10724,21 +10745,23 @@ declare namespace chrome { * @since Chrome 43. */ namespace wallpaper { - const WallpaperLayout: { - 'STRETCH': 'STRETCH', - 'CENTER': 'CENTER', - 'CENTER_CROPPED': 'CENTER_CROPPED' - }; + enum WallpaperLayout { + STRETCH = 'STRETCH', + CENTER = 'CENTER', + CENTER_CROPPED = 'CENTER_CROPPED' + } + type WallpaperLayoutType = 'STRETCH' | 'CENTER' | 'CENTER_CROPPED'; + interface WallpaperDetails { /** The jpeg or png encoded wallpaper image. */ - data?: any; + data?: ArrayBuffer; /** The URL of the wallpaper to be set. */ url?: string; /** * The supported wallpaper layouts. * @see WallpaperLayout */ - layout: ToStringLiteral; + layout: WallpaperLayout | WallpaperLayoutType; /** The file name of the saved wallpaper. */ filename: string; /** True if a 128x60 thumbnail should be generated. */ diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index a08a6cc833..1831ec90f5 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,3 +1,9 @@ +/** + * Some of the tests are based on examples found in the Chromium documentation or source. + * @author Nikolai Ommundsen (niikoo {@link https://github.com/niikoo}) + * @author The Chromium Authors + */ + import runtime = chrome.app.runtime; const cwindow = chrome.app.window; @@ -921,9 +927,116 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { chrome.notifications; // @todo TODO Tests -chrome.platformKeys; // @todo TODO Tests +// #region chrome.platformKeys -chrome.permissions; // @todo TODO Tests +var data = { + trusted_l1_leaf_cert: 'l1_leaf.der', + trusted_l1_interm_cert: 'l1_interm.der', + trusted_l2_leaf_cert: 'l2_leaf.der', + client_1: 'client_1.der', + client_2: 'client_2.der', + client_1_spki: 'client_1_spki.der', + client_1_issuer_dn: { + buffer: new ArrayBuffer(16) + }, + raw_data: 'data', + signature_nohash_pkcs: 'signature_nohash_pkcs', + signature_client1_sha1_pkcs: 'signature_client1_sha1_pkcs', + signature_client2_sha1_pkcs: 'signature_client2_sha1_pkcs', +}; +function requestCA1(): chrome.platformKeys.ClientCertificateRequest { + return { + certificateTypes: [], + certificateAuthorities: [data.client_1_issuer_dn.buffer] + }; +} +chrome.platformKeys.selectClientCertificates( + { interactive: false, request: requestCA1() }, + (matches) => { + }); + +const requestECDSA: chrome.platformKeys.ClientCertificateRequest = { + certificateTypes: ['ecdsaSign'], + certificateAuthorities: [] +}; +chrome.platformKeys.selectClientCertificates( + { interactive: false, request: requestECDSA }, + (matches) => { + return matches.length; + }); + +if (chrome.platformKeys.subtleCrypto && + chrome.platformKeys.subtleCrypto() && + chrome.platformKeys.subtleCrypto().sign && + chrome.platformKeys.subtleCrypto().exportKey) { + console.log('Subtle crypto working (Y)') +} + +var keyParams = { + // Algorithm names are case-insensitive. + name: 'RSASSA-Pkcs1-V1_5', + hash: { name: 'sha-1' } +}; +chrome.platformKeys.getKeyPair( + data.client_1_issuer_dn.buffer, keyParams, + (publicKey, privateKey) => { + let expectedAlgorithm = { + modulusLength: 2048, + name: "RSASSA-PKCS1-v1_5", + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + hash: { name: 'SHA-1' } + }; + + if (expectedAlgorithm === publicKey.algorithm && + privateKey && + expectedAlgorithm === privateKey.algorithm) { + if (publicKey.type === 'public' && privateKey.type === 'private') { + console.log('All okay!'); + } + } + chrome.platformKeys.subtleCrypto() + .exportKey('spki', publicKey) + .then((actualPublicKeySpki) => { + if (new ArrayBuffer(100) === actualPublicKeySpki) { + return false; + } + }); + }); +var details = { + serverCertificateChain: [data.client_1_issuer_dn.buffer], + hostname: "l1_leaf" +}; +chrome.platformKeys.verifyTLSServerCertificate( + details, (result) => { + return result.trusted; + }); +// #endregion + +// #region chrome.permissions + +chrome.permissions.request({ permissions: ['storage'] }, (granted) => { + return granted && 'It was granted'; +}); + +chrome.permissions.getAll((permissions) => { + if (chrome.runtime.lastError || !permissions.permissions) { + return; + } + for (const permission of permissions.permissions) { + if (permission === 'alarms') { + return 'I knew it!'; + } + chrome.permissions.remove({ permissions: [permission] }, (removed) => { + return removed ? 'It was removed' : 'It was not removed'; + }); + } + chrome.permissions.contains({ origins: ['chrome://favicon/'] }, (doIHaveIt) => doIHaveIt ? 'yes' : 'neh'); + chrome.permissions.request( + { permissions: ['audio'] }, + () => { }); +}); + +// #endregion // #region chrome.power @@ -1360,9 +1473,58 @@ chrome.virtualKeyboard.restrictFeatures( ); // #endregion -chrome.vpnProvider; // @todo TODO Tests -chrome.wallpaper; // @todo TODO Tests -chrome.webViewRequest; // @todo TODO Tests +// #region chrome.vpnProvider + +const vpnParams = { + address: '127.0.0.1/32', + mtu: '1500', + exclusionList: ['127.0.0.1/32'], + inclusionList: ['0.0.0.0/0'], + dnsServers: ['1.1.1.1', '1.0.0.1', '8.8.8.8'], + reconnect: true +}; +chrome.vpnProvider.onConfigCreated.addListener((id, name, data) => { + console.log('Connected: ', id.toLowerCase(), name.toUpperCase(), JSON.stringify(data)); +}); +chrome.vpnProvider.createConfig('Local VPN', (id) => { + chrome.vpnProvider.setParameters(vpnParams, () => { + if (chrome.runtime.lastError) { + chrome.vpnProvider.notifyConnectionStateChanged('failure'); + throw chrome.runtime.lastError; + } + chrome.vpnProvider.notifyConnectionStateChanged('connected', () => { + chrome.vpnProvider.onPacketReceived.addListener(data => { + return data.byteLength > 0 ? data : undefined; + }); + chrome.vpnProvider.onConfigRemoved.addListener(id => id.toUpperCase()); + chrome.vpnProvider.onPlatformMessage.addListener((id, message) => { + if (typeof id === 'string') { + return message === 'connected'; + } + }); + chrome.vpnProvider.onUIEvent.addListener((event, id) => { + if (event === 'showAddDialog') { + return id; + } + }); + }); + }); +}); +// #endregion + +// #region chrome.wallpaper +chrome.wallpaper.setWallpaper({ + url: 'chrome://favicon/iconurl/https://www.google.com/favicon.ico', + layout: 'CENTER_CROPPED', + filename: 'test_wallpaper' +}, (thumbnail) => { + const imageUrl = thumbnail; +}); +chrome.wallpaper.setWallpaper({ + layout: chrome.wallpaper.WallpaperLayout.STRETCH, + filename: 'test_wallpaper2' +}, () => { }); +// #endregion // #region chrome.webViewRequest & WebView From 63b94dcb09882f2267a01a8eaf1641093ae9426c Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 13:27:19 +0200 Subject: [PATCH 101/289] Tests for chrome.instanceID --- types/chrome-apps/index.d.ts | 2 +- types/chrome-apps/test/index.ts | 46 ++++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 2d63dc6330..053b3b67cf 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -6425,7 +6425,7 @@ declare namespace chrome { * @param options Contents of the notification to update to. * @param [callback] Called to indicate whether a matching notification existed. */ - function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; + function update(notificationId: string, options: Partial, callback?: (wasUpdated: boolean) => void): void; /** * Clears the specified notification. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 1831ec90f5..eba7ff19c8 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -832,7 +832,23 @@ chrome.idle; // @todo TODO Tests chrome.instanceID; // @todo TODO Tests -chrome.management; // @todo TODO Tests +// #region chrome.management + +chrome.management.getSelf((result) => { + chrome.management.getPermissionWarningsByManifest( + JSON.stringify(chrome.runtime.getManifest()), + (warnings) => { + console.log(warnings.join('\r\n')); + }); + if (result.isApp) { + return 'Of course!'; + } else { + chrome.management.uninstallSelf({ + showConfirmDialog: false + }, () => console.log('Goodbye')); + } +}); +// #endregion // #region chrome.mdns chrome.mdns.onServiceList.addListener( @@ -925,10 +941,34 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { // #endregion -chrome.notifications; // @todo TODO Tests +// #region chrome.notifications + +let nID: string; + +chrome.notifications.create({ + type: 'basic', + iconUrl: 'stay_hydrated.png', + title: 'Time to Hydrate', + message: 'Everyday I\'m Guzzlin\'!', + buttons: [ + { title: 'Keep it Flowing.' } + ], + priority: 0 +}, (notificationId) => { + nID = notificationId; + chrome.notifications.update(nID, { + title: 'Updated title' + }); + chrome.notifications.onButtonClicked.addListener((_id, buttonIndex) => { + if (buttonIndex === 0) { + chrome.notifications.clear(nID, function () { }); + } + }); +}); + +// #endregion // #region chrome.platformKeys - var data = { trusted_l1_leaf_cert: 'l1_leaf.der', trusted_l1_interm_cert: 'l1_interm.der', From 56c3bc683e7cb34f3fb0757de274b76671d94cbb Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 13:36:54 +0200 Subject: [PATCH 102/289] Tests for chrome.idle --- types/chrome-apps/test/index.ts | 37 +++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index eba7ff19c8..a34b29c6c1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -828,9 +828,42 @@ chrome.identity.getAuthToken({ interactive: true }, (token) => { // #endregion -chrome.idle; // @todo TODO Tests +// #region chrome.idle -chrome.instanceID; // @todo TODO Tests +chrome.idle.onStateChanged.addListener((newState) => { + if (newState === 'active') { + return true; + } +}); +chrome.idle.queryState(60, (state) => { + return state === 'idle'; +}); +chrome.idle.setDetectionInterval(20); + +// #endregion + +// #region chrome.instanceID + +chrome.instanceID.getCreationTime((creationTime) => { + if (creationTime === 0) { + return true; + } +}); +chrome.instanceID.getID((instanceId) => { + if (instanceId) { + chrome.instanceID.getCreationTime((creationTime) => { + if (creationTime !== 0) { + chrome.instanceID.getToken( + { "authorizedEntity": "1", "scope": "GCM", "options": { "foo": "1" } }, + (token) => { + return token; + }); + } + }) + } +}) + +// #endregion // #region chrome.management From 0aba0089b3bd8c56287f71bb1dcab29a2139c11e Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 13:54:11 +0200 Subject: [PATCH 103/289] Tests for chrome.gcm --- types/chrome-apps/index.d.ts | 17 +++++------------ types/chrome-apps/test/index.ts | 8 ++++++++ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 053b3b67cf..7ce488deeb 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -4181,16 +4181,9 @@ declare namespace chrome { */ 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; - } + type DisallowedKeys = 'collapse_key' | 'goog' | 'goog.' | 'GOOG' | 'GOOG.' | 'google' | 'GOOGLE'; + type IGCMDataSend = Record, any>; + type IGCMDataReceive = Record; interface OutgoingMessage { /** The ID of the server to send the message to as assigned by Google API Console. */ @@ -4208,12 +4201,12 @@ declare namespace chrome { * * Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. **/ - data: IGCMData; + data: IGCMDataSend; } interface IncomingMessage { /** The message data. */ - data: IGCMData; + data: IGCMDataReceive; /** * Optional. * The sender who issued the message. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index a34b29c6c1..6537914a5e 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -775,6 +775,14 @@ gcmMessage.data = { /*goog: 'any', should not be allowed, and it is not :) */ test: true }; +const eventHandler = (message: chrome.gcm.IncomingMessage) => { + console.log('From: ', message.from, 'collapseKey:', message.collapseKey); + return message.data['google']; +} +chrome.gcm.onMessage.addListener(eventHandler); +chrome.gcm.onMessage.removeListener(eventHandler); +chrome.gcm.onMessagesDeleted.addListener(() => { }); +chrome.gcm.onSendError.addListener((error) => { console.error(error.detail, error.errorMessage, error.messageId); }); // #endregion From e8c8f288bc232b455d60bb85220d01ba5d6bf47c Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 14:09:05 +0200 Subject: [PATCH 104/289] chrome.enterprise tests --- types/chrome-apps/test/index.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 6537914a5e..5fde0c2e36 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -703,6 +703,14 @@ if (deviceAttr.getDirectoryDeviceId && deviceAttr.getDeviceAssetId) { } } +chrome.enterprise.deviceAttributes.getDirectoryDeviceId((deviceId) => { + return deviceId.substring(0, deviceId.length - 1); +}) +chrome.enterprise.deviceAttributes.getDeviceSerialNumber((sn) => console.log(sn.trim())); +chrome.enterprise.deviceAttributes.getDeviceAssetId((assetId) => console.log(assetId.toLowerCase())); +chrome.enterprise.deviceAttributes.getDeviceAnnotatedLocation((loc) => loc.charAt(0)); + + // ENTERPRISE - PLATFORM KEYS if (chrome.enterprise.platformKeys.getTokens) { @@ -712,6 +720,31 @@ if (chrome.enterprise.platformKeys.getTokens) { } } } +const tokenId = 'tokenid....'; +chrome.enterprise.platformKeys.importCertificate(tokenId, new ArrayBuffer(8), () => { }); +chrome.enterprise.platformKeys.getCertificates(tokenId, (certificates) => { + certificates.map((cert) => { + chrome.enterprise.platformKeys.removeCertificate(tokenId, cert, () => { }); + }); +}); +chrome.enterprise.platformKeys.getTokens((tokens) => { + const algorithm = { + name: "RSASSA-PKCS1-v1_5", + // RsaHashedKeyGenParams + modulusLength: 2048, + publicExponent: + new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 + hash: { + name: "SHA-1", + } + }; + tokens.map(token => { + token.subtleCrypto.generateKey(algorithm, false, ["sign"]).then((val) => { + + }) + }); +}); + // #endregion chrome.enterprise // #region chrome.Event From cd3e2542b492f84a8298e8f33023ed5a5d66c91f Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Thu, 23 Aug 2018 14:18:30 +0200 Subject: [PATCH 105/289] Test updates --- types/chrome-apps/appview.d.ts | 2 +- types/chrome-apps/test/index.ts | 54 +++++++++++++++++++++++++++------ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/types/chrome-apps/appview.d.ts b/types/chrome-apps/appview.d.ts index 6924f9ca21..76fe7ccf61 100644 --- a/types/chrome-apps/appview.d.ts +++ b/types/chrome-apps/appview.d.ts @@ -31,7 +31,7 @@ declare namespace AppView { /** The ID of the app that sent the embedding request. */ embedderId: string; /** Optional developer specified data that the app to be embedded can use when making an embedding decision. */ - data?: Object; + data?: any; /** * Allows the embedding request * @param url Specifies the content to be embedded. diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 5fde0c2e36..30d20c408d 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -326,9 +326,27 @@ const ManifestJSONTest1: chrome.runtime.Manifest = { // #region chrome.alarms -chrome.alarms.create('name', { +chrome.alarms.create('name1', { delayInMinutes: 10 -}) +}); +chrome.alarms.create('name2', { + delayInMinutes: 10, + periodInMinutes: 100 +}); +chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name === 'name1') { + chrome.alarms.get('name1', (_alarm) => { + if (alarm === _alarm) { + chrome.alarms.getAll((alarms) => { + chrome.alarms.clear('name2'); + chrome.alarms.clearAll(); + }) + } + }) + return alarm.scheduledTime; + } +}); + // #endregion // #region chrome.app.* @@ -437,12 +455,17 @@ chrome.audio.getDevices({}, (audioDeviceInfoList) => { }); chrome.app.runtime.onEmbedRequested.addListener((request) => { - if (!request.data.message) { - request.allow('default.html'); - } else if (request.data.message == 'camera') { - request.allow('camera.html'); - } else { - request.deny(); + if (request === undefined || request.data === undefined) { + return false; + } + if (typeof request.data === 'object') { + if (!request.data['message']) { + request.allow('default.html'); + } else if (request.data.message == 'camera') { + request.allow('camera.html'); + } else { + request.deny(); + } } }); @@ -690,7 +713,20 @@ chrome.dns.resolve("github.com", (info) => { // #endregion -chrome.documentScan; // @todo TODO Tests +// #region chrome.documentScan + +chrome.documentScan.scan({ + maxImages: 100, + mimeTypes: ['image/jpeg'] +}, (results) => { + results.dataUrls.map(urlData => { + var scannedImage = document.createElement('img'); + scannedImage.title = 'Mime type: ' + results.mimeType; + scannedImage.src = urlData; + }); +}); + +// #endregion // #region chrome.enterprise.* // ENTERPRISE - DEVICE ATTRIBUTES From 0c79a12f676fefdccf3d047925094a45ff751d29 Mon Sep 17 00:00:00 2001 From: Jani Date: Thu, 23 Aug 2018 16:01:26 +0300 Subject: [PATCH 106/289] [@types/webpack-dev-server] Fix stats to webpack.Options.Stats This commit adds more stats options available to webpack-dev-server. The webpack site [0] states that all webpack.Options.Stats are supported on webpack-dev-server: "For webpack-dev-server, this property needs to be in the devServer object." [0]: https://webpack.js.org/configuration/stats/ --- types/webpack-dev-server/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webpack-dev-server/index.d.ts b/types/webpack-dev-server/index.d.ts index 435d2547d9..62b6cedbc2 100644 --- a/types/webpack-dev-server/index.d.ts +++ b/types/webpack-dev-server/index.d.ts @@ -158,7 +158,7 @@ declare namespace WebpackDevServer { * This option lets you precisely control what bundle information gets displayed. * This can be a nice middle ground if you want some bundle information, but not all of it. */ - stats?: string | webpack.Stats; + stats?: string | webpack.Options.Stats; /** This option lets the browser open with your local IP. */ useLocalIp?: boolean; /** Tell the server to watch the files served by the devServer.contentBase option. File changes will trigger a full page reload. */ From c966aca3bd501d48e35aa87e41e12665adf1bb32 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Thu, 23 Aug 2018 18:43:22 +0200 Subject: [PATCH 107/289] Update export name -- Tests improvements -- Restore version number --- types/gulp-jsonmin/gulp-jsonmin-tests.ts | 14 ++++++++++++-- types/gulp-jsonmin/index.d.ts | 8 ++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/types/gulp-jsonmin/gulp-jsonmin-tests.ts b/types/gulp-jsonmin/gulp-jsonmin-tests.ts index 23d4ea5427..e13ec2c69f 100644 --- a/types/gulp-jsonmin/gulp-jsonmin-tests.ts +++ b/types/gulp-jsonmin/gulp-jsonmin-tests.ts @@ -1,4 +1,14 @@ +import gulp = require('gulp'); import gulpJsonmin = require('gulp-jsonmin'); -gulpJsonmin(); -gulpJsonmin({ verbose: true }); +gulp.task('build', () => { + return gulp.src('*.json') + .pipe(gulpJsonmin()) + .pipe(gulp.dest('dist')); +}); + +gulp.task('build', () => { + return gulp.src('*.json') + .pipe(gulpJsonmin({ verbose: true })) + .pipe(gulp.dest('dist')); +}); diff --git a/types/gulp-jsonmin/index.d.ts b/types/gulp-jsonmin/index.d.ts index b246ead5b4..f5502d95cd 100644 --- a/types/gulp-jsonmin/index.d.ts +++ b/types/gulp-jsonmin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for gulp-jsonmin 1.2 +// Type definitions for gulp-jsonmin 1.1 // Project: https://github.com/englercj/gulp-jsonmin // Definitions by: Romain Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,12 +7,12 @@ import { Transform } from 'stream'; -declare function jsonmin(options?: jsonmin.Options): Transform; +declare function GulpJsonmin(options?: GulpJsonmin.Options): Transform; -declare namespace jsonmin { +declare namespace GulpJsonmin { interface Options { verbose?: boolean; } } -export = jsonmin; +export = GulpJsonmin; From 1fbb55213f263b44b6997380c38248ef448f07bd Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 23 Aug 2018 09:43:32 -0700 Subject: [PATCH 108/289] Fix w3cwebsocket type definitions --- types/websocket/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/websocket/index.d.ts b/types/websocket/index.d.ts index cd17039b1c..0a15be7d69 100644 --- a/types/websocket/index.d.ts +++ b/types/websocket/index.d.ts @@ -679,9 +679,11 @@ declare class w3cwebsocket { url: string; readyState: number; protocol?: string; - extenstions: IExtension[]; + extensions: IExtension[]; bufferedAmount: number; + binaryType: "arraybuffer"; + CONNECTING: number; OPEN: number; CLOSING: number; @@ -692,7 +694,7 @@ declare class w3cwebsocket { onclose: () => void; onmessage: (message: any) => void; - constructor(url: string, protocols?: string[], origin?: string, headers?: any[], requestOptions?: object, clientConfig?: IClientConfig); + constructor(url: string, protocols?: string | string[], origin?: string, headers?: any[], requestOptions?: object, clientConfig?: IClientConfig); send(data: Buffer): void; send(data: IStringified): void; From 6013bd6f9de17f35884e59eade39fbdc6e766f55 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Thu, 23 Aug 2018 19:00:07 +0200 Subject: [PATCH 109/289] Change the export case to be more semantically correct --- types/gulp-jsonmin/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/gulp-jsonmin/index.d.ts b/types/gulp-jsonmin/index.d.ts index f5502d95cd..d5faa2b969 100644 --- a/types/gulp-jsonmin/index.d.ts +++ b/types/gulp-jsonmin/index.d.ts @@ -7,12 +7,12 @@ import { Transform } from 'stream'; -declare function GulpJsonmin(options?: GulpJsonmin.Options): Transform; +declare function gulpJsonmin(options?: gulpJsonmin.Options): Transform; -declare namespace GulpJsonmin { +declare namespace gulpJsonmin { interface Options { verbose?: boolean; } } -export = GulpJsonmin; +export = gulpJsonmin; From e5a997d5a4b64743eceab1a9751ddd51e49cae58 Mon Sep 17 00:00:00 2001 From: Marko K Date: Thu, 23 Aug 2018 21:20:50 +0300 Subject: [PATCH 110/289] refactor: GeoJSON.Geometry instead of custom Geometry union type --- types/mapbox-gl/index.d.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 78ce94cb56..3d04db607c 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -63,9 +63,9 @@ declare namespace mapboxgl { isRotating(): boolean; - queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: { layers?: string[], filter?: any[] }): GeoJSON.Feature[]; + queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: { layers?: string[], filter?: any[] }): GeoJSON.Feature[]; - querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; + querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; setStyle(style: mapboxgl.Style | string, options?: { diff?: boolean, localIdeographFontFamily?: string }): this; @@ -530,8 +530,6 @@ declare namespace mapboxgl { type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } - export type GeoJSONGeometry = GeoJSON.Point | GeoJSON.LineString | GeoJSON.MultiPoint | GeoJSON.Polygon | GeoJSON.MultiLineString | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection; - /** * GeoJSONSource */ @@ -545,17 +543,17 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); - setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; getClusterExpansionZoom(clusterId: number, callback: (error: any, zoom: number) => void): this; - getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; - getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; } export interface GeoJSONSourceOptions { - data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; maxzoom?: number; From 5f178511caeb96021fa64676f560b658a8340d8c Mon Sep 17 00:00:00 2001 From: Kendra Knittel Date: Thu, 23 Aug 2018 14:22:14 -0400 Subject: [PATCH 111/289] Make p-cancellable types compatible with 0.5 - Append `onCancel` instead of prepending (https://github.com/sindresorhus/p-cancelable/commit/8e3aaec245492f3a38b5d4f74e9861cf3f334616) - Rename `PCancelable.canceled` to `PCancelable.isCanceled` (https://github.com/sindresorhus/p-cancelable/commit/433d25c8fcf08acd127f0249bc8377379c98363c) - Add `CancelError.isCanceled` (https://github.com/sindresorhus/p-cancelable/commit/ad14c228a9c53f939ed6de068cfe83b5fa27fe1c) - Add ability to provide cancel reason (https://github.com/sindresorhus/p-cancelable/commit/a97b12b309f7ab60f8bfa22883b052c17b32a04e) --- types/p-cancelable/index.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/types/p-cancelable/index.d.ts b/types/p-cancelable/index.d.ts index 4f26cd17ca..bfa30c1fd8 100644 --- a/types/p-cancelable/index.d.ts +++ b/types/p-cancelable/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for p-cancelable 0.3 +// Type definitions for p-cancelable 0.5 // Project: https://github.com/sindresorhus/p-cancelable#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,20 +11,22 @@ interface PCancelableConstructor extends PromiseConstructor { readonly prototype: PCancelable.PCancelable; readonly CancelError: PCancelable.CancelErrorConstructor; fn(wrapper: (onCancel: (fn?: () => void) => void, input: T) => PromiseLike): (input: T) => PCancelable.PCancelable; - new(executor: (onCancel: (fn?: () => void) => void, resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): PCancelable.PCancelable; + new(executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void, onCancel: (fn?: () => void) => void) => void): PCancelable.PCancelable; } declare namespace PCancelable { interface PCancelable extends Promise { - readonly canceled: boolean; - cancel(): void; + readonly isCanceled: boolean; + cancel(reason?: string): void; + } interface CancelErrorConstructor extends ErrorConstructor { - new (): CancelError; + new (reason?: string): CancelError; } interface CancelError extends Error { readonly name: 'CancelError'; + readonly isCanceled: boolean; } } From a1dadf7b216f65c63795ef92609b805505f510fd Mon Sep 17 00:00:00 2001 From: Megan Riel-Mehan Date: Thu, 23 Aug 2018 11:26:47 -0700 Subject: [PATCH 112/289] updated selection interface to include selection description --- types/plotly.js/index.d.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 84cad93b48..3a5784ae21 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -49,10 +49,20 @@ export interface PlotCoordinate { pointNumber: number; } -export interface PlotSelectionEvent { - points: PlotCoordinate[]; +export interface SelectionDescription { + x: number[], + y: number[], } +export type PlotSelectedData = Partial; + +export interface PlotSelectionEvent { + points: PlotSelectedData[]; + range?: SelectionDescription; + lassoPoints?: SelectionDescription; +} + + export type PlotRestyleEvent = [ any, // update object -- attribute updated: new value number[] // array of traces updated From beacb0dee8904a20b8806f5f94c5279e3f2065b7 Mon Sep 17 00:00:00 2001 From: Kendra Knittel Date: Thu, 23 Aug 2018 14:42:56 -0400 Subject: [PATCH 113/289] Update p-cancelable-tests.ts --- types/p-cancelable/p-cancelable-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/p-cancelable/p-cancelable-tests.ts b/types/p-cancelable/p-cancelable-tests.ts index ca5f728e18..8bd3790e08 100644 --- a/types/p-cancelable/p-cancelable-tests.ts +++ b/types/p-cancelable/p-cancelable-tests.ts @@ -3,7 +3,7 @@ import PCancelableCtor = require('p-cancelable'); import { EventEmitter } from "events"; -const cancelablePromise: PCancelableCtor.PCancelable<{}> = new PCancelableCtor((onCancel, resolve, reject) => { +const cancelablePromise: PCancelableCtor.PCancelable<{}> = new PCancelableCtor((resolve, reject, onCancel) => { class Worker extends EventEmitter { close() { } @@ -24,7 +24,7 @@ cancelablePromise console.log('Operation finished successfully:', value); }) .catch(reason => { - if (cancelablePromise.canceled) { + if (cancelablePromise.isCanceled) { // Handle the cancelation here console.log('Operation was canceled'); return; @@ -56,7 +56,7 @@ const fn = PCancelableCtor.fn((onCancel: (fn?: () => void) => void, input: strin const promise = fn('input'); let num: number; promise.then(innum => num = innum); -if (!promise.canceled) { +if (!promise.isCanceled) { promise.cancel(); } From 5780ef042932f95803c90cc66597788c48f90e61 Mon Sep 17 00:00:00 2001 From: Kendra Knittel Date: Thu, 23 Aug 2018 14:53:45 -0400 Subject: [PATCH 114/289] Remove stray newline --- types/p-cancelable/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/p-cancelable/index.d.ts b/types/p-cancelable/index.d.ts index bfa30c1fd8..775400bca8 100644 --- a/types/p-cancelable/index.d.ts +++ b/types/p-cancelable/index.d.ts @@ -18,7 +18,6 @@ declare namespace PCancelable { interface PCancelable extends Promise { readonly isCanceled: boolean; cancel(reason?: string): void; - } interface CancelErrorConstructor extends ErrorConstructor { From dcbe648b6dae0468bfb67189d78a2892c66c9693 Mon Sep 17 00:00:00 2001 From: Marko K Date: Thu, 23 Aug 2018 21:26:17 +0300 Subject: [PATCH 115/289] feat: add customAttribution Adds feature: https://github.com/mapbox/mapbox-gl-js/pull/7033 --- types/mapbox-gl/index.d.ts | 8 ++++++-- types/mapbox-gl/mapbox-gl-tests.ts | 13 ++++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 3d04db607c..08623c37a9 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.47.0 +// Type definitions for Mapbox GL JS v0.48.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -226,6 +226,10 @@ declare namespace mapboxgl { /** ID of the container element */ container?: string | Element; + /** String or strings to show in an AttributionControl. + * Only applicable if options.attributionControl is `true`. */ + customAttribution?: string | string[]; + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ dragPan?: boolean; @@ -441,7 +445,7 @@ declare namespace mapboxgl { * Attribution */ export class AttributionControl extends Control { - constructor(options?: { compact?: boolean }); + constructor(options?: { compact?: boolean, customAttribution?: string | string[] }); } /** diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index 87297effda..783ee86f74 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -17,7 +17,8 @@ let map = new mapboxgl.Map({ minZoom: 1, maxZoom: 2, interactive: true, - attributionControl: false, + attributionControl: true, + customAttribution: '© YourCo', bearingSnap: 7, scrollZoom: true, maxBounds: [[-100,-90],[100,90]], @@ -387,6 +388,16 @@ let marker = new mapboxgl.Marker(undefined, {offset: [10, 0]}) .addTo(map); marker.remove(); + +/* + * LngLatBounds + */ let bool:boolean let bounds = new mapboxgl.LngLatBounds() bool = bounds.isEmpty() + +/* + * AttributionControl + */ +let attributionControl = new mapboxgl.AttributionControl({ compact: false, customAttribution: '© YourCo' }); +attributionControl.on('click', () => {}); From 13253643343e5efedd0f50f3aa9929a84f55e206 Mon Sep 17 00:00:00 2001 From: Megan Riel-Mehan Date: Thu, 23 Aug 2018 17:20:01 -0700 Subject: [PATCH 116/289] Renamed ScatterData and ScatterMarker since they're used for other plots --- types/plotly.js/index.d.ts | 820 +++++++++++++++++++------------------ 1 file changed, 411 insertions(+), 409 deletions(-) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 3a5784ae21..0e943ef569 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -29,7 +29,7 @@ export interface Point { export interface PlotScatterDataPoint { curveNumber: number; - data: ScatterData; + data: PlotData; pointIndex: number; pointNumber: number; x: number; @@ -57,12 +57,11 @@ export interface SelectionDescription { export type PlotSelectedData = Partial; export interface PlotSelectionEvent { - points: PlotSelectedData[]; + points: PlotScatterDataPoint[]; range?: SelectionDescription; lassoPoints?: SelectionDescription; } - export type PlotRestyleEvent = [ any, // update object -- attribute updated: new value number[] // array of traces updated @@ -151,10 +150,10 @@ export interface PlotlyHTMLElement extends HTMLElement { on(event: 'plotly_sliderend', callback: (event: SliderEndEvent) => void): void; on(event: 'plotly_sliderstart', callback: (event: SliderStartEvent) => void): void; on(event: 'plotly_event', callback: (data: any) => void): void; - on(event: 'plotly_beforeplot' , callback: (event: BeforePlotEvent) => boolean): void; + on(event: 'plotly_beforeplot', callback: (event: BeforePlotEvent) => boolean): void; on(event: 'plotly_afterexport' | 'plotly_afterplot' | 'plotly_animated' | 'plotly_animationinterrupted' | 'plotly_autosize' | 'plotly_beforeexport' | 'plotly_deselect' | 'plotly_doubleclick' | 'plotly_framework' | 'plotly_redraw' | - 'plotly_transitioning' | 'plotly_transitioninterrupted' , callback: () => void): void; + 'plotly_transitioning' | 'plotly_transitioninterrupted', callback: () => void): void; } export interface ToImgopts { @@ -394,32 +393,32 @@ export interface ModeBarButton { /** name / id of the buttons (for tracking) */ name: string; - /** - * text that appears while hovering over the button, - * enter null, false or '' for no hover text - */ + /** + * text that appears while hovering over the button, + * enter null, false or '' for no hover text + */ title: string; - /** - * svg icon object associated with the button - * can be linked to Plotly.Icons to use the default plotly icons - */ + /** + * svg icon object associated with the button + * can be linked to Plotly.Icons to use the default plotly icons + */ icon: string | Icon; /** icon positioning */ gravity?: string; - /** - * click handler associated with the button, a function of - * 'gd' (the main graph object) and - * 'ev' (the event object) - */ + /** + * click handler associated with the button, a function of + * 'gd' (the main graph object) and + * 'ev' (the event object) + */ click: ButtonClickEvent; - /** - * attribute associated with button, - * use this with 'val' to keep track of the state - */ + /** + * attribute associated with button, + * use this with 'val' to keep track of the state + */ attr?: string; /** initial 'attr' value, can be a function of gd */ @@ -436,12 +435,13 @@ export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int export type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; -export type Data = Partial; +export type Data = Partial; export type Color = string | Array | Array>; - +export type DataTransForm = Partial; +export type ScatterData = PlotData; // Bar Scatter -export interface ScatterData { - type: 'bar' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' |'surface'; +export interface PlotData { + type: 'bar' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; x: Datum[] | Datum[][] | TypedArray; y: Datum[] | Datum[][] | TypedArray; z: Datum[] | Datum[][] | Datum[][][] | TypedArray; @@ -456,7 +456,7 @@ export interface ScatterData { 'line.shape': 'linear' | 'spline' | 'hv' | 'vh' | 'hvh' | 'vhv'; 'line.smoothing': number; 'line.simplify': boolean; - marker: Partial; + marker: Partial; 'marker.symbol': string | string[]; // Drawing.symbolList 'marker.color': Color; 'marker.opacity': number | number[]; @@ -472,15 +472,15 @@ export interface ScatterData { mode: 'lines' | 'markers' | 'text' | 'lines+markers' | 'text+markers' | 'text+lines' | 'text+lines+markers' | 'none'; hoveron: 'points' | 'fills'; hoverinfo: 'all' | 'name' | 'none' | 'skip' | 'text' | - 'x' | 'x+text' | 'x+name' | - 'x+y' | 'x+y+text' | 'x+y+name' | - 'x+y+z' | 'x+y+z+text' | 'x+y+z+name' | - 'y+x' | 'y+x+text' | 'y+x+name' | - 'y+z' | 'y+z+text' | 'y+z+name' | - 'y+x+z' | 'y+x+z+text' | 'y+x+z+name' | - 'z+x' | 'z+x+text' | 'z+x+name' | - 'z+y+x' | 'z+y+x+text' | 'z+y+x+name' | - 'z+x+y' | 'z+x+y+text' | 'z+x+y+name'; + 'x' | 'x+text' | 'x+name' | + 'x+y' | 'x+y+text' | 'x+y+name' | + 'x+y+z' | 'x+y+z+text' | 'x+y+z+name' | + 'y+x' | 'y+x+text' | 'y+x+name' | + 'y+z' | 'y+z+text' | 'y+z+name' | + 'y+x+z' | 'y+x+z+text' | 'y+x+z+name' | + 'z+x' | 'z+x+text' | 'z+x+name' | + 'z+y+x' | 'z+y+x+text' | 'z+y+x+name' | + 'z+x+y' | 'z+x+y+text' | 'z+x+y+name'; hoverlabel: Partial
); +const globalCSS = css.global`body { margin: 0; }`; +const withGlobalCSS = ( +
+ +
+); + +const resolvedCSS = css.resolve`a { color: green; }`; +const withResolvedCSS = ( +
+ + {resolvedCSS.styles} +
+); + +const dynamicResolvedCSS = css.resolve`a { color: ${buttonColor}; }`; +const withDynamicResolvedCSS = ( +
+ + {dynamicResolvedCSS.styles} +
+); + const stylesChildren = flushToReact(); const jsxToRender = ( { stylesChildren } From 216e478ff5c4e0793eb1e1972dd03bcd1e07131a Mon Sep 17 00:00:00 2001 From: DimaMukhin Date: Fri, 24 Aug 2018 21:05:48 -0700 Subject: [PATCH 172/289] fixed failing tests --- types/koa2-session-redis/index.d.ts | 1 + types/koa2-session-redis/koa2-session-redis-tests.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts index 39707be4da..195dc30247 100644 --- a/types/koa2-session-redis/index.d.ts +++ b/types/koa2-session-redis/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/lonord/koa2-session-redis // Definitions by: Dima Mukhin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /*~ Note that ES6 modules cannot directly export class objects. *~ This file should be imported using the CommonJS-style: diff --git a/types/koa2-session-redis/koa2-session-redis-tests.ts b/types/koa2-session-redis/koa2-session-redis-tests.ts index 5a72ebcecd..7623b30aca 100644 --- a/types/koa2-session-redis/koa2-session-redis-tests.ts +++ b/types/koa2-session-redis/koa2-session-redis-tests.ts @@ -10,6 +10,6 @@ const CONFIG = { port: 6379, max_attempts: 0 }) -} +}; app.use(session(CONFIG, app)); From a5c4bc400099fa42056c2361b66eb6bfb5ee78d2 Mon Sep 17 00:00:00 2001 From: DimaMukhin Date: Fri, 24 Aug 2018 21:09:14 -0700 Subject: [PATCH 173/289] removed auto generated comments --- types/koa2-session-redis/index.d.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts index 195dc30247..24e85e1674 100644 --- a/types/koa2-session-redis/index.d.ts +++ b/types/koa2-session-redis/index.d.ts @@ -4,23 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/*~ Note that ES6 modules cannot directly export class objects. - *~ This file should be imported using the CommonJS-style: - *~ import x = require('someLibrary'); - *~ - *~ Refer to the documentation to understand common - *~ workarounds for this limitation of ES6 modules. - */ - import * as Redis from 'redis'; import * as session from 'koa-session'; -/*~ This declaration specifies that the class constructor function - *~ is the exported object from the file - */ export = RedisStore; -/*~ Write your module's methods and properties in this class */ declare class RedisStore implements session.stores { constructor(config?: Redis.ClientOpts); From 0c46e1fcac16a28014bb8f802eb539c442982a5d Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Sat, 25 Aug 2018 15:07:06 +0800 Subject: [PATCH 174/289] in weixin-app fix typo details => detail --- types/weixin-app/index.d.ts | 18 ++++++++++++------ types/weixin-app/weixin-app-tests.ts | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index a5e8abe504..b528bbeba1 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3147,20 +3147,26 @@ declare namespace wx { | "tap" | "longpress"; - interface BaseEvent { + interface BaseEvent { type: T; timeStamp: number; currentTarget: EventTarget; target: EventTarget; - details: Details; + detail: Detail; } + interface BuiltInEvent + extends BaseEvent {} + + interface CustomEvent + extends BaseEvent {} + /** * 指定focus时的光标位置 * @version 1.5.0 */ interface InputEvent - extends BaseEvent< + extends BuiltInEvent< "input", { value: string; @@ -3169,14 +3175,14 @@ declare namespace wx { > {} interface FormEvent - extends BaseEvent< + extends BuiltInEvent< "form", { value: { [name: string]: string | boolean | number }; } > {} - interface ScrollEvent extends BaseEvent<"scroll", {}> {} + interface ScrollEvent extends BuiltInEvent<"scroll", {}> {} interface Touch { identifier: number; @@ -3187,7 +3193,7 @@ declare namespace wx { } interface TouchEvent - extends BaseEvent< + extends BuiltInEvent< T, { x: number; diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index adbd641b3e..f36de3d178 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -1,5 +1,13 @@ getCurrentPages(); +interface MyOwnEvent + extends wx.CustomEvent< + "my-own", + { + hello: string; + } + > {} + let behavior = Behavior({ behaviors: [], properties: { @@ -143,17 +151,28 @@ Page({ customData: { hi: "MINA" }, + onMyOwnEvent(e: MyOwnEvent) { + e.detail.hello; + }, onTouchStart(e: wx.TouchStartEvent) { e.touches; + e.detail.x; + e.detail.y; }, onTouchEnd(e: wx.TouchEndEvent) { e.touches; + e.detail.x; + e.detail.y; }, onTouchCancel(e: wx.TouchCancelEvent) { e.touches; + e.detail.x; + e.detail.y; }, onTouchMove(e: wx.TouchMoveEvent) { e.touches; + e.detail.x; + e.detail.y; } }); From bc8c43e07d2d279129293bd011c7ec90a25e5bb3 Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Sat, 25 Aug 2018 15:37:59 +0800 Subject: [PATCH 175/289] update weixin-app to reflect data & props unification --- types/weixin-app/index.d.ts | 72 ++++++++++++++++++++-------- types/weixin-app/weixin-app-tests.ts | 19 +++++++- 2 files changed, 70 insertions(+), 21 deletions(-) diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index b528bbeba1..b86530c77c 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -2376,7 +2376,7 @@ declare namespace wx { * (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点 * @version 1.6.0 */ - in(component: Component): SelectorQuery; + in(component: Component): SelectorQuery; /** * 在当前页面下选择第一个匹配选择器selector的节点,返回一个NodesRef对象实例,可以用于获取节点信息。 * selector类似于CSS的选择器,但仅支持下列语法。 @@ -3313,37 +3313,54 @@ declare function App(app: T & ThisType): void; declare function getApp(): App; // #endregion // #region Compontent组件 + type DefaultData = object | ((this: V) => object); -type DefaultProps = Record; + +type DefaultProps = object | Record; + type ExtendedComponent< - Instance extends Component, + Instance extends Component, Data, Methods, Options, Props -> = CombinedInstance & Component; +> = CombinedInstance & + Component; + +// CombinedInstance models the `this`, i.e. instance type for (user defined) component type CombinedInstance< - Instance extends Component, + Instance extends Component, Data, Methods, Options, Props -> = Data & Methods & Options & Props & Instance; +> = Methods & Options & Instance; + type Prop = (() => T) | { new (...args: any[]): T & object }; + type PropValidator = PropOptions | Prop | Array>; + interface DefaultMethods { [key: string]: (this: V, ...args: any[]) => any; } + interface PropOptions { type?: Prop | Array>; value?: T | null | (() => object); - observer?(value: T, old: T): void; + // bug : 对于 type 为 Object 或 Array 的属性,如果通过该组件自身的 this.setData + // 来改变属性值的一个子字段,则依旧会触发属性 observer ,且 observer 接收到的 newVal 是变化的那个子字段的值, + // oldVal 为空, changedPath 包含子字段的字段名相关信息。 + observer?(value: T, old: T, changedPath: string): void; } + type RecordPropsDefinition = { [K in keyof T]: PropValidator }; + type ArrayPropsDefinition = Array; + type PropsDefinition = ArrayPropsDefinition | RecordPropsDefinition; + type ThisTypedComponentOptionsWithRecordProps< - V extends Component, + V extends Component, Data, Methods, Options, @@ -3374,7 +3391,7 @@ interface ComponentRelation { * Component组件参数 */ interface ComponentOptions< - Instance extends Component, + Instance extends Component, Data = DefaultData, Methods = DefaultMethods, Options = object, @@ -3404,7 +3421,7 @@ interface ComponentOptions< * 类似于mixins和traits的组件间代码复用机制 * 参见 [behaviors](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/behaviors.html) */ - behaviors?: Array<(ComponentOptions>) | string>; + behaviors?: Array<(ComponentOptions>) | string>; /** * 组件生命周期函数,在组件实例进入页面节点树时执行 * 注意此时不能调用 setData @@ -3439,7 +3456,7 @@ interface ComponentOptions< /** * Component实例方法 */ -interface Component { +interface Component { /** * 组件的文件路径 */ @@ -3455,7 +3472,12 @@ interface Component { /** * 组件数据,包括内部数据和属性值 */ - data: T; + data: D & P; + + /** + * 组件数据,包括内部数据和属性值(与 data 一致) + */ + properties: D & P; /** * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 @@ -3466,7 +3488,7 @@ interface Component { */ setData( data: { - [key in keyof T]?: + [key in keyof D]?: | string | number | boolean @@ -3503,19 +3525,25 @@ interface Component { * 使用选择器选择组件实例节点 * 返回匹配到的第一个组件实例对象 */ - selectComponent(selector: string): Component; + selectComponent(selector: string): Component; /** * selector 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 */ - selectAllComponents(selector: string): Array>; + selectAllComponents(selector: string): Array>; /** * 获取所有这个关系对应的所有关联节点,参见 [组件间关系](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/relations.html) */ getRelationNodes(relationKey: string): { [key: string]: ComponentRelation }; } declare function Component( - options?: ThisTypedComponentOptionsWithRecordProps, D, M, O, P> -): ExtendedComponent, D, M, O, P>; + options?: ThisTypedComponentOptionsWithRecordProps< + Component, + D, + M, + O, + P + > +): ExtendedComponent, D, M, O, P>; /** * behaviors 是用于组件间代码共享的特性 * 类似于一些编程语言中的“mixins”或“traits” @@ -3525,8 +3553,14 @@ declare function Component( * behavior 也可以引用其他 behavior */ declare function Behavior( - options?: ThisTypedComponentOptionsWithRecordProps, D, M, O, P> -): ExtendedComponent, D, M, O, P>; + options?: ThisTypedComponentOptionsWithRecordProps< + Component, + D, + M, + O, + P + > +): ExtendedComponent, D, M, O, P>; // #endregion // #region Page interface PageShareAppMessageOptions { diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index f36de3d178..74da0d6ae5 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -21,7 +21,7 @@ let behavior = Behavior({ attached() {}, methods: { myBehaviorMethod() { - this.myBehaviorData; + this.properties.myBehaviorData; } } }); @@ -34,7 +34,12 @@ Component({ // 属性名 type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) value: "", // 属性初始值(可选),如果未指定则会根据类型选择一个 - observer(newVal: string, oldVal: string) {} // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange' + observer(newVal: string, oldVal: string, changedPath: string) { + const anotherKey = newVal + changedPath; + this.setData({ + anotherKey + }); + } // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange' }, myProperty2: String // 简化的定义方式 }, @@ -50,6 +55,16 @@ Component({ moved() {}, detached() {}, methods: { + readMyDataAndMyProps() { + this.data.myProperty; + this.data.myProperty2; + this.data.key; + this.data.anotherKey; + this.properties.myProperty; + this.properties.myProperty2; + this.properties.key; + this.properties.anotherKey; + }, onMyButtonTap() { // 更新属性和数据的方法与更新页面数据的方法类似 this.setData({ From cdab315a76d2027a8f671ca65a70b2c4399da16c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Sat, 25 Aug 2018 10:01:14 +0200 Subject: [PATCH 176/289] [react-relay] Add generics to QueryRenderer to type variables and response. --- types/react-relay/index.d.ts | 28 ++++++++++++-------- types/react-relay/test/react-relay-tests.tsx | 21 +++++++++++---- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 2e41dcbd6a..69c417b7ec 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -7,7 +7,7 @@ // Cameron Knight // Kaare Hoff Skovgaard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 // Prettified with: // $ prettier --parser typescript --tab-width 4 --semi --trailing-comma es5 --write --print-width 120 \ @@ -88,24 +88,30 @@ export const graphql: GraphqlInterface; // ~~~~~~~~~~~~~~~~~~~~~ // ReactRelayQueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ -export interface QueryRendererProps { + +export type QueryRendererGenerics = { variables: object; response: object }; + +export interface QueryRendererProps { cacheConfig?: RelayRuntimeTypes.CacheConfig; environment: RelayRuntimeTypes.Environment; query?: RelayRuntimeTypes.GraphQLTaggedNode | null; - render(readyState: ReadyState): React.ReactElement | undefined | null; - variables: RelayRuntimeTypes.Variables; + render(readyState: ReadyState): React.ReactElement | undefined | null; + variables: T["variables"]; rerunParamExperimental?: RelayRuntimeTypes.RerunParam; } -export interface ReadyState { +export interface ReadyState { error: Error | undefined | null; - props: { [propName: string]: any } | undefined | null; + props: T | undefined | null; retry?(): void; } -export interface QueryRendererState { - readyState: ReadyState; -} -export class ReactRelayQueryRenderer extends React.Component {} -export class QueryRenderer extends ReactRelayQueryRenderer {} + +export class ReactRelayQueryRenderer extends React.Component> {} +export class QueryRenderer< + T extends QueryRendererGenerics = { + variables: RelayRuntimeTypes.Variables; + response: { [propName: string]: any }; + } +> extends ReactRelayQueryRenderer {} // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 9d08ed42d6..9f704bb042 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -1,3 +1,5 @@ +// tslint:disable:interface-over-type-literal + import * as React from "react"; import { Environment, Network, RecordSource, Store, ConnectionHandler, FragmentReference } from "relay-runtime"; @@ -28,8 +30,21 @@ const modernEnvironment = new Environment({ network, store }); // ~~~~~~~~~~~~~~~~~~~~~ // Modern QueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ + +// Artifact produced by relay-compiler-language-typescript +type MyQueryRendererVariables = { + pageID: string; +}; +type MyQueryRendererResponse = { + name: string; +}; +type MyQueryRenderer = { + variables: MyQueryRendererVariables; + response: MyQueryRendererResponse; +}; + const MyQueryRenderer = (props: { name: string; show: boolean }) => ( - environment={modernEnvironment} query={ props.show @@ -82,7 +97,6 @@ type StoryLike = (storyID: string) => void; // Artifact produced by relay-compiler-language-typescript declare const _Story_story$ref: unique symbol; type Story_story$ref = typeof _Story_story$ref; -// tslint:disable-next-line:interface-over-type-literal type Story_story = { readonly id: string; readonly text: string; @@ -173,7 +187,6 @@ declare const _FeedStories_feed$ref: unique symbol; type FeedStories_feed$ref = typeof _FeedStories_feed$ref; declare const _FeedStory_edges$ref: unique symbol; type FeedStory_edges$ref = typeof _FeedStory_edges$ref; -// tslint:disable-next-line:interface-over-type-literal type FeedStories_feed = { readonly edges: ReadonlyArray<{ readonly node: { @@ -184,7 +197,6 @@ type FeedStories_feed = { }>; readonly " $refType": FeedStories_feed$ref; }; -// tslint:disable-next-line:interface-over-type-literal type FeedStory_edges = ReadonlyArray<{ readonly publishedAt: string; readonly " $refType": FeedStory_edges$ref; @@ -255,7 +267,6 @@ const Feed = (() => { // Artifact produced by relay-compiler-language-typescript declare const _UserFeed_user$ref: unique symbol; type UserFeed_user$ref = typeof _UserFeed_user$ref; -// tslint:disable-next-line:interface-over-type-literal type UserFeed_user = { readonly feed: { readonly pageInfo: { From b53cc5d5cf90ffdcd4d84b1dd71b515af5f49e01 Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Sat, 25 Aug 2018 16:21:44 +0800 Subject: [PATCH 177/289] fix build --- types/weixin-app/index.d.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index b86530c77c..1e454c4ed9 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3366,13 +3366,7 @@ type ThisTypedComponentOptionsWithRecordProps< Options, Props > = object & - ComponentOptions< - V, - Data | ((this: Readonly & V) => Data), - Methods, - Options, - PropsDefinition - > & + ComponentOptions Data), Methods, Options, Props> & ThisType>>; interface ComponentRelation { From 822a20b79b09f869caa708a56741236efd6c1f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Monnot?= Date: Sat, 25 Aug 2018 15:06:21 +0200 Subject: [PATCH 178/289] Add some tests --- ...eact-vertical-timeline-component-tests.tsx | 29 +++++++++++++++++++ .../tsconfig.json | 10 +++++-- 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 types/react-vertical-timeline-component/react-vertical-timeline-component-tests.tsx diff --git a/types/react-vertical-timeline-component/react-vertical-timeline-component-tests.tsx b/types/react-vertical-timeline-component/react-vertical-timeline-component-tests.tsx new file mode 100644 index 0000000000..d09416010f --- /dev/null +++ b/types/react-vertical-timeline-component/react-vertical-timeline-component-tests.tsx @@ -0,0 +1,29 @@ +import * as React from "react"; +import { VerticalTimeline, VerticalTimelineElement } from "react-vertical-timeline-component"; + +export default class ReactVerticalTimelineComponentTests extends React.Component { + render() { + return ( + + console.info('icon has been clicked')} + className="vertical-timeline-element--work" + date="2012 - present" + > +

Creative Director

+

Miami, FL

+

+ Creative Direction, User Experience, Visual Design, Project Management, Team Leading +

+
+ +

Art Director

+

San Francisco, CA

+

+ Creative Direction, User Experience, Visual Design, SEO, Online Marketing +

+
+
+ ); + } +} diff --git a/types/react-vertical-timeline-component/tsconfig.json b/types/react-vertical-timeline-component/tsconfig.json index ca4a35b1cb..7c4c2106fb 100644 --- a/types/react-vertical-timeline-component/tsconfig.json +++ b/types/react-vertical-timeline-component/tsconfig.json @@ -5,8 +5,10 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], + "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -18,5 +20,9 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "react-vertical-timeline-component-tests.tsx" + ] } From bdce3cdaae21d93c78f10a416863e9330c7ad049 Mon Sep 17 00:00:00 2001 From: Pav Sidhu Date: Sat, 25 Aug 2018 14:28:53 +0100 Subject: [PATCH 179/289] Add contextMenuHidden to TextInput --- types/react-native/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 3d92f7ddd4..9ab61b6b7a 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1234,6 +1234,11 @@ export interface TextInputProps */ caretHidden?: boolean + /** + * If true, context menu is hidden. The default value is false. + */ + contextMenuHidden?: boolean + /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you don't want to deal with listening to events From 277080fb1c3bfb31a0f3498ea280fa7611112686 Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Sat, 25 Aug 2018 22:02:30 +0800 Subject: [PATCH 180/289] update component relationship api calls --- types/weixin-app/index.d.ts | 12 ++++++------ types/weixin-app/weixin-app-tests.ts | 3 +++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index a5e8abe504..6c8e44b484 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3352,17 +3352,17 @@ type ThisTypedComponentOptionsWithRecordProps< > & ThisType>>; -interface ComponentRelation { +interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ - type: string; + type: "parent" | "child" | "ancestor" | "descendant"; /** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */ target?: string; /** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */ - linked?: (...args: any[]) => void; + linked?: (target: Component) => void; /** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */ - linkChanged?: (...args: any[]) => void; + linkChanged?: (target: Component) => void; /** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */ - unlinked?: (...args: any[]) => void; + unlinked?: (target: Component) => void; } /** * Component组件参数 @@ -3505,7 +3505,7 @@ interface Component { /** * 获取所有这个关系对应的所有关联节点,参见 [组件间关系](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/relations.html) */ - getRelationNodes(relationKey: string): { [key: string]: ComponentRelation }; + getRelationNodes(relationKey: string): ComponentRelation[]; } declare function Component( options?: ThisTypedComponentOptionsWithRecordProps, D, M, O, P> diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index adbd641b3e..c805c2c5bf 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -65,12 +65,15 @@ Component({ type: "parent", // 关联的目标节点应为父节点 linked(target) { // 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后 + target.data; }, linkChanged(target) { // 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后 + target.data; }, unlinked(target) { // 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后 + target.data; } } } From 76f9bfce33ce017e2046f11552f6af27d4e24712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Sat, 25 Aug 2018 08:13:04 -0600 Subject: [PATCH 181/289] bugfix: improve Polyline and Polygon and add more tests --- types/leaflet/index.d.ts | 10 +++--- types/leaflet/leaflet-tests.ts | 61 +++++++++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 14 deletions(-) diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 89c9cbd9b9..0822dea605 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -612,10 +612,10 @@ export interface PolylineOptions extends PathOptions { } export class Polyline extends Path { - constructor(latlngs: LatLngExpression[], options?: PolylineOptions); + constructor(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions); toGeoJSON(): geojson.Feature; getLatLngs(): LatLng[] | LatLng[][] | LatLng[][][]; - setLatLngs(latlngs: LatLngExpression[]): this; + setLatLngs(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][]): this; isEmpty(): boolean; getCenter(): LatLng; getBounds(): LatLngBounds; @@ -625,13 +625,13 @@ export class Polyline extends Polyline { - constructor(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions); + constructor(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][], options?: PolylineOptions); } -export function polygon(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions): Polygon; +export function polygon(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][], options?: PolylineOptions): Polygon; export class Rectangle

extends Polygon

{ constructor(latLngBounds: LatLngBoundsExpression, options?: PolylineOptions); diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 1f6671cc8c..66f12fd0ed 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -473,15 +473,58 @@ L.marker([1, 2], { className: 'my-div-icon' })); -const latLngs = [ - {lat: 0, lng: 0}, - {lat: 1, lng: 1} -]; -const polygon = new L.Polygon(latLngs); -const polygonExclusion = new L.Polygon([latLngs, latLngs]); +let polygon: L.Polygon; -L.polygon(latLngs).addTo(map); -L.polygon([latLngs, latLngs]).addTo(map); +// simple polygon +const simplePolygonLatLngs: L.LatLngExpression[] = [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]]; +polygon = L.polygon(simplePolygonLatLngs); +polygon = new L.Polygon(simplePolygonLatLngs); +polygon.setLatLngs(simplePolygonLatLngs); +const simplePolygonLatLngs2: L.LatLng[] = polygon.getLatLngs() as L.LatLng[]; + +// complex polygon (polygon with holes) +const complexPolygonLatLngs: L.LatLngExpression[][] = [ + [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring + [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole +]; +polygon = L.polygon(complexPolygonLatLngs); +polygon = new L.Polygon(complexPolygonLatLngs); +polygon.setLatLngs(complexPolygonLatLngs); +const complexPolygonLatLngs2: L.LatLng[][] = polygon.getLatLngs() as L.LatLng[][]; + +// multi polygon +const multiPolygonLatLngs: L.LatLngExpression[][][] = [ + [ // first polygon + [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring + [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole + ], + [ // second polygon + [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] + ] +]; +polygon = L.polygon(multiPolygonLatLngs); +polygon = new L.Polygon(multiPolygonLatLngs); +polygon.setLatLngs(multiPolygonLatLngs); +const multiPolygonLatLngs2: L.LatLng[][][] = polygon.getLatLngs() as L.LatLng[][][]; + +let polyline: L.Polyline; + +// simple polyline +const simplePolylineLatLngs: L.LatLngExpression[] = [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]]; +polyline = L.polyline(simplePolylineLatLngs); +polyline = new L.Polyline(simplePolylineLatLngs); +polyline.setLatLngs(simplePolylineLatLngs); +const simplePolylineLatLngs2: L.LatLng[] = polyline.getLatLngs() as L.LatLng[]; + +// multi polyline +const multiPolylineLatLngs: L.LatLngExpression[][] = [ + [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], + [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] +]; +polyline = L.polyline(multiPolylineLatLngs); +polyline = new L.Polyline(multiPolylineLatLngs); +polyline.setLatLngs(multiPolylineLatLngs); +const multiPolylineLatLngs2: L.LatLng[][] = polyline.getLatLngs() as L.LatLng[][]; L.Util.extend({}); L.Util.create({}); @@ -512,7 +555,7 @@ interface MyProperties { testProperty: string; } -(L.polygon(latLngs) as L.Polygon).feature.properties.testProperty = "test"; +(L.polygon(simplePolygonLatLngs) as L.Polygon).feature.properties.testProperty = "test"; (L.marker([1, 2], { icon: L.icon({ From 20c03ac0dd8feae657862340c134c278dcbb0fc6 Mon Sep 17 00:00:00 2001 From: Pav Sidhu Date: Sat, 25 Aug 2018 15:25:06 +0100 Subject: [PATCH 182/289] Fix whitespace --- types/react-native/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 9ab61b6b7a..0c90a87cf6 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1238,7 +1238,7 @@ export interface TextInputProps * If true, context menu is hidden. The default value is false. */ contextMenuHidden?: boolean - + /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you don't want to deal with listening to events From f83044211c0f87d3b869b426137b06a5456cdbf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Sat, 25 Aug 2018 15:18:22 +0200 Subject: [PATCH 183/289] [react-relay] Add generics to commitMutation to type variables and response. --- types/react-relay/index.d.ts | 13 +++--- types/react-relay/test/react-relay-tests.tsx | 45 ++++++++++++++------ types/relay-runtime/index.d.ts | 37 +++++++++++----- 3 files changed, 64 insertions(+), 31 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 69c417b7ec..3db0b23dbc 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -89,9 +89,7 @@ export const graphql: GraphqlInterface; // ReactRelayQueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ -export type QueryRendererGenerics = { variables: object; response: object }; - -export interface QueryRendererProps { +export interface QueryRendererProps { cacheConfig?: RelayRuntimeTypes.CacheConfig; environment: RelayRuntimeTypes.Environment; query?: RelayRuntimeTypes.GraphQLTaggedNode | null; @@ -105,12 +103,11 @@ export interface ReadyState { retry?(): void; } -export class ReactRelayQueryRenderer extends React.Component> {} +export class ReactRelayQueryRenderer extends React.Component< + QueryRendererProps +> {} export class QueryRenderer< - T extends QueryRendererGenerics = { - variables: RelayRuntimeTypes.Variables; - response: { [propName: string]: any }; - } + T extends RelayRuntimeTypes.OperationBase = RelayRuntimeTypes.OperationDefaults > extends ReactRelayQueryRenderer {} // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 9f704bb042..f19d2a818c 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -383,7 +383,7 @@ export const mutation = graphql` export const optimisticResponse = { markReadNotification: { notification: { - seenState: "SEEN", + seenState: "SEEN" as "SEEN", }, }, }; @@ -419,26 +419,47 @@ export const configs = [ ]; function markNotificationAsRead(source: string, storyID: string) { - const variables = { - input: { - source, - storyID, - }, + // Artifact produced by relay-compiler-language-typescript + type MyMutationVariables = { + readonly input: { + readonly source: string; + readonly storyID: string; + }; + }; + type MyMutationResponse = { + readonly markReadNotification: { + readonly notification: { + readonly seenState: "SEEN" | "UNSEEN"; + }; + }; + }; + type MyMutation = { + readonly variables: MyMutationVariables; + readonly response: MyMutationResponse; }; - commitMutation(modernEnvironment, { + commitMutation(modernEnvironment, { configs, mutation, optimisticResponse, - variables, + variables: { + input: { + source, + storyID, + }, + }, onCompleted: (response, errors) => { - console.log("Response received from server."); + if (errors) { + console.log(`Errors received from server: ${errors.map(error => error.message).join(", ")}`); + } else { + console.log(`Response received from server: ${response.markReadNotification.notification.seenState}`); + } }, onError: err => console.error(err), updater: (store, data) => { - const field = store.get(storyID); - if (field) { - field.setValue(data.story, "story"); + const story = store.get(storyID); + if (story) { + story.setValue(data.markReadNotification.notification.seenState, "seenState"); } }, }); diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index acfec9eaa5..42cd633b57 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Martin // Eloy Durán // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.9 // Prettified with: // $ prettier --parser typescript --tab-width 4 --semi --trailing-comma es5 --write --print-width 120 \ @@ -51,6 +51,15 @@ export type RequestNode = ConcreteRequest | ConcreteBatchRequest; // tslint:disable-next-line:no-const-enum export const enum FragmentReference {} +export interface OperationBase { + variables: object; + response: object; +} +export interface OperationDefaults { + variables: Variables; + response: Variables; +} + // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ @@ -140,11 +149,11 @@ export type StoreUpdater = (store: RecordSourceProxy) => void; * order to easily access the root fields of a query/mutation as well as a * second argument of the response object of the mutation. */ -export type SelectorStoreUpdater = ( +export type SelectorStoreUpdater = ( store: RecordSourceSelectorProxy, // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is // inconvenient to access deeply in product code. - data: any // FLOW FIXME + data: T ) => void; /** @@ -483,7 +492,9 @@ export interface CUnstableEnvironmentCore, props: Props - ): { [key: string]: CSelector | Array> | null | undefined }; + ): { + [key: string]: CSelector | Array> | null | undefined; + }; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -1005,18 +1016,22 @@ export type commitLocalUpdate = (environment: Environment, updater: StoreUpdater // commitRelayModernMutation // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly -export interface MutationConfig { +export interface MutationConfig { configs?: RelayMutationConfig[]; mutation: GraphQLTaggedNode; - variables: Variables; + variables: T["variables"]; uploadables?: UploadableMap; - onCompleted?(response: T, errors: PayloadError[] | null | undefined): void; + onCompleted?(response: T["response"], errors: PayloadError[] | null | undefined): void; onError?(error?: Error): void; - optimisticUpdater?: SelectorStoreUpdater; - optimisticResponse?: object; - updater?: SelectorStoreUpdater; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: T["response"]; + updater?: SelectorStoreUpdater; } -export function commitRelayModernMutation(environment: Environment, config: MutationConfig): Disposable; +export function commitRelayModernMutation( + environment: Environment, + // tslint:disable-next-line:no-unnecessary-generics + config: MutationConfig +): Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // applyRelayModernOptimisticMutation From d33b4a2d939f27488dee73a27603238953753f34 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Sat, 25 Aug 2018 17:38:40 +0200 Subject: [PATCH 184/289] [@types/imagemin-gifsicle] Add type definitions --- .../imagemin-gifsicle-tests.ts | 9 ++++++++ types/imagemin-gifsicle/index.d.ts | 20 ++++++++++++++++ types/imagemin-gifsicle/tsconfig.json | 23 +++++++++++++++++++ types/imagemin-gifsicle/tslint.json | 1 + 4 files changed, 53 insertions(+) create mode 100644 types/imagemin-gifsicle/imagemin-gifsicle-tests.ts create mode 100644 types/imagemin-gifsicle/index.d.ts create mode 100644 types/imagemin-gifsicle/tsconfig.json create mode 100644 types/imagemin-gifsicle/tslint.json diff --git a/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts b/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts new file mode 100644 index 0000000000..b69d6b2541 --- /dev/null +++ b/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts @@ -0,0 +1,9 @@ +import imagemin = require('imagemin'); +import imageminGifsicle = require('imagemin-gifsicle'); + +imagemin(['*.png'], { + plugins: [ + imageminGifsicle(), + imageminGifsicle({ colors: 255 }) + ] +}); diff --git a/types/imagemin-gifsicle/index.d.ts b/types/imagemin-gifsicle/index.d.ts new file mode 100644 index 0000000000..f3132d5cfe --- /dev/null +++ b/types/imagemin-gifsicle/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for imagemin-gifsicle 5.2 +// Project: https://github.com/imagemin/imagemin-gifsicle#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Plugin } from 'imagemin'; + +declare function imageminGifsicle(options?: imageminGifsicle.Options): Plugin; + +declare namespace imageminGifsicle { + interface Options { + colors?: number; + interlaced?: boolean; + optimizationLevel?: number; + } +} + +export = imageminGifsicle; diff --git a/types/imagemin-gifsicle/tsconfig.json b/types/imagemin-gifsicle/tsconfig.json new file mode 100644 index 0000000000..8efb698e59 --- /dev/null +++ b/types/imagemin-gifsicle/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", + "imagemin-gifsicle-tests.ts" + ] +} diff --git a/types/imagemin-gifsicle/tslint.json b/types/imagemin-gifsicle/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/imagemin-gifsicle/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 391019b6ca770cdddcc35b0024a03dafbfbba5d3 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Sat, 25 Aug 2018 17:44:11 +0200 Subject: [PATCH 185/289] Remove useless reference to "node" types --- types/imagemin-gifsicle/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/imagemin-gifsicle/index.d.ts b/types/imagemin-gifsicle/index.d.ts index f3132d5cfe..80bc128286 100644 --- a/types/imagemin-gifsicle/index.d.ts +++ b/types/imagemin-gifsicle/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Romain Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import { Plugin } from 'imagemin'; declare function imageminGifsicle(options?: imageminGifsicle.Options): Plugin; From f2a7f1dab3ab9fb45a4e06c807b6387a46381900 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Sat, 25 Aug 2018 17:45:42 +0200 Subject: [PATCH 186/289] [@types/imagemin-jpegtran] Add type definitions --- .../imagemin-jpegtran-tests.ts | 9 ++++++++ types/imagemin-jpegtran/index.d.ts | 17 ++++++++++++++ types/imagemin-jpegtran/tsconfig.json | 23 +++++++++++++++++++ types/imagemin-jpegtran/tslint.json | 1 + 4 files changed, 50 insertions(+) create mode 100644 types/imagemin-jpegtran/imagemin-jpegtran-tests.ts create mode 100644 types/imagemin-jpegtran/index.d.ts create mode 100644 types/imagemin-jpegtran/tsconfig.json create mode 100644 types/imagemin-jpegtran/tslint.json diff --git a/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts b/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts new file mode 100644 index 0000000000..2259abeede --- /dev/null +++ b/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts @@ -0,0 +1,9 @@ +import imagemin = require('imagemin'); +import imageminJpegtran = require('imagemin-jpegtran'); + +imagemin(['*.png'], { + plugins: [ + imageminJpegtran(), + imageminJpegtran({ progressive: true }) + ] +}); diff --git a/types/imagemin-jpegtran/index.d.ts b/types/imagemin-jpegtran/index.d.ts new file mode 100644 index 0000000000..2ec98c3c17 --- /dev/null +++ b/types/imagemin-jpegtran/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for imagemin-jpegtran 5.0 +// Project: https://github.com/imagemin/imagemin-jpegtran#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'imagemin'; + +declare function imageminJpegtran(options?: imageminJpegtran.Options): Plugin; + +declare namespace imageminJpegtran { + interface Options { + arithmetic?: boolean; + progressive?: boolean; + } +} + +export = imageminJpegtran; diff --git a/types/imagemin-jpegtran/tsconfig.json b/types/imagemin-jpegtran/tsconfig.json new file mode 100644 index 0000000000..e26dc49c0e --- /dev/null +++ b/types/imagemin-jpegtran/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", + "imagemin-jpegtran-tests.ts" + ] +} diff --git a/types/imagemin-jpegtran/tslint.json b/types/imagemin-jpegtran/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/imagemin-jpegtran/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 619e32e0b1b114bd92da80be4178fb760ba8fb47 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Sat, 25 Aug 2018 17:48:41 +0200 Subject: [PATCH 187/289] Fix test incoherence --- types/imagemin-gifsicle/imagemin-gifsicle-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts b/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts index b69d6b2541..0156322cd7 100644 --- a/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts +++ b/types/imagemin-gifsicle/imagemin-gifsicle-tests.ts @@ -1,7 +1,7 @@ import imagemin = require('imagemin'); import imageminGifsicle = require('imagemin-gifsicle'); -imagemin(['*.png'], { +imagemin(['*.gif'], { plugins: [ imageminGifsicle(), imageminGifsicle({ colors: 255 }) From 61c413402d2b430b27dc8159e468d3542085704e Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Sat, 25 Aug 2018 17:48:55 +0200 Subject: [PATCH 188/289] Fix test incoherence --- types/imagemin-jpegtran/imagemin-jpegtran-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts b/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts index 2259abeede..82a8ea927f 100644 --- a/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts +++ b/types/imagemin-jpegtran/imagemin-jpegtran-tests.ts @@ -1,7 +1,7 @@ import imagemin = require('imagemin'); import imageminJpegtran = require('imagemin-jpegtran'); -imagemin(['*.png'], { +imagemin(['*.jpg'], { plugins: [ imageminJpegtran(), imageminJpegtran({ progressive: true }) From 3f625cb3f2fd4549c6e0756f58796c5d122d3a20 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Sat, 25 Aug 2018 17:52:57 +0200 Subject: [PATCH 189/289] [@types/imagemin-optipng] Add type definitions --- .../imagemin-optipng-tests.ts | 9 ++++++++ types/imagemin-optipng/index.d.ts | 19 +++++++++++++++ types/imagemin-optipng/tsconfig.json | 23 +++++++++++++++++++ types/imagemin-optipng/tslint.json | 1 + 4 files changed, 52 insertions(+) create mode 100644 types/imagemin-optipng/imagemin-optipng-tests.ts create mode 100644 types/imagemin-optipng/index.d.ts create mode 100644 types/imagemin-optipng/tsconfig.json create mode 100644 types/imagemin-optipng/tslint.json diff --git a/types/imagemin-optipng/imagemin-optipng-tests.ts b/types/imagemin-optipng/imagemin-optipng-tests.ts new file mode 100644 index 0000000000..ce0eb272ee --- /dev/null +++ b/types/imagemin-optipng/imagemin-optipng-tests.ts @@ -0,0 +1,9 @@ +import imagemin = require('imagemin'); +import imageminOptipng = require('imagemin-optipng'); + +imagemin(['*.png'], { + plugins: [ + imageminOptipng(), + imageminOptipng({ optimizationLevel: 2 }) + ] +}); diff --git a/types/imagemin-optipng/index.d.ts b/types/imagemin-optipng/index.d.ts new file mode 100644 index 0000000000..9ab9506205 --- /dev/null +++ b/types/imagemin-optipng/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for imagemin-optipng 5.2 +// Project: https://github.com/imagemin/imagemin-optipng#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'imagemin'; + +declare function imageminOptipng(options?: imageminOptipng.Options): Plugin; + +declare namespace imageminOptipng { + interface Options { + bitDepthReduction?: boolean; + colorTypeReduction?: boolean; + optimizationLevel?: number; + paletteReduction?: boolean; + } +} + +export = imageminOptipng; diff --git a/types/imagemin-optipng/tsconfig.json b/types/imagemin-optipng/tsconfig.json new file mode 100644 index 0000000000..586e747281 --- /dev/null +++ b/types/imagemin-optipng/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", + "imagemin-optipng-tests.ts" + ] +} diff --git a/types/imagemin-optipng/tslint.json b/types/imagemin-optipng/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/imagemin-optipng/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 06e5b267f34c0b9d4372266465dd7798e134f0c7 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Sat, 25 Aug 2018 17:57:21 +0200 Subject: [PATCH 190/289] [@types/imagemin-svgo] Add type definitions --- types/imagemin-svgo/imagemin-svgo-tests.ts | 9 +++++++++ types/imagemin-svgo/index.d.ts | 16 +++++++++++++++ types/imagemin-svgo/tsconfig.json | 23 ++++++++++++++++++++++ types/imagemin-svgo/tslint.json | 1 + 4 files changed, 49 insertions(+) create mode 100644 types/imagemin-svgo/imagemin-svgo-tests.ts create mode 100644 types/imagemin-svgo/index.d.ts create mode 100644 types/imagemin-svgo/tsconfig.json create mode 100644 types/imagemin-svgo/tslint.json diff --git a/types/imagemin-svgo/imagemin-svgo-tests.ts b/types/imagemin-svgo/imagemin-svgo-tests.ts new file mode 100644 index 0000000000..23895afcd6 --- /dev/null +++ b/types/imagemin-svgo/imagemin-svgo-tests.ts @@ -0,0 +1,9 @@ +import imagemin = require('imagemin'); +import imageminSvgo = require('imagemin-svgo'); + +imagemin(['*.svg'], { + plugins: [ + imageminSvgo(), + imageminSvgo({ floatPrecision: 2 }) + ] +}); diff --git a/types/imagemin-svgo/index.d.ts b/types/imagemin-svgo/index.d.ts new file mode 100644 index 0000000000..24d3b73ca9 --- /dev/null +++ b/types/imagemin-svgo/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for imagemin-svgo 7.0 +// Project: https://github.com/imagemin/imagemin-svgo#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { Plugin } from 'imagemin'; +import { Options as SvgoOptions } from 'svgo'; + +declare function imageminSvgo(options?: imageminSvgo.Options): Plugin; + +declare namespace imageminSvgo { + type Options = SvgoOptions; +} + +export = imageminSvgo; diff --git a/types/imagemin-svgo/tsconfig.json b/types/imagemin-svgo/tsconfig.json new file mode 100644 index 0000000000..6b4f221e13 --- /dev/null +++ b/types/imagemin-svgo/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", + "imagemin-svgo-tests.ts" + ] +} diff --git a/types/imagemin-svgo/tslint.json b/types/imagemin-svgo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/imagemin-svgo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ccdb2edb025570433b20f2ea814aba4b3f784264 Mon Sep 17 00:00:00 2001 From: Benjamin Lannon Date: Sat, 25 Aug 2018 15:22:30 -0400 Subject: [PATCH 191/289] Adding Type definitions for Teddy --- types/teddy/index.d.ts | 57 ++++++++++++++++++++++++++++++++++++++ types/teddy/teddy-tests.ts | 30 ++++++++++++++++++++ types/teddy/tsconfig.json | 16 +++++++++++ types/teddy/tslint.json | 1 + 4 files changed, 104 insertions(+) create mode 100644 types/teddy/index.d.ts create mode 100644 types/teddy/teddy-tests.ts create mode 100644 types/teddy/tsconfig.json create mode 100644 types/teddy/tslint.json diff --git a/types/teddy/index.d.ts b/types/teddy/index.d.ts new file mode 100644 index 0000000000..5699a25e49 --- /dev/null +++ b/types/teddy/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for teddy 0.4 +// Project: https://github.com/rooseveltframework/teddy +// Definitions by: Benjamin Lannon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// compiles a template +export function compile(template: string): string; + +// parses a template +export function render(template: string, model: object): string; + +// mutator method to set template root param; must be a string +export function setTemplateRoot(path: string): void; + +// mutator method to set verbosity param. takes human-readable string argument and converts it to an integer for more efficient checks against the setting +export function setVerbosity(n: number | string): void; + +// turn on or off the setting to cache template renders +export function cacheRenders(b: boolean): void; + +// mutator method to set default caches param: the number of cached versions of each templates to store by default if cacheRenders is enabled +export function setDefaultCaches(n: number): void; + +// mutator method to set max caches for a given registered template +export function setMaxCaches(template: string, n: number): void; + +// mutator method to set a whitelist of templates to cache, e.g. { "myTemplate.html": maxCaches} where maxCaches is an integer +export function setCacheWhitelist(o: object): void; + +// mutator method to set a blacklist of templates not to cache as an array +export function setCacheBlacklist(templateArray: ReadonlyArray): void; + +// sets all params to their default values +export function setDefaultParams(): void; + +// invalidates cache of a given template and model combination +// if no model is supplied, deletes all caches of the given template +export function flushCache(template: string, model?: object): void; + +// mutator method to set max passes param: the number of times the parser can iterate over the template +export function setMaxPasses(n: number): void; + +// turn on or off the setting to compile templates at every render +export function compileAtEveryRender(b: boolean): void; + +// turn on or off the setting to minify templates using teddy's internal minifier +export function minify(b: boolean): void; + +// default values for parameters sent to teddy +export let params: object; + +// compiled templates are stored as object collections, e.g. { "myTemplate.html": "

some markup

"} +export let templates: object; + +// cache of fully rendered temmplates, e.g. { "myTemplate.html": "

some markup

"} +export let renderedTemplates: object; diff --git a/types/teddy/teddy-tests.ts b/types/teddy/teddy-tests.ts new file mode 100644 index 0000000000..899b7d94f9 --- /dev/null +++ b/types/teddy/teddy-tests.ts @@ -0,0 +1,30 @@ +import * as teddy from "teddy"; + +teddy.compile("template.html"); + +const markup = teddy.render("template.html", {}); + +teddy.setTemplateRoot("~/"); + +teddy.setVerbosity(3); + +teddy.cacheRenders(true); + +teddy.setDefaultCaches(2); + +teddy.setMaxCaches("template.html", 2); + +teddy.setCacheWhitelist({ "template.html": 5 }); + +teddy.setCacheBlacklist(["template1.html", "template2.html"]); + +teddy.setDefaultParams(); + +teddy.flushCache("template.html"); +teddy.flushCache("template.html", {}); + +teddy.setMaxPasses(500); + +teddy.compileAtEveryRender(true); + +teddy.minify(false); diff --git a/types/teddy/tsconfig.json b/types/teddy/tsconfig.json new file mode 100644 index 0000000000..3e60a19082 --- /dev/null +++ b/types/teddy/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "teddy-tests.ts"] +} diff --git a/types/teddy/tslint.json b/types/teddy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/teddy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 98fd1ebaaf39aba0ea7740515f62f369b8153222 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danilo=20B=C3=BCrger?= Date: Sat, 25 Aug 2018 21:50:28 +0200 Subject: [PATCH 192/289] [react-native] FormData is a class See https://github.com/facebook/react-native/blob/master/Libraries/Network/FormData.js#L49 --- types/react-native/globals.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native/globals.d.ts b/types/react-native/globals.d.ts index 2110ab7278..f5dcb25382 100644 --- a/types/react-native/globals.d.ts +++ b/types/react-native/globals.d.ts @@ -33,7 +33,7 @@ declare function fetch(input: RequestInfo, init?: RequestInit): Promise Date: Sat, 25 Aug 2018 22:24:18 +0200 Subject: [PATCH 193/289] jsdoc: sinon matchers and sandbox --- types/sinon/index.d.ts | 179 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index 5a3f98070b..ea655c610a 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -1180,7 +1180,17 @@ declare namespace Sinon { } interface SinonMatcher { + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ and(expr: SinonMatcher): SinonMatcher; + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ or(expr: SinonMatcher): SinonMatcher; test(val: any): boolean; } @@ -1235,19 +1245,62 @@ declare namespace Sinon { } interface SinonMatch { + /** + * Requires the value to be == to the given number. + */ (value: number): SinonMatcher; + /** + * Requires the value to be a string and have the expectation as a substring. + */ (value: string): SinonMatcher; + /** + * Requires the value to be a string and match the given regular expression. + */ (expr: RegExp): SinonMatcher; + /** + * See custom matchers. + */ (callback: (value: any) => boolean, message?: string): SinonMatcher; + /** + * Requires the value to be not null or undefined and have at least the same properties as expectation. + * This supports nested matchers. + */ (obj: object): SinonMatcher; + /** + * Matches anything. + */ any: SinonMatcher; + /** + * Requires the value to be defined. + */ defined: SinonMatcher; + /** + * Requires the value to be truthy. + */ truthy: SinonMatcher; + /** + * Requires the value to be falsy. + */ falsy: SinonMatcher; + /** + * Requires the value to be a Boolean + */ bool: SinonMatcher; + /** + * Requires the value to be a Number. + */ number: SinonMatcher; + /** + * Requires the value to be a String. + */ string: SinonMatcher; + /** + * Requires the value to be an Object. + */ object: SinonMatcher; + /** + * Requires the value to be a Function. + */ func: SinonMatcher; /** * Requires the value to be a Map. @@ -1261,23 +1314,84 @@ declare namespace Sinon { * Requires the value to be an Array. */ array: SinonArrayMatcher; + /** + * Requires the value to be a regular expression. + */ regexp: SinonMatcher; + /** + * Requires the value to be a Date object. + */ date: SinonMatcher; + /** + * Requires the value to be a Symbol. + */ symbol: SinonMatcher; + /** + * Requires the value to strictly equal ref. + */ same(obj: any): SinonMatcher; + /** + * Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp", "date" or "symbol". + */ typeOf(type: string): SinonMatcher; + /** + * Requires the value to be an instance of the given type. + */ instanceOf(type: any): SinonMatcher; + /** + * Requires the value to define the given property. + * The property might be inherited via the prototype chain. + * If the optional expectation is given, the value of the property is deeply compared with the expectation. + * The expectation can be another matcher. + * @param property + * @param expect + */ has(property: string, expect?: any): SinonMatcher; + /** + * Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored. + * @param property + * @param expect + */ hasOwn(property: string, expect?: any): SinonMatcher; + /** + * Requires the value to define the given propertyPath. Dot (prop.prop) and bracket (prop[0]) notations are supported as in Lodash.get. + * The propertyPath might be inherited via the prototype chain. + * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. + * The expectation can be another matcher. + */ hasNested(path: string, expect?: any): SinonMatcher; + /** + * Requires every element of an Array, Set or Map, or alternatively every value of an Object to match the given matcher. + */ every(matcher: SinonMatcher): SinonMatcher; + /** + * Requires any element of an Array, Set or Map, or alternatively any value of an Object to match the given matcher. + */ some(matcher: SinonMatcher): SinonMatcher; } interface SinonSandboxConfig { + /** + * The sandbox’s methods can be injected into another object for convenience. + * The injectInto configuration option can name an object to add properties to. + */ injectInto: object | null; + /** + * What properties to inject. + * Note that simply naming “server” here is not sufficient to have a server property show up in the target object, + * you also have to set useFakeServer to true. + */ properties: string[]; + /** + * If set to true, the sandbox will have a clock property. + * You can optionally pass in a configuration object that follows the specification for fake timers, such as { toFake: ["setTimeout", "setInterval"] }. + */ useFakeTimers: boolean | Partial; + /** + * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server. + * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler, + * you might want to do: + */ useFakeServer: boolean | SinonFakeServer; } @@ -1347,12 +1461,25 @@ declare namespace Sinon { } interface SinonSandbox { + /** + * A convenience reference for sinon.assert + * Since sinon@2.0.0 + */ assert: SinonAssert; clock: SinonFakeTimers; requests: SinonFakeXMLHttpRequest[]; server: SinonFakeServer; + /** + * Works exactly like sinon.spy + */ spy: SinonSpyStatic; + /** + * Works exactly like sinon.stub. + */ stub: SinonStubStatic; + /** + * Works exactly like sinon.mock + */ mock: SinonMockStatic; /** @@ -1378,23 +1505,71 @@ declare namespace Sinon { * The native XMLHttpRequest object will be available at sinon.xhr.XMLHttpRequest */ useFakeXMLHttpRequest(): SinonFakeXMLHttpRequestStatic; + /** + * Fakes XHR and binds a server object to the sandbox such that it too is restored when calling sandbox.restore(). + * Access requests through sandbox.requests and server through sandbox.server + */ useFakeServer(): SinonFakeServer; + /** + * Restores all fakes created through sandbox. + */ restore(): void; + /** + * Resets the internal state of all fakes created through sandbox. + */ reset(): void; + /** + * Resets the history of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ resetHistory(): void; + /** + * Resets the behaviour of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ resetBehavior(): void; + /** + * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Returns the stub to allow chaining. + * Since sinon@2.0.0 + */ usingPromise(promiseLibrary: any): SinonSandbox; + /** + * Verifies all mocks created through the sandbox. + */ verify(): void; + /** + * Verifies all mocks and restores all fakes created through the sandbox. + */ verifyAndRestore(): void; + /** + * Replaces property on object with replacement argument. Attempts to replace an already replaced value cause an exception. + * replacement can be any value, including spies, stubs and fakes. + * This method only works on non-accessor properties, for replacing accessors, use sandbox.replaceGetter() and sandbox.replaceSetter(). + */ replace( obj: T, prop: TKey, replacement: T[TKey]): T[TKey]; + /** + * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ replaceGetter( obj: T, prop: TKey, replacement: () => T[TKey]): () => T[TKey]; + /** + * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ replaceSetter( obj: T, prop: TKey, @@ -1426,6 +1601,10 @@ declare namespace Sinon { fakeServer: SinonFakeServerStatic; fakeServerWithClock: SinonFakeServerStatic; + /** + * Creates a new sandbox object with spies, stubs, and mocks. + * @param config + */ createSandbox(config?: Partial): SinonSandbox; defaultConfig: Partial; } From f8edcaeac62359af7901b7e3fa615040e08656dc Mon Sep 17 00:00:00 2001 From: MrLuje Date: Sat, 25 Aug 2018 22:47:01 +0200 Subject: [PATCH 194/289] jsdoc: sinon lint --- types/sinon/index.d.ts | 284 +++++++++++++++++++++-------------------- 1 file changed, 148 insertions(+), 136 deletions(-) diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index ea655c610a..3f15beba8e 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -25,16 +25,16 @@ declare namespace Sinon { // Methods /** - * Returns true if the spy was called at least once with @param obj as this. + * Returns true if the spy was called at least once with @param obj as this. * calledOn also accepts a matcher spyCall.calledOn(sinon.match(fn)) (see matchers). - * @param obj + * @param obj */ calledOn(obj: any): boolean; /** * Returns true if spy was called at least once with the provided arguments. - * Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, + * Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, * so a call that received the provided arguments (in the same spots) and possibly others as well will return true. - * @param args + * @param args */ calledWith(...args: any[]): boolean; /** @@ -43,37 +43,37 @@ declare namespace Sinon { calledWithExactly(...args: any[]): boolean; /** * Returns true if spy/stub was called the new operator. - * Beware that this is inferred based on the value of the this object and the spy function’s prototype, + * Beware that this is inferred based on the value of the this object and the spy function’s prototype, * so it may give false positives if you actively return the right kind of object. */ calledWithNew(): boolean; /** * Returns true if spy was called at exactly once with the provided arguments. - * @param args + * @param args */ calledOnceWith(...args: any[]): boolean; calledOnceWithExactly(...args: any[]): boolean; /** * Returns true if spy was called with matching arguments (and possibly others). * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). - * @param args + * @param args */ calledWithMatch(...args: any[]): boolean; /** * Returns true if call did not receive provided arguments. - * @param args + * @param args */ notCalledWith(...args: any[]): boolean; /** - * Returns true if call did not receive matching arguments. + * Returns true if call did not receive matching arguments. * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). - * @param args + * @param args */ notCalledWithMatch(...args: any[]): boolean; /** * Returns true if spy returned the provided value at least once. * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers). - * @param value + * @param value */ returned(value: any): boolean; /** @@ -91,7 +91,7 @@ declare namespace Sinon { /** * Like yield, but with an explicit argument number specifying which callback to call. * Useful if a function is called with more than one callback, and simply calling the first callback is not desired. - * @param pos + * @param pos */ callArg(pos: number): void; callArgOn(pos: number, obj: any, ...args: any[]): void; @@ -141,12 +141,12 @@ declare namespace Sinon { /** * Returns true if the spy call occurred before another spy call. - * @param call + * @param call */ calledBefore(call: SinonSpyCall): boolean; /** * Returns true if the spy call occurred after another spy call. - * @param call + * @param call */ calledAfter(call: SinonSpyCall): boolean; } @@ -216,32 +216,33 @@ declare namespace Sinon { (...args: any[]): any; /** * Returns true if the spy was called before @param anotherSpy - * @param anotherSpy + * @param anotherSpy */ calledBefore(anotherSpy: SinonSpy): boolean; /** * Returns true if the spy was called after @param anotherSpy - * @param anotherSpy + * @param anotherSpy */ calledAfter(anotherSpy: SinonSpy): boolean; /** * Returns true if spy was called before @param anotherSpy, and no spy calls occurred between spy and @param anotherSpy. - * @param anotherSpy + * @param anotherSpy */ calledImmediatelyBefore(anotherSpy: SinonSpy): boolean; /** * Returns true if spy was called after @param anotherSpy, and no spy calls occurred between @param anotherSpy and spy. - * @param anotherSpy + * @param anotherSpy */ calledImmediatelyAfter(anotherSpy: SinonSpy): boolean; /** - * Creates a spy that only records calls when the received arguments match those passed to withArgs. This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * Creates a spy that only records calls when the received arguments match those passed to withArgs. + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. * @param args Expected args */ withArgs(...args: any[]): SinonSpy; /** * Returns true if the spy was always called with @param obj as this. - * @param obj + * @param obj */ alwaysCalledOn(obj: any): boolean; /** @@ -250,24 +251,24 @@ declare namespace Sinon { alwaysCalledWith(...args: any[]): boolean; /** * Returns true if spy was always called with the exact provided arguments. - * @param args + * @param args */ alwaysCalledWithExactly(...args: any[]): boolean; /** * Returns true if spy was always called with matching arguments (and possibly others). * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). - * @param args + * @param args */ alwaysCalledWithMatch(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with the provided arguments. - * @param args + * @param args */ neverCalledWith(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with matching arguments. * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). - * @param args + * @param args */ neverCalledWithMatch(...args: any[]): boolean; /** @@ -284,7 +285,7 @@ declare namespace Sinon { alwaysThrew(obj: any): boolean; /** * Returns true if spy always returned the provided value. - * @param obj + * @param obj */ alwaysReturned(obj: any): boolean; /** @@ -296,7 +297,7 @@ declare namespace Sinon { /** * Returns the nth call. * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. - * @param n + * @param n */ getCall(n: number): SinonSpyCall; /** @@ -316,8 +317,8 @@ declare namespace Sinon { * * %n - the formatted value of the nth argument passed to printf * * %* - a comma-delimited list of the (non-format string) arguments passed to printf * * %D - a multi-line list of the arguments received by all calls to the spy - * @param format - * @param args + * @param format + * @param args */ printf(format: string, ...args: any[]): string; /** @@ -336,10 +337,10 @@ declare namespace Sinon { */ (func: Function): SinonSpy; /** - * Creates a spy for object.method and replaces the original method with the spy. - * An exception is thrown if the property is not already a function. - * The spy acts exactly like the original method in all cases. - * The original method can be restored by calling object.method.restore(). + * Creates a spy for object.method and replaces the original method with the spy. + * An exception is thrown if the property is not already a function. + * The spy acts exactly like the original method in all cases. + * The original method can be restored by calling object.method.restore(). * The returned spy is the function object which replaced the original method. spy === object.method. */ (obj: T, method: keyof T): SinonSpy; @@ -360,22 +361,22 @@ declare namespace Sinon { */ reset(): void; /** - * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. * Returns the stub to allow chaining. */ usingPromise(promiseLibrary: any): SinonStub; /** * Makes the stub return the provided @param obj value. - * @param obj + * @param obj */ returns(obj: any): SinonStub; /** * Causes the stub to return the argument at the provided @param index. * stub.returnsArg(0); causes the stub to return the first argument. - * If the argument at the provided index is not available, prior to sinon@6.1.2, an undefined value will be returned; + * If the argument at the provided index is not available, prior to sinon@6.1.2, an undefined value will be returned; * starting from sinon@6.1.2, a TypeError will be thrown. - * @param index + * @param index */ returnsArg(index: number): SinonStub; /** @@ -385,13 +386,15 @@ declare namespace Sinon { returnsThis(): SinonStub; /** * Causes the stub to return a Promise which resolves to the provided value. - * When constructing the Promise, sinon uses the Promise.resolve method. You are responsible for providing a polyfill in environments which do not provide Promise. The Promise library can be overwritten using the usingPromise method. + * When constructing the Promise, sinon uses the Promise.resolve method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ resolves(value?: any): SinonStub; /** * Causes the stub to throw an exception (Error). - * @param type + * @param type */ throws(type?: string): SinonStub; /** @@ -403,14 +406,16 @@ declare namespace Sinon { * stub.throwsArg(0); causes the stub to throw the first argument as the exception. * If the argument at the provided index is not available, a TypeError will be thrown. * Since sinon@2.3.0 - * @param index + * @param index */ throwsArg(index: number): SinonStub; throwsException(type?: string): SinonStub; throwsException(obj: any): SinonStub; /** * Causes the stub to return a Promise which rejects with an exception (Error). - * When constructing the Promise, sinon uses the Promise.reject method. You are responsible for providing a polyfill in environments which do not provide Promise. The Promise library can be overwritten using the usingPromise method. + * When constructing the Promise, sinon uses the Promise.reject method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ rejects(): SinonStub; @@ -436,36 +441,36 @@ declare namespace Sinon { callThrough(): SinonStub; /** * Like stub.callsArg(index); but with an additional parameter to pass the this context. - * @param index - * @param context + * @param index + * @param context */ callsArgOn(index: number, context: any): SinonStub; /** * Like callsArg, but with arguments to pass to the callback. - * @param index - * @param args + * @param index + * @param args */ callsArgWith(index: number, ...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. - * @param index - * @param context - * @param args + * @param index + * @param context + * @param args */ callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param index + * @param index */ callsArgAsync(index: number): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param index - * @param context + * @param index + * @param context */ callsArgOnAsync(index: number, context: any): SinonStub; /** @@ -482,7 +487,7 @@ declare namespace Sinon { callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; /** * Makes the stub call the provided @param func when invoked. - * @param func + * @param func */ callsFake(func: (...args: any[]) => any): SinonStub; /** @@ -491,14 +496,14 @@ declare namespace Sinon { get(func: () => any): SinonStub; /** * Defines a new setter for this stub. - * @param func + * @param func */ set(func: (v: any) => void): SinonStub; /** * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions. * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally. * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs. - * @param n + * @param n */ onCall(n: number): SinonStub; /** @@ -515,7 +520,7 @@ declare namespace Sinon { onThirdCall(): SinonStub; /** * Defines a new value for this stub. - * @param val + * @param val */ value(val: any): SinonStub; /** @@ -532,8 +537,8 @@ declare namespace Sinon { /** * Causes the spy to invoke a callback passed as a property of an object to the spy. * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. - * @param property - * @param args + * @param property + * @param args */ yieldsTo(property: string, ...args: any[]): SinonStub; /** @@ -544,38 +549,39 @@ declare namespace Sinon { * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param args + * @param args */ yieldsAsync(...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param context - * @param args + * @param context + * @param args */ yieldsOnAsync(context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param property - * @param args + * @param property + * @param args */ yieldsToAsync(property: string, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). - * @param property - * @param context - * @param args + * @param property + * @param context + * @param args */ yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; /** * Stubs the method only for the provided arguments. - * This is useful to be more expressive in your assertions, where you can access the spy with the same call. It is also useful to create a stub that can act differently in response to different arguments. - * @param args + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * It is also useful to create a stub that can act differently in response to different arguments. + * @param args */ withArgs(...args: any[]): SinonStub; } @@ -593,7 +599,7 @@ declare namespace Sinon { */ (obj: T): SinonStubbedInstance; /** - * Replaces obj.method with a stub function. + * Replaces obj.method with a stub function. * An exception is thrown if the property is not already a function. * The original function can be restored by calling object.method.restore(); (or stub.restore();). */ @@ -607,7 +613,7 @@ declare namespace Sinon { atLeast(n: number): SinonExpectation; /** * Specify the maximum amount of calls expected. - * @param n + * @param n */ atMost(n: number): SinonExpectation; /** @@ -632,18 +638,18 @@ declare namespace Sinon { exactly(n: number): SinonExpectation; /** * Expect the method to be called with the provided arguments and possibly others. - * An expectation instance only holds onto a single set of arguments specified with withArgs. - * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * An expectation instance only holds onto a single set of arguments specified with withArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), * so it is generally not intended that this method be invoked more than once per test case. - * @param args + * @param args */ withArgs(...args: any[]): SinonExpectation; /** * Expect the method to be called with the provided arguments and no others. - * An expectation instance only holds onto a single set of arguments specified with withExactArgs. - * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * An expectation instance only holds onto a single set of arguments specified with withExactArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), * so it is generally not intended that this method be invoked more than once per test case. - * @param args + * @param args */ withExactArgs(...args: any[]): SinonExpectation; on(obj: any): SinonExpectation; @@ -663,7 +669,7 @@ declare namespace Sinon { /** * Creates an expectation without a mock object, basically an anonymous mock function. * Method name is optional and is used in exception messages to make them more readable. - * @param methodName + * @param methodName */ create(methodName?: string): SinonExpectation; } @@ -711,11 +717,11 @@ declare namespace Sinon { /** * Tick the clock ahead time milliseconds. - * Causes all timers scheduled within the affected time range to be called. - * time may be the number of milliseconds to advance the clock by or a human-readable string. + * Causes all timers scheduled within the affected time range to be called. + * time may be the number of milliseconds to advance the clock by or a human-readable string. * Valid string formats are “08” for eight seconds, “01:00” for one minute and “02:34:10” for two hours, 34 minutes and ten seconds. * time may be negative, which causes the clock to change but won’t fire any callbacks. - * @param ms + * @param ms */ tick(ms: number | string): void; /** @@ -828,7 +834,7 @@ declare namespace Sinon { responseXML: Document; /** * The value of the given response header, if the request has been responded to (see respond). - * @param header + * @param header */ getResponseHeader(header: string): string; /** @@ -839,7 +845,7 @@ declare namespace Sinon { // Methods /** * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. - * @param headers + * @param headers */ setResponseHeaders(headers: any): void; /** @@ -868,16 +874,16 @@ declare namespace Sinon { useFilters: boolean; /** * Add a filter that will decide whether or not to fake a request. - * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). + * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). * If the filter returns true, the request will not be faked. - * @param filter + * @param filter */ addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; /** - * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() + * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). - * @param xhr + * @param xhr */ onCreate(xhr: SinonFakeXMLHttpRequest): void; /** @@ -890,14 +896,14 @@ declare namespace Sinon { // Properties /** * Used internally to determine the HTTP method used with the provided request. - * By default this method simply returns request.method. + * By default this method simply returns request.method. * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. * This method can be overridden to provide custom behavior. - * @param request + * @param request */ getHTTPMethod(request: SinonFakeXMLHttpRequest): string; /** - * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. + * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. */ requests: SinonFakeXMLHttpRequest[]; @@ -1010,7 +1016,7 @@ declare namespace Sinon { /** * If set, the server will respond to every request immediately and synchronously. * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. - * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. + * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. */ respondImmediately: boolean; @@ -1034,7 +1040,7 @@ declare namespace Sinon { /** * Every assertion fails by calling this method. * By default it throws an error of type sinon.assert.failException. - * If the test framework looks for assertion errors by checking for a specific exception, you can simply override the kind of exception thrown. + * If the test framework looks for assertion errors by checking for a specific exception, you can simply override the kind of exception thrown. * If that does not fit with your testing framework of choice, override the fail method to do the right thing. */ fail(message?: string): void; // Overridable @@ -1047,7 +1053,7 @@ declare namespace Sinon { // Methods /** * Passes if spy was never called - * @param spy + * @param spy */ notCalled(spy: SinonSpy): void; /** @@ -1072,7 +1078,7 @@ declare namespace Sinon { callCount(spy: SinonSpy, count: number): void; /** * Passes if provided spies were called in the specified order. - * @param spies + * @param spies */ callOrder(...spies: SinonSpy[]): void; /** @@ -1087,27 +1093,27 @@ declare namespace Sinon { /** * Passes if spy was called with the provided arguments. * It’s possible to assert on a dedicated spy call: sinon.assert.calledWith(spy.firstCall, arg1, arg2, ...);. - * @param spyOrSpyCall - * @param args + * @param spyOrSpyCall + * @param args */ calledWith(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** * Passes if spy was always called with the provided arguments. - * @param spy - * @param args + * @param spy + * @param args */ alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; /** * Passes if spy was never called with the provided arguments. - * @param spy - * @param args + * @param spy + * @param args */ neverCalledWith(spy: SinonSpy, ...args: any[]): void; /** * Passes if spy was called with the provided arguments and no others. * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithExactly(spy.getCall(1), arg1, arg2, ...);. - * @param spyOrSpyCall - * @param args + * @param spyOrSpyCall + * @param args */ calledWithExactly(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** @@ -1128,14 +1134,14 @@ declare namespace Sinon { /** * Passes if spy was never called with matching arguments. * This behaves the same way as sinon.assert.neverCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). - * @param spy - * @param args + * @param spy + * @param args */ neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; /** * Passes if spy was called with the new operator. * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithNew(spy.secondCall, arg1, arg2, ...);. - * @param spyOrSpyCall + * @param spyOrSpyCall */ calledWithNew(spyOrSpyCall: SinonSpy | SinonSpyCall): void; /** @@ -1171,7 +1177,8 @@ declare namespace Sinon { */ match(actual: any, expected: any): void; /** - * Exposes assertions into another object, to better integrate with the test framework. For instance, JsTestDriver uses global assertions, and to make Sinon.JS assertions appear alongside them, you can do. + * Exposes assertions into another object, to better integrate with the test framework. + * For instance, JsTestDriver uses global assertions, and to make Sinon.JS assertions appear alongside them, you can do. * @example sinon.assert.expose(this); * This will give you assertCalled(spy),assertCallOrder(spy1, spy2, ...) and so on. * The method accepts an optional options object with two options. @@ -1181,15 +1188,17 @@ declare namespace Sinon { interface SinonMatcher { /** - * All matchers implement and and or. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); - var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); */ and(expr: SinonMatcher): SinonMatcher; /** - * All matchers implement and and or. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); - var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); */ or(expr: SinonMatcher): SinonMatcher; test(val: any): boolean; @@ -1340,23 +1349,23 @@ declare namespace Sinon { instanceOf(type: any): SinonMatcher; /** * Requires the value to define the given property. - * The property might be inherited via the prototype chain. - * If the optional expectation is given, the value of the property is deeply compared with the expectation. + * The property might be inherited via the prototype chain. + * If the optional expectation is given, the value of the property is deeply compared with the expectation. * The expectation can be another matcher. - * @param property - * @param expect + * @param property + * @param expect */ has(property: string, expect?: any): SinonMatcher; /** * Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored. - * @param property - * @param expect + * @param property + * @param expect */ hasOwn(property: string, expect?: any): SinonMatcher; /** * Requires the value to define the given propertyPath. Dot (prop.prop) and bracket (prop[0]) notations are supported as in Lodash.get. - * The propertyPath might be inherited via the prototype chain. - * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. + * The propertyPath might be inherited via the prototype chain. + * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. * The expectation can be another matcher. */ hasNested(path: string, expect?: any): SinonMatcher; @@ -1372,24 +1381,24 @@ declare namespace Sinon { interface SinonSandboxConfig { /** - * The sandbox’s methods can be injected into another object for convenience. + * The sandbox’s methods can be injected into another object for convenience. * The injectInto configuration option can name an object to add properties to. */ injectInto: object | null; /** - * What properties to inject. - * Note that simply naming “server” here is not sufficient to have a server property show up in the target object, + * What properties to inject. + * Note that simply naming “server” here is not sufficient to have a server property show up in the target object, * you also have to set useFakeServer to true. */ properties: string[]; /** - * If set to true, the sandbox will have a clock property. + * If set to true, the sandbox will have a clock property. * You can optionally pass in a configuration object that follows the specification for fake timers, such as { toFake: ["setTimeout", "setInterval"] }. */ useFakeTimers: boolean | Partial; /** - * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server. - * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler, + * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server. + * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler, * you might want to do: */ useFakeServer: boolean | SinonFakeServer; @@ -1441,12 +1450,13 @@ declare namespace Sinon { throws(val: Error | string): SinonSpy; /** * Creates a fake that returns a resolved Promise for the passed value. - * @param val Resolved promise + * @param val Resolved promise */ resolves(val: any): SinonSpy; /** * Creates a fake that returns a rejected Promise for the passed value. - * If an Error is passed as the value argument, then that will be the value of the promise. If any other value is passed, then that will be used for the message property of the Error returned by the promise. + * If an Error is passed as the value argument, then that will be the value of the promise. + * If any other value is passed, then that will be used for the message property of the Error returned by the promise. * @param val Rejected promise */ rejects(val: any): SinonSpy; @@ -1483,7 +1493,7 @@ declare namespace Sinon { mock: SinonMockStatic; /** - * * No param : Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, process.hrtime, performance.now(when available) + * * No param : Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, process.hrtime, performance.now(when available) * and Date with a custom implementation which is bound to the returned clock object. * Starts the clock at the UNIX epoch (timestamp of 0). * * Now : As above, but rather than starting the clock with a timestamp of 0, start at the provided timestamp now. @@ -1491,16 +1501,18 @@ declare namespace Sinon { * You can also pass in a Date object, and its getTime() will be used for the starting timestamp. * * Config : As above, but allows further configuration options, some of which are: * * config.now - Number/Date - installs lolex with the specified unix epoch (default: 0) - * * config.toFake - String[ ] - an array with explicit function names to fake. By default lolex will automatically fake all methods except process.nextTick. You could, however, still fake nextTick by providing it explicitly + * * config.toFake - String[ ] - an array with explicit function names to fake. + * By default lolex will automatically fake all methods except process.nextTick. You could, however, still fake nextTick by providing it explicitly * * config.shouldAdvanceTime - Boolean - tells lolex to increment mocked time automatically based on the real system time shift (default: false) * * Please visit the lolex.install documentation for the full feature set. - * * Important note: when faking nextTick, normal calls to process.nextTick() would not execute automatically as they would during normal event-loop phases. You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. - * @param config + * * Important note: when faking nextTick, normal calls to process.nextTick() would not execute automatically as they would during normal event-loop phases. + * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. + * @param config */ useFakeTimers(config?: number | Date | Partial): SinonFakeTimers; /** * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests. - * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. + * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. * Other progIds, such as XMLDOM are left untouched. * The native XMLHttpRequest object will be available at sinon.xhr.XMLHttpRequest */ @@ -1529,7 +1541,7 @@ declare namespace Sinon { */ resetBehavior(): void; /** - * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. * Returns the stub to allow chaining. * Since sinon@2.0.0 */ @@ -1555,9 +1567,9 @@ declare namespace Sinon { /** * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. - * @param obj - * @param prop - * @param replacement + * @param obj + * @param prop + * @param replacement */ replaceGetter( obj: T, @@ -1566,9 +1578,9 @@ declare namespace Sinon { /** * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. - * @param obj - * @param prop - * @param replacement + * @param obj + * @param prop + * @param replacement */ replaceSetter( obj: T, @@ -1603,7 +1615,7 @@ declare namespace Sinon { /** * Creates a new sandbox object with spies, stubs, and mocks. - * @param config + * @param config */ createSandbox(config?: Partial): SinonSandbox; defaultConfig: Partial; From cfaac3f02c8571cb4c8ee372ddf2e2efce1dc664 Mon Sep 17 00:00:00 2001 From: Romain Faust Date: Sun, 26 Aug 2018 01:52:13 +0200 Subject: [PATCH 195/289] [@types/gulp-imagemin] Update type definitions --- types/gulp-imagemin/gulp-imagemin-tests.ts | 34 ++++++++++------------ types/gulp-imagemin/index.d.ts | 21 ++++++++----- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts index 7fc1d86311..926d6b6dfb 100644 --- a/types/gulp-imagemin/gulp-imagemin-tests.ts +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -1,20 +1,18 @@ -import * as GulpImagemin from 'gulp-imagemin'; +import gulp = require('gulp'); +import gulpImagemin = require('gulp-imagemin'); -GulpImagemin(); +const plugins = [ + gulpImagemin.gifsicle({ interlaced: true }), + gulpImagemin.jpegtran({ progressive: true }), + gulpImagemin.optipng({ optimizationLevel: 5 }), + gulpImagemin.svgo({ floatPrecision: 2 }) +]; -GulpImagemin([ - GulpImagemin.gifsicle({ interlaced: true }), - GulpImagemin.jpegtran({ progressive: true }), - GulpImagemin.optipng({ optimizationLevel: 5 }), - GulpImagemin.svgo({ - plugins: [{ removeViewBox: true }, { cleanupIDs: false }] - }) -]); - -GulpImagemin({ verbose: true }); - -GulpImagemin([ - GulpImagemin.svgo({ - plugins: [{ removeViewBox: true }] - }) -], { verbose: true }); +gulp.task('minify:img', () => { + return gulp.src('img/**/*') + .pipe(gulpImagemin()) + .pipe(gulpImagemin(plugins)) + .pipe(gulpImagemin({ verbose: true })) + .pipe(gulpImagemin(plugins, { verbose: true })) + .pipe(gulp.dest('dist')); +}); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts index 42c1ef8d5c..ac61547a74 100644 --- a/types/gulp-imagemin/index.d.ts +++ b/types/gulp-imagemin/index.d.ts @@ -2,26 +2,31 @@ // Project: https://github.com/sindresorhus/gulp-imagemin#readme // Definitions by: Romain Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// +import { Plugin } from 'imagemin'; +import { Options as GifsicleOptions } from 'imagemin-gifsicle'; +import { Options as JpegtranOptions } from 'imagemin-jpegtran'; +import { Options as OptipngOptions } from 'imagemin-optipng'; +import { Options as SvgoOptions } from 'imagemin-svgo'; import { Transform } from 'stream'; -declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; -declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; +declare function imagemin(pluginsOrOptions?: ReadonlyArray | imagemin.Options): Transform; +declare function imagemin(plugins?: ReadonlyArray, options?: imagemin.Options): Transform; declare namespace imagemin { interface Options { verbose?: boolean; } - type Plugin = (input: any) => Promise; - type PluginFactory = (options?: any) => Plugin; + type PluginFactory = (options?: T) => Plugin; - const gifsicle: PluginFactory; - const jpegtran: PluginFactory; - const optipng: PluginFactory; - const svgo: PluginFactory; + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; } export = imagemin; From 12b8027ec5c3993b109db81f083a80e412f41504 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Sun, 26 Aug 2018 01:57:09 +0200 Subject: [PATCH 196/289] Fix test incoherence --- types/gulp-imagemin/gulp-imagemin-tests.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts index 926d6b6dfb..839e126fe2 100644 --- a/types/gulp-imagemin/gulp-imagemin-tests.ts +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -8,11 +8,26 @@ const plugins = [ gulpImagemin.svgo({ floatPrecision: 2 }) ]; -gulp.task('minify:img', () => { - return gulp.src('img/**/*') +gulp.task('build', () => { + return gulp.src('*.{gif,jpg,png,svg}') .pipe(gulpImagemin()) + .pipe(gulp.dest('dist')); +}); + +gulp.task('build', () => { + return gulp.src('*.{gif,jpg,png,svg}') .pipe(gulpImagemin(plugins)) + .pipe(gulp.dest('dist')); +}); + +gulp.task('build', () => { + return gulp.src('*.{gif,jpg,png,svg}') .pipe(gulpImagemin({ verbose: true })) + .pipe(gulp.dest('dist')); +}); + +gulp.task('build', () => { + return gulp.src('*.{gif,jpg,png,svg}') .pipe(gulpImagemin(plugins, { verbose: true })) .pipe(gulp.dest('dist')); }); From f137b3e122354a6e651a65fa2325570a276bc4a9 Mon Sep 17 00:00:00 2001 From: Drew Dowling Date: Sat, 25 Aug 2018 17:28:06 -0700 Subject: [PATCH 197/289] react-bootstrap: Allow interval prop to be null The react-bootstrap docs state that the interval prop on a Carousel can be null. In this state, a Carousel will not automatically cycle through its items. Tested locally. https://react-bootstrap.github.io/components/carousel/#carousels-props-carousel --- types/react-bootstrap/lib/Carousel.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-bootstrap/lib/Carousel.d.ts b/types/react-bootstrap/lib/Carousel.d.ts index 23ceeda466..17de20bac8 100644 --- a/types/react-bootstrap/lib/Carousel.d.ts +++ b/types/react-bootstrap/lib/Carousel.d.ts @@ -12,7 +12,7 @@ declare namespace Carousel { defaultActiveIndex?: number; direction?: string; indicators?: boolean; - interval?: number; + interval?: number | null; nextIcon?: React.ReactNode; onSelect?: SelectCallback; // TODO: Add more specific type From 7dd487303b4c6474b8ef60b97382171e6d3b410c Mon Sep 17 00:00:00 2001 From: Allen Gammel Date: Sat, 25 Aug 2018 19:30:03 -0500 Subject: [PATCH 198/289] removed comments per reviewer feedback. --- types/expired-storage/expired-storage-tests.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/types/expired-storage/expired-storage-tests.ts b/types/expired-storage/expired-storage-tests.ts index fa2dd29ef7..5c1a814b23 100644 --- a/types/expired-storage/expired-storage-tests.ts +++ b/types/expired-storage/expired-storage-tests.ts @@ -1,8 +1,5 @@ -// import { LocalStorage } from 'node-localstorage'; // Removed since this pkg isn't getting installed. import ExpiredStorage = require('expired-storage'); -// const localStorage = new LocalStorage('./scratch', Infinity); -// const expiredStorage = new ExpiredStorage(localStorage); // ExpiredStorage requires a LocalStorage provider const expiredStorage = new ExpiredStorage(); const mjkModel = { From e6568c65f5703695f6acf5197a8054b826884051 Mon Sep 17 00:00:00 2001 From: Mariusz Pawelski Date: Sun, 26 Aug 2018 08:21:16 +0200 Subject: [PATCH 199/289] Basic support for typed "this" in Widget Factory (#28395) --- types/jqueryui/index.d.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index a979c65c7a..7dca429ce4 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -1071,6 +1071,17 @@ declare namespace JQueryUI { show?: any; } + interface WidgetCommonProperties { + element: JQuery; + defaultElement : string; + document: Document; + namespace: string; + uuid: string; + widgetEventPrefix: string; + widgetFullName: string; + window: Window; + } + interface Widget { (methodName: string): JQuery; (options: WidgetOptions): JQuery; @@ -1079,8 +1090,8 @@ declare namespace JQueryUI { (optionLiteral: string, options: WidgetOptions): any; (optionLiteral: string, optionName: string, optionValue: any): JQuery; - (name: string, prototype: any): JQuery; - (name: string, base: Function, prototype: any): JQuery; + (name: string, prototype: T & ThisType): JQuery; + (name: string, base: Function, prototype: T & ThisType ): JQuery; } //////////////////////////////////////////////////////////////////////////////////////////////////// From 45baf1fcd503d68fe45f76f8d62c68e03da83003 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Sat, 25 Aug 2018 13:30:06 -0700 Subject: [PATCH 200/289] adds typings for the 'toposort' package --- types/toposort/index.d.ts | 6 ++++++ types/toposort/toposort-tests.ts | 19 +++++++++++++++++++ types/toposort/tsconfig.json | 23 +++++++++++++++++++++++ types/toposort/tslint.json | 3 +++ 4 files changed, 51 insertions(+) create mode 100644 types/toposort/index.d.ts create mode 100644 types/toposort/toposort-tests.ts create mode 100644 types/toposort/tsconfig.json create mode 100644 types/toposort/tslint.json diff --git a/types/toposort/index.d.ts b/types/toposort/index.d.ts new file mode 100644 index 0000000000..8da78b7d11 --- /dev/null +++ b/types/toposort/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for toposort 2.0 +// Project: https://github.com/marcelklehr/toposort +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function toposort(graph: ReadonlyArray<[string, string]>): ReadonlyArray; diff --git a/types/toposort/toposort-tests.ts b/types/toposort/toposort-tests.ts new file mode 100644 index 0000000000..201277fefa --- /dev/null +++ b/types/toposort/toposort-tests.ts @@ -0,0 +1,19 @@ +import toposort from 'toposort'; + +const testGraph: ReadonlyArray<[string, string]> = [ + [ + 'string1', + 'string2', + ], + [ + 'string2', + 'string3', + ], + [ + 'string3', + 'string1', + ], +]; + +// $ExpectType ReadonlyArray +toposort(testGraph); diff --git a/types/toposort/tsconfig.json b/types/toposort/tsconfig.json new file mode 100644 index 0000000000..3524da0d19 --- /dev/null +++ b/types/toposort/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "toposort-tests.ts" + ] +} diff --git a/types/toposort/tslint.json b/types/toposort/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/toposort/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From a40d251db47b57e88844019070a6d5804425df3b Mon Sep 17 00:00:00 2001 From: Sander Bouwhuis Date: Sun, 26 Aug 2018 10:40:44 +0200 Subject: [PATCH 201/289] Support named queries in elasticsearch response --- types/elasticsearch/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index c791db72c3..a9dc133545 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -645,6 +645,7 @@ export interface SearchResponse { fields?: any; highlight?: any; inner_hits?: any; + matched_queries?: string[]; sort?: string[]; }>; }; From a806b2eca60c7466e3aa899cbb6106df2ca978d9 Mon Sep 17 00:00:00 2001 From: Sander Bouwhuis Date: Sun, 26 Aug 2018 10:57:21 +0200 Subject: [PATCH 202/289] Add test for accessing property --- types/elasticsearch/elasticsearch-tests.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index 85574e3c91..c28db244f8 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -37,6 +37,14 @@ client.search({ }, (error) => { }); +client.search({ + q: 'pants' +}).then((body) => { + const hit = body.hits.hits[0]; + const names = hit && hit.matched_queries; +}, (error) => { +}); + client.indices.delete({ index: 'test_index', ignore: [404] From 55b80854086ef6a8ba14f22179de52f172dcd69a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Sun, 26 Aug 2018 12:26:47 +0200 Subject: [PATCH 203/289] [react-relay] Make QueryRenderer typings backwards compatible. --- types/react-relay/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 3db0b23dbc..acce5bf832 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -89,7 +89,7 @@ export const graphql: GraphqlInterface; // ReactRelayQueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ -export interface QueryRendererProps { +export interface QueryRendererProps { cacheConfig?: RelayRuntimeTypes.CacheConfig; environment: RelayRuntimeTypes.Environment; query?: RelayRuntimeTypes.GraphQLTaggedNode | null; @@ -97,7 +97,7 @@ export interface QueryRendererProps { variables: T["variables"]; rerunParamExperimental?: RelayRuntimeTypes.RerunParam; } -export interface ReadyState { +export interface ReadyState { error: Error | undefined | null; props: T | undefined | null; retry?(): void; From 15f698578b30af4557eecfdda1dee72bd1e12fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danilo=20B=C3=BCrger?= Date: Sat, 25 Aug 2018 21:45:24 +0200 Subject: [PATCH 204/289] [react-native] SectionList is a VirtualizedList See https://github.com/facebook/react-native/blob/master/Libraries/Lists/SectionList.js#L187 ``` export type Props = RequiredProps & OptionalProps & VirtualizedSectionListProps; ``` See https://github.com/facebook/react-native/blob/master/Libraries/Lists/VirtualizedSectionList.js#L119 ``` export type Props = RequiredProps & OptionalProps & VirtualizedListProps; ``` See https://github.com/facebook/react-native/blob/master/Libraries/Lists/VirtualizedList.js#L54 ``` // TODO: Conflicts with the optional `renderItem` in // `VirtualizedSectionList`'s props. renderItem: $FlowFixMe, ``` --- types/react-native/index.d.ts | 10 ++++++---- types/react-native/test/index.tsx | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 3d92f7ddd4..13880f61a5 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -4042,7 +4042,7 @@ export interface SectionListRenderItemInfo extends ListRenderItemInfo = (info: SectionListRenderItemInfo) => React.ReactElement | null; -export interface SectionListProps extends ScrollViewProps { +export interface SectionListProps extends VirtualizedListWithoutRenderItemProps { /** * Rendered in between adjacent Items within each section. */ @@ -4201,7 +4201,11 @@ export interface SectionListStatic extends React.ComponentClass extends ScrollViewProps { + export interface VirtualizedListProps extends VirtualizedListWithoutRenderItemProps { + renderItem: ListRenderItem; + } + + export interface VirtualizedListWithoutRenderItemProps extends ScrollViewProps { /** * Rendered when the list is empty. Can be a React Component Class, a render function, or * a rendered element. @@ -4345,8 +4349,6 @@ export interface VirtualizedListProps extends ScrollViewProps { */ removeClippedSubviews?: boolean; - renderItem: ListRenderItem; - /** * Render a custom scroll component, e.g. with a differently styled `RefreshControl`. */ diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index a9e3944a9b..c4d7d493e3 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -360,6 +360,7 @@ export class SectionListTest extends React.Component, { {`${info.section.title} - ${info.item}`} )} + maxToRenderPerBatch={5} /> ); From 9111cc41165c694dd65d4188721c37932e5a49bd Mon Sep 17 00:00:00 2001 From: Luca Lindhorst Date: Sun, 26 Aug 2018 16:17:59 +0200 Subject: [PATCH 205/289] Added definitions for wink-tokenizer --- types/wink-tokenizer/index.d.ts | 135 +++++++++++++++++++ types/wink-tokenizer/tsconfig.json | 23 ++++ types/wink-tokenizer/tslint.json | 1 + types/wink-tokenizer/wink-tokenizer-tests.ts | 11 ++ 4 files changed, 170 insertions(+) create mode 100644 types/wink-tokenizer/index.d.ts create mode 100644 types/wink-tokenizer/tsconfig.json create mode 100644 types/wink-tokenizer/tslint.json create mode 100644 types/wink-tokenizer/wink-tokenizer-tests.ts diff --git a/types/wink-tokenizer/index.d.ts b/types/wink-tokenizer/index.d.ts new file mode 100644 index 0000000000..11b9236cdc --- /dev/null +++ b/types/wink-tokenizer/index.d.ts @@ -0,0 +1,135 @@ +// Type definitions for wink-tokenizer 4.0 +// Project: http://winkjs.org/ +// Definitions by: Luca Lindhorst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Tokenizer { + /** + * create a tokenizer instance + */ + constructor(); + + /** + * Tokenize a string + * @param sentence to be tokenized + * @returns tokens + */ + tokenize(sentence: string): Tokenizer.Token[]; + + /** + * Defines the configuration in terms of the types of token that will be extracted by tokenize() method. + * Note by default, all types of tokens will be detected and tagged automatically. + * @param config configuration object + * @returns number of true parameters + */ + defineConfig(config: Tokenizer.Config): number; + + /** + * Returns the finger print of the tokens generated by the last call to tokenize(). + * A finger print is a string created by sequentially joining the unique code of each token's type. + * + * currency: 'r', email: 'e', emoji: 'j', emoticon: 'c', + * hashtag: 'h', number: 'n', ordinal: 'o', + * punctuation: token becomes fingerprint, + * quoted_phrase: 'q', symbol: token becomes fingerprint, + * time: 't', mention: 'm', url: 'u', word: 'w', + * @return string of token types + */ + getTokensFP(): string; +} + +declare namespace Tokenizer { + type Tag = "word" | "email" | "emoji" | "punctuation" + | "number" | "time" | "hashtag" | "mention" | "emoticon" | "ordinal" + | "quoted_phrase" | "url" | "symbol" | "currency" | "alien"; + + interface Token { + value: string; + tag: Tag; + } + + /** + * It defines 0 or more properties from the list of 14 properties. + * A true value for a property ensures tokenization for that type of text; + * whereas false value will mean that the tokenization of that type of text will not be attempted. + * + * An empty config object is equivalent to splitting on spaces. + * Whatever tokens are created like this are tagged as alien + * and z is the finger print code of this token type. + */ + interface Config { + /** + * such as $ or £ symbols + * @default true + */ + currency?: boolean; + + /** + * @default true + */ + email?: boolean; + + /** + * @default true + */ + emoji?: boolean; + + /** + * @default true + */ + emoticon?: boolean; + + /** + * @default true + */ + hashtag?: boolean; + + /** + * @default true + */ + number?: boolean; + + /** + * ordinals like 1st , 2nd , 3rd , 4th or 12th or 91st + * @default true + */ + ordinal?: boolean; + + /** + * @default true + */ + punctuation?: boolean; + + /** + * @default true + */ + quoted_phrase?: boolean; + + /** + * @default true + */ + symbol?: boolean; + + /** + * @default true + */ + time?: boolean; + + /** + * @default true + */ + mention?: boolean; + + /** + * @default true + */ + url?: boolean; + + /** + * @default true + */ + word?: boolean; + } +} + +export = Tokenizer; diff --git a/types/wink-tokenizer/tsconfig.json b/types/wink-tokenizer/tsconfig.json new file mode 100644 index 0000000000..5ec43876c0 --- /dev/null +++ b/types/wink-tokenizer/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "wink-tokenizer-tests.ts" + ] +} diff --git a/types/wink-tokenizer/tslint.json b/types/wink-tokenizer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wink-tokenizer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wink-tokenizer/wink-tokenizer-tests.ts b/types/wink-tokenizer/wink-tokenizer-tests.ts new file mode 100644 index 0000000000..755127370e --- /dev/null +++ b/types/wink-tokenizer/wink-tokenizer-tests.ts @@ -0,0 +1,11 @@ +import * as Tokenizer from "wink-tokenizer"; + +const tokenizer = new Tokenizer(); + +tokenizer.defineConfig({ + currency: false +}); + +tokenizer.tokenize("asd asd asd ads"); + +tokenizer.getTokensFP(); From 3cf39396301026e5e063080cc36253052db914c5 Mon Sep 17 00:00:00 2001 From: d-ph Date: Sun, 26 Aug 2018 15:20:29 +0100 Subject: [PATCH 206/289] [bluebird-global] Miscellaneous improvements 1. Bring copy&pasted code from std lib back to sync. 2. Come up with a plan to remove the copy&paste from std lib 3. Add an information that due to how these typings work, users can't cast instances of global Promise to Bluebird promise. Also, mention a walk-around if that's needed. --- .../bluebird-global/bluebird-global-tests.ts | 8 ++ types/bluebird-global/index.d.ts | 75 ++++++++++++++----- 2 files changed, 64 insertions(+), 19 deletions(-) diff --git a/types/bluebird-global/bluebird-global-tests.ts b/types/bluebird-global/bluebird-global-tests.ts index b6bbb915e2..3928ba46c9 100644 --- a/types/bluebird-global/bluebird-global-tests.ts +++ b/types/bluebird-global/bluebird-global-tests.ts @@ -44,3 +44,11 @@ function testPromiseRejection() { function testGithubTicket28081Regression() { Promise.resolve([3]).map((n: number) => true); } + +import Bluebird = require("bluebird"); + +function testTheWalkaroundForCastingGlobalPromiseToBluebirdPromise() { + const bluebirdString: Bluebird = Bluebird.resolve( + new Promise(() => 'Lorem ipsum') + ); +} diff --git a/types/bluebird-global/index.d.ts b/types/bluebird-global/index.d.ts index 7f38f981f1..fca3c1235e 100644 --- a/types/bluebird-global/index.d.ts +++ b/types/bluebird-global/index.d.ts @@ -10,6 +10,25 @@ * If you want to leverage the fact, that bluebird polyfills the global Promise in the browser, then * you need to tell TypeScript about this. The following declaration file does exactly that. * + * 1.1. Why you might not want to use `bluebird-global` instead of `bluebird`. + * + * Because of how these typings tell TypeScript about bluebird's Promise methods, it is not + * possible to cast global Promises to Bluebird promises in your code. In other words, you won't + * be able to do the following (even though it's possible at the runtime): + * + * let bluebirdPromise: Bluebird = new Promise(() => { return 'Lorem ipsum'; }); + * + * If you need to, you can walk-around this by constructing a new Bluebird promise over an instance + * of the global Promise, like so: + * + * let bluebirdPromise: Bluebird = Bluebird.resolve( + * new Promise(() => { return 'Lorem ipsum'; }) + * ); + * + * So the bottom line is: if you use these typings, then be mindful when you try to mix the global + * Promises with the Bluebird promises. You can avoid this problem by just settling on using either + * of them and not both of them at the same time. + * * 2. How to use it? * * It should just work, but there are a couple of points to be wary about: @@ -60,6 +79,17 @@ * d. target es6, latest "es20xx", e.g. "es2017" */ +/* + * @todo When dropping TS 2.x support, uncomment the following triple-slash directives and + * remove the copy&paste from this file (marked with #std-lib-copy&paste-to-remove) + * + * TS 2.x support should be dropped once bluebird's typings stop compiling on 2.x (i.e. + * once bluebird's typings stop supporting TS 2.x) + */ +/* /// */ +/* /// */ +/* /// */ + import Bluebird = require("bluebird"); declare global { @@ -73,7 +103,7 @@ declare global { bind: Bluebird["bind"]; call: Bluebird["call"]; cancel: Bluebird["cancel"]; - // catch: Bluebird["catch"]; + // catch: Bluebird["catch"]; // Provided by lib.es5.d.ts caught: Bluebird["caught"]; delay: Bluebird["delay"]; disposer: Bluebird["disposer"]; @@ -81,7 +111,7 @@ declare global { each: Bluebird["each"]; error: Bluebird["error"]; filter: Bluebird["filter"]; - // finally: Bluebird["finally"]; + // finally: Bluebird["finally"]; // Provided by lib.es2018.promise.d.ts get: Bluebird["get"]; isCancelled: Bluebird["isCancelled"]; isFulfilled: Bluebird["isFulfilled"]; @@ -103,7 +133,7 @@ declare global { suppressUnhandledRejections: Bluebird["suppressUnhandledRejections"]; tap: Bluebird["tap"]; tapCatch: Bluebird["tapCatch"]; - // then: Bluebird["then"]; + // then: Bluebird["then"]; // Provided by lib.es5.d.ts thenReturn: Bluebird["thenReturn"]; thenThrow: Bluebird["thenThrow"]; catchReturn: Bluebird["catchReturn"]; @@ -115,19 +145,18 @@ declare global { value: Bluebird["value"]; /* - * Copy&paste ::then and ::catch from lib.es2015.promise.d.ts, because Bluebird's typings are not + * Copy&paste ::then and ::catch from lib.es5.promise.d.ts, because Bluebird's typings are not * in line with the standard lib. * - * This is only needed for es5 target, which doesn't include the lib.es2015.promise.d.ts typings. + * #std-lib-copy&paste-to-remove * - * @todo Make Bluebird's typings be in line with the standard lib. + * @todo See the comment near the top of the file about code marked with #std-lib-copy&paste-to-remove */ - then(onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Promise; - then(onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, onrejected: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; - then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; - catch(onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Promise; - catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + then( + onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null + ): Promise; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; /* * TypeScript disallows adding overrides via `catch: typeof Bluebird.prototype.catch`. Copy&paste them then. @@ -142,7 +171,11 @@ declare global { catch(predicate: Object, onReject: (error: any) => U | PromiseLike): Bluebird; /* - * See comments above `then` for the reason why this is needed. Taken from esnext.promise.d.ts. + * See comments above `then` for the reason why this is needed. Taken from es2018.promise.d.ts. + * + * #std-lib-copy&paste-to-remove + * + * @todo See the comment near the top of the file about code marked with #std-lib-copy&paste-to-remove */ finally(onfinally?: (() => void) | undefined | null): Promise; } @@ -153,7 +186,7 @@ declare global { interface PromiseConstructor { new (callback: (resolve: (thenableOrResult?: T | PromiseLike) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void): Promise; - // all: typeof Bluebird.all; + // all: typeof Bluebird.all; // Provided by lib.es2015.d.ts any: typeof Bluebird.any; attempt: typeof Bluebird.attempt; bind: typeof Bluebird.bind; @@ -176,10 +209,10 @@ declare global { promisify: typeof Bluebird.promisify; promisifyAll: typeof Bluebird.promisifyAll; props: typeof Bluebird.props; - // race: typeof Bluebird.race; + // race: typeof Bluebird.race; // Provided by lib.es2015.d.ts reduce: typeof Bluebird.reduce; - // reject: typeof Bluebird.reject; - // resolve: typeof Bluebird.resolve; + // reject: typeof Bluebird.reject; // Provided by lib.es2015.d.ts + // resolve: typeof Bluebird.resolve; // Provided by lib.es2015.d.ts some: typeof Bluebird.some; try: typeof Bluebird.try; using: typeof Bluebird.using; @@ -187,9 +220,9 @@ declare global { /* * Copy&paste from lib.es2015.promise.d.ts, because Bluebird's typings are not in line with the standard lib. * - * This is only needed for es5 target, which doesn't include the lib.es2015.promise.d.ts typings. + * #std-lib-copy&paste-to-remove * - * @todo Make Bluebird's typings be in line with the standard lib. + * @todo See the comment near the top of the file about code marked with #std-lib-copy&paste-to-remove */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; @@ -219,6 +252,10 @@ declare global { /* * Declare the `Promise` variable. This is needed for es5 only and is a no-op for all other targets. + * + * #std-lib-copy&paste-to-remove + * + * @todo See the comment near the top of the file about code marked with #std-lib-copy&paste-to-remove */ var Promise: PromiseConstructor; } From 0a256eed0142a8410d6cc7e9f0264e0fa38d29d9 Mon Sep 17 00:00:00 2001 From: d-ph Date: Sun, 26 Aug 2018 15:35:28 +0100 Subject: [PATCH 207/289] [bluebird] Simplify the "catch()" typing --- types/bluebird/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 93dc18dfee..091dbe6e7a 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -70,8 +70,7 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - catch(onReject: (error: any) => Resolvable): Bluebird; - catch(onReject: ((error: any) => Resolvable) | undefined | null): Bluebird; + catch(onReject: ((error: any) => Resolvable) | undefined | null): Bluebird; /** * This extends `.catch` to work more like catch-clauses in languages like Java or C#. From 3e39c3ebbd63d1c35b21adbfcf6d8540c65b95de Mon Sep 17 00:00:00 2001 From: Artem Date: Sun, 26 Aug 2018 21:05:59 +0300 Subject: [PATCH 208/289] ReactPortal extends ReactElement. (#28264) --- types/react/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index e8de06ef62..f2f624d068 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -106,7 +106,7 @@ declare namespace React { type: keyof ReactSVG; } - interface ReactPortal { + interface ReactPortal extends ReactElement { key: Key | null; children: ReactNode; } From a4de39ab3e9211e59ca8e176144fe15a1ace808e Mon Sep 17 00:00:00 2001 From: sintetico82 Date: Sun, 26 Aug 2018 21:32:43 +0200 Subject: [PATCH 209/289] Added method to LCD class Added two method to LCD class: * noBacklight(): void; * backlight(): void; --- types/johnny-five/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/johnny-five/index.d.ts b/types/johnny-five/index.d.ts index 5f0f6a9f37..eafa4038de 100644 --- a/types/johnny-five/index.d.ts +++ b/types/johnny-five/index.d.ts @@ -378,6 +378,8 @@ export declare class LCD { autoscroll(): void; noAutoscroll(): void; bgColor(color: any): void; + noBacklight(): void; + backlight(): void; } export interface LedOption { From d40259ff0ff8f056d04b2c43754519073e7566af Mon Sep 17 00:00:00 2001 From: Alexander Marks Date: Sun, 26 Aug 2018 13:02:21 -0700 Subject: [PATCH 210/289] Add types for ansi-escape-sequences --- .../ansi-escape-sequences-tests.ts | 50 ++++++ types/ansi-escape-sequences/index.d.ts | 148 ++++++++++++++++++ types/ansi-escape-sequences/tsconfig.json | 23 +++ types/ansi-escape-sequences/tslint.json | 1 + 4 files changed, 222 insertions(+) create mode 100644 types/ansi-escape-sequences/ansi-escape-sequences-tests.ts create mode 100644 types/ansi-escape-sequences/index.d.ts create mode 100644 types/ansi-escape-sequences/tsconfig.json create mode 100644 types/ansi-escape-sequences/tslint.json diff --git a/types/ansi-escape-sequences/ansi-escape-sequences-tests.ts b/types/ansi-escape-sequences/ansi-escape-sequences-tests.ts new file mode 100644 index 0000000000..ae27a57146 --- /dev/null +++ b/types/ansi-escape-sequences/ansi-escape-sequences-tests.ts @@ -0,0 +1,50 @@ +import * as ansi from 'ansi-escape-sequences'; + +// $ExpectType string +ansi.style.red; +// $ExpectError +ansi.style.invalidStyle; + +// $ExpectType string +ansi.styles('green'); +// $ExpectType string +ansi.styles(['green', 'underline']); +// $ExpectError +ansi.styles('invalidStyle'); +// $ExpectError +ansi.styles(['invalidStyle']); + +// $ExpectType string +ansi.format('what?', 'green'); +// $ExpectType string +ansi.format('what?', ['green', 'bold']); +// $ExpectType string +ansi.format('[green bold]{what?}'); +// $ExpectError +ansi.styles('what?', 'invalidStyle'); +// $ExpectError +ansi.styles('what?', ['invalidStyle']); + +// $ExpectType string +ansi.cursor.up(); +// $ExpectType string +ansi.cursor.up(1); + +// $ExpectType string +ansi.cursor.hide; +// $ExpectType string +ansi.cursor.show; + +// $ExpectType string +ansi.erase.display(); +// $ExpectType string +ansi.erase.display(3); +// $ExpectError +ansi.erase.display(4); + +// $ExpectType string +ansi.erase.inLine(); +// $ExpectType string +ansi.erase.inLine(2); +// $ExpectError +ansi.erase.inLine(3); diff --git a/types/ansi-escape-sequences/index.d.ts b/types/ansi-escape-sequences/index.d.ts new file mode 100644 index 0000000000..437841aefa --- /dev/null +++ b/types/ansi-escape-sequences/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for ansi-escape-sequences 4.0 +// Project: https://github.com/75lb/ansi-escape-sequences#readme +// Definitions by: Alexander Marks +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export type Style = 'reset'|'bold'|'italic'|'underline'|'fontDefault'|'font2'| + 'font3'|'font4'|'font5'|'font6'|'imageNegative'|'imagePositive'|'black'| + 'red'|'green'|'yellow'|'blue'|'magenta'|'cyan'|'white'|'grey'|'gray'| + 'bg-black'|'bg-red'|'bg-green'|'bg-yellow'|'bg-blue'|'bg-magenta'|'bg-cyan'| + 'bg-white'|'bg-grey'|'bg-gray'; + +/** + * Various formatting styles (aka Select Graphic Rendition codes). + * + * @example + * console.log(ansi.style.red + 'this is red' + ansi.style.reset) + */ +export const style: {[K in Style]: string}; + +/** + * Returns an ansi sequence setting one or more effects. + * + * @param styles a style, or list or styles + * + * @example + * > ansi.styles('green') + * '\u001b[32m' + * + * > ansi.styles([ 'green', 'underline' ]) + * '\u001b[32;4m' + */ +export function styles(styles: Style|ReadonlyArray\n' + + '\n' + + ' \n' + + ' \n' + + ' \n' + + '\n'; + + return webview; +} + +onload = () => { + var webview = CreateWebViewAndGuest(); + document.body.appendChild(webview); +}; + // #endregion // #region Embedding & AppView @@ -1954,6 +1997,3 @@ document.body.appendChild(appview); appview.connect('id of app'); document.appendChild(appview); //#endregion - - - diff --git a/types/chrome-apps/webview.d.ts b/types/chrome-apps/webview.d.ts index 71eb4e5a6f..c23eefe17d 100644 --- a/types/chrome-apps/webview.d.ts +++ b/types/chrome-apps/webview.d.ts @@ -28,7 +28,7 @@ declare class HTMLWebViewElement extends HTMLElement { * 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'; + autosize?: 'on' | boolean; /** 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. @@ -154,7 +154,7 @@ declare class HTMLWebViewElement extends HTMLElement { * Rules are preserved even if the guest process crashes * or is killed or even if the webview is reparented. * Refer to the /extensions/content_scripts documentation for more details. - * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. + * @param contentScriptList Details of the content scripts to add. * @since Chrome 44. */ addContentScripts(contentScriptList: WebView.ContentScriptDetails[]): void; @@ -295,6 +295,9 @@ declare class HTMLWebViewElement extends HTMLElement { */ removeContentScripts(scriptNameList?: string[]): void; + /** Set an attribute */ + setAttribute(attributeName: string, value: string | number | boolean): void; + /** * Override the user agent string used by the webview for guest page requests. * @param userAgent The user agent string to use. @@ -453,7 +456,25 @@ declare class HTMLWebViewElement extends HTMLElement { addEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + + /// + /// STYLE + /// + + /** Maximum height */ + maxheight: number; + /** Minimum height */ + minheight: number; + /** Maximum width */ + maxwidth: number; + /** Minimum width */ + minwidth: number; + /** + * Allow scaling? + * @default false + */ + allowscaling?: boolean; } ///////////// // WEBVIEW // @@ -479,7 +500,7 @@ declare namespace WebView { 'loadstart': LoadStartEvent, 'loadstop': LoadStopEvent, 'newwindow': NewWindowEvent, - 'permissionrequest': PermissionRequest, + 'permissionrequest': PermissionRequestEvent, 'responsive': ResponsiveEvent, 'sizechanged': SizeChangedEvent, 'unresponsive': UnresponsiveEvent, @@ -924,36 +945,32 @@ declare namespace WebView { code?: string; /** JavaScript or CSS file to inject. */ - file?: string + file?: string; } /** The type of injection item: code or a set of files. */ interface InjectionItems { /** JavaScript code or CSS to be injected into matching pages. */ - code?: string + code?: string; /** * 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[] + files?: any[]; } /** Details of the content script to inject. **/ interface ContentScriptDetails { /** The name of the content script to inject. */ - name: string + name: string; /** Specifies which pages this content script will be injected into. */ - matches: any[] + matches: string[]; /** Excludes pages that this content script would otherwise be injected into. */ - exclude_matches?: any[] + exclude_matches?: string[]; - /** JavaScript or CSS file to inject. */ - file?: string - } - /** The type of injection item: code or a set of files. */ - interface InjectionItems { /** JavaScript code or CSS to be injected into matching pages. */ - code?: string + code?: string; + /** * Whether to insert the content script on about:blank and about:srcdoc. * Content scripts will only be injected on pages when their inherit URL From 8e32bbb4b6dcae495caf723a87f18b0bd1a9ddca Mon Sep 17 00:00:00 2001 From: taoqf Date: Tue, 28 Aug 2018 17:02:01 +0800 Subject: [PATCH 245/289] add typedefinition money-math --- types/money-math/index.d.ts | 21 +++++++++++++++++++++ types/money-math/money-math-tests.ts | 18 ++++++++++++++++++ types/money-math/tsconfig.json | 23 +++++++++++++++++++++++ types/money-math/tslint.json | 1 + 4 files changed, 63 insertions(+) create mode 100644 types/money-math/index.d.ts create mode 100644 types/money-math/money-math-tests.ts create mode 100644 types/money-math/tsconfig.json create mode 100644 types/money-math/tslint.json diff --git a/types/money-math/index.d.ts b/types/money-math/index.d.ts new file mode 100644 index 0000000000..95b5f846d7 --- /dev/null +++ b/types/money-math/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for money-math 2.5 +// Project: https://github.com/ikr/money-math#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace Money; + +export function add(a: string, b: string): string; +export function subtract(a: string, b: string): string; +export function mul(a: string, b: string): string; +export function div(a: string, b: string): string; +export function percent(a: string, b: string): string; +export function cmp(a: string, b: string): 0 | 1 | -1; +export function isEqual(a: string, b: string): boolean; +export function isZero(value: string): boolean; +export function isNegative(value: string): boolean; +export function isPositive(value: string): boolean; +export function floatToAmount(value: number): string; +export function format(currency: 'CHF' | 'CNY' | 'EUR' | 'GBP' | 'JPY' | 'LTL' | 'PLN' | 'SEK' | 'SKK' | 'UAH' | 'USD' | string, value: string): string; +export function roundUpTo5Cents(value: string): string; +export function roundTo5Cents(value: string): string; diff --git a/types/money-math/money-math-tests.ts b/types/money-math/money-math-tests.ts new file mode 100644 index 0000000000..9b93824ca1 --- /dev/null +++ b/types/money-math/money-math-tests.ts @@ -0,0 +1,18 @@ +import * as money from 'money-math'; + +money.add("16.11", "17.07"); // "33.18" +money.subtract("16.00", "7.00"); // "9.00" +money.mul("24.00", "0.25"); // "6.00" +money.div("64.00", "2.00"); // "32.00" +money.percent("200.00", "3.25"); // "6.50" +money.cmp("100.00", "200.00"); // -1 +money.isEqual("100.00", "100.00"); // true +money.isZero("0.00"); // true +money.isNegative("-1.00"); // true +money.isPositive("-1.00"); // false + +money.format("JPY", "236800.00"); // "236,800" +money.floatToAmount(56.345); // "56.35" + +money.roundUpTo5Cents("42.02"); // "42.05" +money.roundTo5Cents("442.26"); // "442.25" diff --git a/types/money-math/tsconfig.json b/types/money-math/tsconfig.json new file mode 100644 index 0000000000..fd8b7d167d --- /dev/null +++ b/types/money-math/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "money-math-tests.ts" + ] +} \ No newline at end of file diff --git a/types/money-math/tslint.json b/types/money-math/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/money-math/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6406610f5dd4d0ae7c530c449b5de4171aa50f27 Mon Sep 17 00:00:00 2001 From: Mateusz Krupa Date: Tue, 28 Aug 2018 11:02:13 +0200 Subject: [PATCH 246/289] [@types/pg-large-object] Added missing part --- types/pg-large-object/index.d.ts | 52 ++++++++++++++++-- .../pg-large-object/pg-large-object-tests.ts | 54 +++++++++++++++++-- 2 files changed, 99 insertions(+), 7 deletions(-) diff --git a/types/pg-large-object/index.d.ts b/types/pg-large-object/index.d.ts index 804b86df1a..64a450d545 100644 --- a/types/pg-large-object/index.d.ts +++ b/types/pg-large-object/index.d.ts @@ -2,14 +2,58 @@ // Project: https://github.com/Joris-van-der-Wel/node-pg-large-object#readme // Definitions by: Mateusz Krupa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// -import { WriteStream } from "fs"; +import stream = require("stream"); +import pg = require("pg"); + +export class LargeObject { + static readonly SEEK_SET: number; + static readonly SEEK_CUR: number; + static readonly SEEK_END: number; + constructor(query: any, oid: number, fd: any); + close(callback: (error: Error) => void): void; + closeAsync(): Promise; + read(length: number, callback: (error: Error, data: Buffer) => void): void; + readAsync(length: number): Promise; + write(buffer: Buffer, callback?: (error: Error) => void): void; + writeAsync(buffer: Buffer): Promise; + seek(position: number, ref: number, callback?: (error: Error, position: number) => void): void; + seekAsync(position: number, ref: number): Promise; + tell(callback: (error: Error, position: number) => void): void; + tellAsync(): Promise; + size(callback: (error: Error, size: number) => void): void; + sizeAsync(): Promise; + truncate(length: number, callback?: (error: Error) => void): void; + truncateAsync(length: number): Promise; + getReadableStream(bufferSize?: number): ReadStream; + getWritableStream(bufferSize?: number): WriteStream; +} + +export interface LargeObjectManagerSettings { + pg?: pg.Client; + pgPromise?: object; // module: pg-promise/Task +} export class LargeObjectManager { - constructor(options: any); - openAndReadableStreamAsync(oid: number, bufferSize: number): Promise<[number, NodeJS.ReadableStream]>; - createAndWritableStreamAsync(bufferSize: number): Promise<[number, WriteStream]>; + static readonly WRITE: number; + static readonly READ: number; + static readonly READWRITE: number; + constructor(options: LargeObjectManagerSettings|object); + open(oid: number, mode: number, callback: (error: Error, result: LargeObject) => void): void; + openAsync(oid: number, mode: number): Promise; + create(callback: (error: Error, oid: number) => void): void; + createAsync(): Promise; + openAndReadableStream(oid: number, bufferSize: number, callback: (error: Error, size: number, stream: ReadStream) => void): void; + openAndReadableStreamAsync(oid: number, bufferSize?: number): Promise<[number, ReadStream]>; + createAndWritableStream(bufferSize?: number, callback?: (error: Error, oid: number, stream: WriteStream) => void): void; + createAndWritableStreamAsync(bufferSize?: number): Promise<[number, WriteStream]>; + unlink(oid: number, callback?: (error: Error) => void): void; unlinkAsync(oid: number): Promise; } + +export class ReadStream extends stream.Readable {} + +export class WriteStream extends stream.Writable {} diff --git a/types/pg-large-object/pg-large-object-tests.ts b/types/pg-large-object/pg-large-object-tests.ts index 050fad80f6..42a939572b 100644 --- a/types/pg-large-object/pg-large-object-tests.ts +++ b/types/pg-large-object/pg-large-object-tests.ts @@ -1,8 +1,56 @@ -import { LargeObjectManager } from 'pg-large-object'; +import { + LargeObject, + LargeObjectManager, + LargeObjectManagerSettings, + ReadStream, + WriteStream +} from "pg-large-object"; +import { Buffer } from "buffer"; +import pg = require("pg"); +const buffer = new Buffer(""); const bufferSize = 16384; +const length = 16384; const oid = 1; -const lom = new LargeObjectManager({}); +const seekSetConst = LargeObject.SEEK_SET; // $ExpectType number +const seekCurConst = LargeObject.SEEK_CUR; // $ExpectType number +const seekEndConst = LargeObject.SEEK_END; // $ExpectType number + +const lo = new LargeObject({}, oid, {}); +lo.close((error: Error) => {}); // $ExpectType void +lo.closeAsync(); // $ExpectType Promise +lo.read(length, (error: Error, data: Buffer) => {}); // $ExpectType void +lo.readAsync(length); // $ExpectType Promise +lo.write(buffer, (error: Error) => {}); // $ExpectType void +lo.writeAsync(buffer); // $ExpectType Promise +lo.seek(0, LargeObject.SEEK_CUR, (error: Error, position: number) => {}); // $ExpectType void +lo.seekAsync(0, LargeObject.SEEK_CUR); // $ExpectType Promise +lo.tell((error: Error, position: number) => {}); // $ExpectType void +lo.tellAsync(); // $ExpectType Promise +lo.size((error: Error, size: number) => {}); // $ExpectType void +lo.sizeAsync(); //// $ExpectType Promise +lo.truncate(length, (error: Error) => {}); // $ExpectType void +lo.truncateAsync(length); // $ExpectType Promise +lo.getReadableStream(bufferSize); // $ExpectType ReadStream +lo.getWritableStream(bufferSize); // $ExpectType WriteStream + +const writeConst = LargeObjectManager.WRITE; // $ExpectType number +const readConst = LargeObjectManager.READ; // $ExpectType number +const readWriteConst = LargeObjectManager.READWRITE; // $ExpectType number +const config: LargeObjectManagerSettings = { + pg: new pg.Client(), + pgPromise: {} +}; + +const lom = new LargeObjectManager(config); +lom.open(oid, LargeObjectManager.READWRITE, (error: Error, result: LargeObject) => {}); // $ExpectType void +lom.openAsync(oid, LargeObjectManager.READWRITE); // $ExpectType Promise +lom.create((error: Error, oid: number) => {}); // $ExpectType void +lom.createAsync(); // $ExpectType Promise +lom.unlink(oid, (error: Error) => {}); // $ExpectType void +lom.unlinkAsync(oid); // $ExpectType Promise +lom.openAndReadableStream(oid, bufferSize, (error: Error, size: number, stream: ReadStream) => {}); // $ExpectType void +lom.openAndReadableStreamAsync(oid, bufferSize); // $ExpectType Promise<[number, ReadStream]> +lom.createAndWritableStream(bufferSize, (error: Error, oid: number, stream: WriteStream) => {}); // $ExpectType void lom.createAndWritableStreamAsync(bufferSize); // $ExpectType Promise<[number, WriteStream]> -lom.openAndReadableStreamAsync(oid, bufferSize); // $ExpectType Promise<[number, ReadableStream]> lom.unlinkAsync(oid); // $ExpectType Promise From 5a26aadb62dc0e22374dcfde063e1cd6f2c48529 Mon Sep 17 00:00:00 2001 From: taoqf Date: Tue, 28 Aug 2018 17:03:51 +0800 Subject: [PATCH 247/289] change return type --- types/money-math/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/money-math/index.d.ts b/types/money-math/index.d.ts index 95b5f846d7..a86734c477 100644 --- a/types/money-math/index.d.ts +++ b/types/money-math/index.d.ts @@ -10,7 +10,7 @@ export function subtract(a: string, b: string): string; export function mul(a: string, b: string): string; export function div(a: string, b: string): string; export function percent(a: string, b: string): string; -export function cmp(a: string, b: string): 0 | 1 | -1; +export function cmp(a: string, b: string): 0 | number; export function isEqual(a: string, b: string): boolean; export function isZero(value: string): boolean; export function isNegative(value: string): boolean; From 75ac903b6079bf972e5b3694094995a24a1d6898 Mon Sep 17 00:00:00 2001 From: Maurice de Beijer Date: Tue, 28 Aug 2018 11:39:36 +0200 Subject: [PATCH 248/289] Updates after review comments --- types/i18next/index.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 205f87f6e1..484745bcad 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -102,24 +102,24 @@ declare namespace i18next { wait?: boolean; /** * set it to fallback to let passed namespaces to translated hoc act as fallbacks - * @default default + * @default 'default' */ - nsMode?: string; + nsMode?: 'default' | 'fallback'; /** * set it to the default parent element created by the Trans component. - * @default div + * @default 'div' */ defaultTransParent?: string; /** * set which events trigger a rerender, can be set to false or string of events - * @default languageChanged loaded + * @default 'languageChanged loaded' */ - bindI18n?: string | boolean; + bindI18n?: string | false; /** * set which events on store trigger a rerender, can be set to false or string of events - * @default added removed + * @default 'added removed' */ - bindStore?: string | boolean; + bindStore?: string | false; } interface InitOptions { From 81bf290568b3a8c7dd89d51b0b8c24d73fd2b110 Mon Sep 17 00:00:00 2001 From: Florian Keller Date: Tue, 28 Aug 2018 11:50:08 +0200 Subject: [PATCH 249/289] fix: Add loose CSP for helmet --- types/helmet/helmet-tests.ts | 1 + types/helmet/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/types/helmet/helmet-tests.ts b/types/helmet/helmet-tests.ts index 53fba8e948..afedea6c23 100644 --- a/types/helmet/helmet-tests.ts +++ b/types/helmet/helmet-tests.ts @@ -58,6 +58,7 @@ function contentSecurityPolicyTest() { directives: { defaultSrc: ["'self'"] }, + loose: false, setAllHeaders: true })); } diff --git a/types/helmet/index.d.ts b/types/helmet/index.d.ts index 1abe99c20f..6f89728e8a 100644 --- a/types/helmet/index.d.ts +++ b/types/helmet/index.d.ts @@ -60,6 +60,7 @@ declare namespace helmet { disableAndroid?: boolean; browserSniff?: boolean; directives?: IHelmetContentSecurityPolicyDirectives; + loose?: boolean; } export interface IHelmetDnsPrefetchControlConfiguration { From 9e5e1174493f44d3e088f62f55a53b9b7ec7d801 Mon Sep 17 00:00:00 2001 From: Nikolai Ommundsen Date: Tue, 28 Aug 2018 11:52:32 +0200 Subject: [PATCH 250/289] Merge declarations to be able to import it more easily in other type declarations. --- types/chrome-apps/appview.d.ts | 51 - types/chrome-apps/index.d.ts | 1763 ++++++++++++++++++++++++++++++- types/chrome-apps/test/index.ts | 7 +- types/chrome-apps/web-apis.d.ts | 135 --- types/chrome-apps/webview.d.ts | 1562 --------------------------- 5 files changed, 1762 insertions(+), 1756 deletions(-) delete mode 100644 types/chrome-apps/appview.d.ts delete mode 100644 types/chrome-apps/web-apis.d.ts delete mode 100644 types/chrome-apps/webview.d.ts diff --git a/types/chrome-apps/appview.d.ts b/types/chrome-apps/appview.d.ts deleted file mode 100644 index 7fa5732308..0000000000 --- a/types/chrome-apps/appview.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Type definitions for Chrome packaged application development -// Project: http://developer.chrome.com/apps/ -// Definitions by: Nikolai Ommundsen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -///////////////// -// AppView Tag // -///////////////// -/** - * Use the appview tag to embed other Chrome Apps within your Chrome App. - * The appview runs in a separate process from your app, - * it doesn't inherit the same permissions and is only allowed - * to interact with your app through asynchronous APIs. - * Not all apps can be embedded; apps have to explicitly allow themselves to be embedded. - * @since Chrome 43. - * @requires Permissions: 'appview' - * @see[Documentation]{@link https://developer.chrome.com/apps/tags/appview} - */ -declare class HTMLAppViewElement extends HTMLElement { - /** Create a new AppView tag */ - constructor (); - /** - * Requests another app to be embedded. - * @param app The extension id of the app to be embedded. - * @param [data] Optional developer specified data that the app to be embedded can use when making an embedding decision. - * @param [callback] Optional callback when the embedding request is completed. Will provide the result. - */ - connect(app: string, data?: any, callback?: (success: boolean) => void): void; -} -declare namespace AppView { - interface EmbedRequest { - /** The ID of the app that sent the embedding request. */ - embedderId: string; - /** Optional developer specified data that the app to be embedded can use when making an embedding decision. */ - data?: any; - /** - * Allows the embedding request - * @param url Specifies the content to be embedded. - */ - allow(url: string): void; - /** Prevents the embedding request */ - deny(): void; - } -} - -declare interface Document { - createElement(element: 'appview'): HTMLAppViewElement; -} - -declare const AppView: typeof HTMLAppViewElement; diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 132e1f7c26..33b760ce82 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -5,9 +5,6 @@ // TypeScript Version: 2.8 /// -/// -/// -/// // // Extra sources in addition to the Chromium source code and official documentation: @@ -11506,11 +11503,1765 @@ declare namespace chrome { // #endregion } +///////////////// +// AppView Tag // +///////////////// +/** + * Use the appview tag to embed other Chrome Apps within your Chrome App. + * The appview runs in a separate process from your app, + * it doesn't inherit the same permissions and is only allowed + * to interact with your app through asynchronous APIs. + * Not all apps can be embedded; apps have to explicitly allow themselves to be embedded. + * @since Chrome 43. + * @requires Permissions: 'appview' + * @see[Documentation]{@link https://developer.chrome.com/apps/tags/appview} + */ +declare class HTMLAppViewElement extends HTMLElement { + /** Create a new AppView tag */ + constructor (); + /** + * Requests another app to be embedded. + * @param app The extension id of the app to be embedded. + * @param [data] Optional developer specified data that the app to be embedded can use when making an embedding decision. + * @param [callback] Optional callback when the embedding request is completed. Will provide the result. + */ + connect(app: string, data?: any, callback?: (success: boolean) => void): void; +} +declare namespace AppView { + interface EmbedRequest { + /** The ID of the app that sent the embedding request. */ + embedderId: string; + /** Optional developer specified data that the app to be embedded can use when making an embedding decision. */ + data?: any; + /** + * Allows the embedding request + * @param url Specifies the content to be embedded. + */ + allow(url: string): void; + /** Prevents the embedding request */ + deny(): void; + } +} + +declare interface Document { + createElement(element: 'appview'): HTMLAppViewElement; +} + +declare interface Window { + AppView: typeof AppView; +} + +declare const AppView: typeof HTMLAppViewElement; + + +declare interface HTMLElementTagNameMap { + 'appview': HTMLAppViewElement +} + +// Type definitions for Chrome packaged application development +// Project: http://developer.chrome.com/apps/ +// 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.8 + +///////////////// +// 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. + */ + +declare class HTMLWebViewElement extends HTMLElement { + /** + * 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' | boolean; + + /** 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; + + /** + * Object reference which can be used to post messages into the guest page. + */ + contentWindow: WebView.ContentWindow; + + /** This sets the guest content's window.name object.**/ + name: 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. + * 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; + + /** Interface which provides access to webRequest events on the guest page. */ + request: WebView.WebRequestEventInterface; + + /** + * 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. + * The src attribute cannot be cleared or removed once it has been set, unless the webview is removed from the DOM. + * The src attribute can also accept data URLs, such as 'data:text/plain,Hello, world!'. + */ + src: string; + + /** Create a new element */ + constructor (); + + /** + * Queries audio state. + * @since Chrome 62. + **/ + getAudioState(callback: (audible: boolean) => void): void; + + /** + * Sets audio mute state of the webview. + * @param mute Mute audio value + * @since Chrome 62. + */ + setAudioMuted(mute: boolean): void; + + /** + * Queries whether audio is muted. + * @since Chrome 62. + */ + isAudioMuted(callback: (muted: boolean) => void): void; + + /** + * Captures the visible region of the webview. + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. + */ + captureVisibleRegion(callback: (dataUrl: string) => void): void; + /** + * Captures the visible region of the webview. + * @param options Extension type + * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. + * May be assigned to the 'src' property of an HTML Image element for display. + * @since Chrome 50. + */ + captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; + + /** + * Adds content script injection rules to the webview. + * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. + * You can programmatically add rules or update existing rules. + * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. + * @example + * webview.addContentScripts([ + * { + * name: 'myRule', + * matches: ['http://www.foo.com/*'], + * css: { files: ['mystyles.css'] }, + * js: { files: ['jquery.js', 'myscript.js'] }, + * run_at: 'document_start' + * }, + * { + * name: 'anotherRule', + * matches: ['http://www.bar.com/*'], + * js: { code: 'document.body.style.backgroundColor = 'red';' }, + * run_at: 'document_end' + * }]); + * ... + * // Navigates webview. + * webview.src = 'http://www.foo.com'; + * + * @description + * You can defer addContentScripts call until you needs to inject scripts. + * The following example shows how to overwrite an existing rule. + * @example + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.foo.com/*'], + * js: { files: ['scriptA.js'] }, + * run_at: 'document_start'}]); + * + * // Do something. + * webview.src = 'http://www.foo.com/*'; + * ... + * // Overwrite 'rule' defined before. + * webview.addContentScripts([{ + * name: 'rule', + * matches: ['http://www.bar.com/*'], + * js: { files: ['scriptB.js'] }, + * run_at: 'document_end'}]); + * @description + * If webview has been naviagted to the origin (e.g., foo.com) and + * calls webview.addContentScripts to add 'myRule', + * you need to wait for next navigation to make the scripts injected. + * If you want immediate injection, executeScript will do the right thing. + * Rules are preserved even if the guest process crashes + * or is killed or even if the webview is reparented. + * Refer to the /extensions/content_scripts documentation for more details. + * @param contentScriptList Details of the content scripts to add. + * @since Chrome 44. + */ + addContentScripts(contentScriptList: WebView.ContentScriptDetails[]): void; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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 Called after the data has been successfully cleared. + * @since Chrome 33. + */ + clearData(options: WebView.ClearDataOptions, types: WebView.ClearDataTypeSet, callback?: () => void): void; + + /** + * 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] Called after all the JavaScript has been executed. + */ + executeScript(details: WebView.InjectDetails, callback?: (result?: any[]) => void): void; + + /** + * Initiates a find-in-page request. + * @param searchText The string to find in the page. + * @param [options] Options for the find request. + * @param [callback] Called after all find results have been returned for this find request. + * Provides optionally: + * results: Contains all of the results of the find request. + * results can be omitted if it is not utilized in the callback function body; + * e.g. if the callback is only used to discern when the find request has completed. + */ + find(searchText: string, options?: WebView.FindOptions, callback?: (results?: WebView.FindCallbackResults) => void): void; + + /** + * Navigates forward one history entry if possible. Equivalent to go(1). + * @param [callback] Called after the navigation has either failed or completed successfully. + * Provides *success* which indicates whether the navigation was successful. + */ + forward(callback?: (success: boolean) => void): void; + + /** + * 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(): chrome.integer; + + /** + * Returns the user agent string used by the webview for guest page requests. + * @since Chrome 33. + */ + getUserAgent(): string; + + /** + * Gets the current zoom factor. + * @param callback Called after the current zoom factor is retrieved. Provides the current zoom factor. + * @since Chrome 36. + */ + getZoom(callback: (zoomFactor: chrome.double) => void): void; + + /** + * Gets the current zoom mode. + * @param callback Called with the webview's current zoom mode. + * @since Chrome 43. + */ + getZoomMode(callback: (ZoomMode: WebView.ZoomMode) => void): void; + + /** + * 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] Called after the navigation has either failed or completed successfully. + * Provides a boolean, *success*, which indicates whether the navigation was successful. + */ + go(relativeIndex: chrome.integer, callback?: (success: boolean) => void): void; + + /** + * Injects CSS into the guest page. + * @param details Details of the CSS to insert. + * @param callback Called after the CSS has been inserted. + */ + insertCSS(details: WebView.InjectDetails, callback?: () => void): void; + + /** + * Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. + * @since Chrome 33. + */ + isUserAgentOverridden(): void; + + /** + * Prints the contents of the webview. + * This is equivalent to calling scripted print function from the webview itself. + * @since Chrome 38. + */ + print(): void; + + /** Reloads the current top-level page. */ + reload(): void; + + /** + * 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(); + * @param 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. + * @since Chrome 44. + */ + removeContentScripts(scriptNameList?: string[]): void; + + /** Set an attribute */ + setAttribute(attributeName: string, value: string | number | boolean): void; + + /** + * Override the user agent string used by the webview for guest page requests. + * @param userAgent The user agent string to use. + * @since Chrome 33. + */ + setUserAgentOverride(userAgent: string): void; + + /** + * 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] Called after the page has been zoomed. + * @since Chrome 36. + */ + setZoom(zoomFactor: chrome.double, callback?: () => void): void; + + /** + * Sets the zoom mode of the webview. + * @param ZoomMode Defines how zooming is handled in the webview. + * @param [callback] Called after the zoom mode has been changed. + * @since Chrome 43. + */ + setZoomMode(ZoomMode: WebView.ZoomMode, callback?: () => void): void; + + /** Stops loading the current webview navigation if in progress. */ + stop(): void; + + /** + * Ends the current find session (clearing all highlighting) + * and cancels all find requests in progress. + * @param 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. + * @since Chrome 35. + */ + stopFinding(action?: 'clear' | 'keep' | 'activate'): void; + + /** + * 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 dataUrl The data URL to load. + * @param baseUrl The base URL that will be used for relative links. + * @param virtualUrl The URL that will be displayed to the user (in the address bar). + * @since Chrome 40. + */ + loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; + + /** + * 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; + + + /// + /// DOM Events + /// + + /** Fired when the guest window logs a console message. */ + onconsolemessage: ((this: HTMLWebViewElement, ev: WebView.Events.ConsoleMessageEvent) => any) | null; + /** + * 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. + */ + oncontentload: ((this: HTMLWebViewElement, ev: WebView.Events.ContentLoadEvent) => any) | null; + /** + * 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.) + */ + ondialog: ((this: HTMLWebViewElement, ev: WebView.Events.DialogEvent) => any) | null; + /** + * Fired when the process rendering the guest web content has exited. + */ + onexit: ((this: HTMLWebViewElement, ev: WebView.Events.ExitEvent) => any) | null; + /** + * 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. + */ + onfindupdate: ((this: HTMLWebViewElement, ev: WebView.Events.FindUpdateEvent) => any) | null; + /** + * 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'. + */ + onloadabort: ((this: HTMLWebViewElement, ev: WebView.Events.LoadAbortEvent) => any) | null; + /** + * 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. + */ + onloadcommit: ((this: HTMLWebViewElement, ev: WebView.Events.LoadCommitEvent) => any) | null; + /** + * Fired when a top-level load request has redirected to a different URL. + */ + onloadredirect: ((this: HTMLWebViewElement, ev: WebView.Events.LoadRedirectEvent) => any) | null; + /** + * 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. + */ + onloadstop: ((this: HTMLWebViewElement, ev: WebView.Events.LoadStopEvent) => any) | null; + /** + * Fired when the guest page attempts to open a new browser window. + */ + onnewwwindow: ((this: HTMLWebViewElement, ev: WebView.Events.NewWindowEvent) => any) | null; + /** + * Fired when the guest page needs to request special permission from the embedder. + */ + onpermissionrequest: ((this: HTMLWebViewElement, ev: WebView.Events.PermissionRequestEvent) => any) | null; + /** + * Fired when the process rendering the guest web content has become responsive again after being unresponsive. + */ + onresponsive: ((this: HTMLWebViewElement, ev: WebView.Events.ResponsiveEvent) => any) | null; + /** + * @requires autosize: enabled + * Fired when the embedded web content has been resized via autosize. + * Only fires if autosize is enabled. + */ + onsizechanged: ((this: HTMLWebViewElement, ev: WebView.Events.SizeChangedEvent) => any) | null; + /** + * 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. + */ + onunresponsive: ((this: HTMLWebViewElement, ev: WebView.Events.UnresponsiveEvent) => any) | null + /** + * Fired when the page's zoom changes. + */ + onzoomchange: ((this: HTMLWebViewElement, ev: WebView.Events.ZoomChangeEvent) => any) | null; + + + addEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + + /// + /// STYLE + /// + + /** Maximum height */ + maxheight: number; + /** Minimum height */ + minheight: number; + /** Maximum width */ + maxwidth: number; + /** Minimum width */ + minwidth: number; + /** + * Allow scaling? + * @default false + */ + allowscaling?: boolean; +} +///////////// +// WEBVIEW // +///////////// +/** + * WebView Events, Methods and interfaces. + */ +declare namespace WebView { + /** + * WebView Events are different from Chrome Events, they extend the normal DOM Events. + */ + namespace Events { + interface WebViewElementEventMap extends HTMLElementEventMap { + 'close': CloseEvent, + 'consolemessage': ConsoleMessageEvent, + 'contentload': ContentLoadEvent, + 'dialog': DialogEvent, + 'exit': ExitEvent, + 'findupdate': FindUpdateEvent, + 'loadabort': LoadAbortEvent, + 'loadcommit': LoadCommitEvent, + 'loadredirect': LoadRedirectEvent, + 'loadstart': LoadStartEvent, + 'loadstop': LoadStopEvent, + 'newwindow': NewWindowEvent, + 'permissionrequest': PermissionRequestEvent, + 'responsive': ResponsiveEvent, + 'sizechanged': SizeChangedEvent, + 'unresponsive': UnresponsiveEvent, + 'zoomchange': ZoomChangeEvent + } + + /** + * 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. + */ + interface CloseEvent extends Event { } + + type ConsoleMessageLevel = -1 | 0 | 1 | 2; + + /** + * 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. + */ + interface ConsoleMessageEvent extends Event { + /** + * 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; + /** The logged message contents. */ + message: string; + /** The line number of the message source. */ + line: chrome.integer; + /** A string identifying the resource which logged the message. */ + sourceId: string; + } + + /** + * 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'' }) + * }); + */ + interface ContentLoadEvent extends Event { } + + /** + * 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. + */ + 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'; + + /** + * The type of modal dialog requested by the guest. + */ + type DialogMessageType = + 'alert' | + 'confirm' | + 'prompt'; + /** + * 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. + */ + interface DialogEvent extends Event { + /** + * The type of modal dialog requested by the guest. + */ + messageType: DialogMessageType; + /** + * The text the guest attempted to display in the modal dialog. + */ + messageText: string; + /** + * An interface that can be used to respond to the guest's modal request. + */ + dialog: DialogController; + } + + /** + * String indicating the reason for the exit. + */ + type ExitEventReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; + + /** + * Fired when the process rendering the guest web content has exited. + */ + interface ExitEvent extends Event { + /** Chrome's internal ID of the process that exited. */ + processID: chrome.integer; + /** String indicating the reason for the exit. */ + reason: ExitEventReason; + } + + /** + * 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. + */ + interface FindUpdateEvent extends Event { + /** + * The string that is being searched for in the page. + */ + searchText: string; + /** + * The number of matches found for searchText on the page so far. + */ + numberOfMatches: chrome.integer; + /** + * The ordinal number of the current active match, + * if it has been found. This will be 0 until then. + */ + activeMatchOrdinal: chrome.integer; + /** + * Describes a rectangle around the active match, + * if it has been found, in screen coordinates. + */ + selectionRect: SelectionRect; + /** + * Indicates whether the find request was canceled. + */ + canceled: boolean; + /** + * Indicates that all find requests have completed + * and that no more findupdate events will be fired + * until more find requests are made. + */ + finalUpdate: string; + } + + /** + * 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'. + */ + interface LoadAbortEvent extends Event { + /** Requested URL. */ + url: string; + /** Whether the load was top-level or in a subframe. */ + isTopLevel: boolean; + /** + * Unique chrome.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 chrome.integer. + */ + code: chrome.integer; + /** + * 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: LoadAbortReason; + } + + /** + * 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. + */ + interface LoadCommitEvent extends Event { + /** The URL that committed. */ + url: string; + /** Whether the load is top-level or in a subframe. */ + isTopLevel: boolean; + } + + /** + * Fired when a top-level load request has redirected to a different URL. + */ + interface LoadRedirectEvent { + /** 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; + } + /** + * Fired when a load has begun. + */ + interface LoadStartEvent extends Event { + /** Requested URL. */ + url: string; + /** Whether the load is top-level or in a subframe. */ + isTopLevel: boolean; + } + + /** + * 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. + */ + interface LoadStopEvent extends Event { } + + /** The requested disposition of the new window. */ + type WindowOpenDisposition = + 'ignore' | + 'save_to_disk' | + 'current_tab' | + 'new_background_tab' | + 'new_foreground_tab' | + 'new_window' | + 'new_popup'; + + /** + * 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); + * }); + */ + interface NewWindowEvent extends Event { + /** + * 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; + + /** The target URL requested for the new window. */ + targetUrl: string; + + /** The initial width requested for the new window. */ + initialWidth: chrome.integer; + + /** The initial height requested for the new window. */ + initialHeight: chrome.integer; + + /** The requested name of the new window. */ + name: string; + + /** The requested disposition of the new window. */ + windowOpenDisposition: WindowOpenDisposition; + } + + type RequestedPermission = + 'media' | + 'geolocation' | + 'pointerLock' | + 'download' | + 'loadplugin' | + 'filesystem' | + 'fullscreen'; + + /** + * @requires `Permissions:` `audioCapture` and/or `videoCapture` + * @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: + * + * @example + * webview.addEventListener('permissionrequest', (e) => { if (e.permission === 'media') e.request.allow(); }); + */ + interface PermissionRequestEvent extends Event { + /** The type of permission being requested. */ + permission: RequestedPermission; + /** An object which holds details of the requested permission.*/ + request: PermissionRequestHandler; + } + + /** + * 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', () => { + * webview.style.opacity = '0.5'; + * }); + * webview.addEventListener('responsive', () => { + * webview.style.opacity = '1'; + * }); + */ + interface ResponsiveEvent extends Event { + /** Chrome's internal ID of the process that became responsive. */ + processID: chrome.integer; + } + + /** + * Fired when the embedded web content has been resized via autosize. + * Only fires if autosize is enabled. + */ + interface SizeChangedEvent extends Event { + /** Old width of embedded web content. */ + oldWidth: chrome.integer; + /** Old height of embedded web content. */ + oldHeight: chrome.integer; + /** New width of embedded web content. */ + newWidth: chrome.integer; + /** New height of embedded web content. */ + newHeight: chrome.integer; + } + + /** + * 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. + */ + interface UnresponsiveEvent extends Event { + /** Chrome's internal ID of the process that has become unresponsive. */ + processID: chrome.integer; + } + + /** Fired when the page's zoom changes. */ + interface ZoomChangeEvent extends Event { + /** The page's previous zoom factor. */ + oldzoomFactor: chrome.double; + /** The new zoom factor that the page was zoomed to. */ + newzoomFactor: chrome.double; + } + + } + + /** 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). + * @default 0 + */ + since?: chrome.integer; + } + + + /** + * 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 { + /** + * 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, + /** + * JavaScript or CSS file to inject. + */ + file?: string + } + + /** + * WebView element from html + */ + + + /** A set of data types. Missing properties are interpreted as false. */ + interface ClearDataTypeSet { + /** Websites' appcaches. */ + appcache?: boolean; + /** + * The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. + * @since Chrome 43. + */ + 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. + **/ + 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 { + /** + * 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; + + /** JavaScript or CSS file to inject. */ + file?: string; + } + /** The type of injection item: code or a set of files. */ + interface InjectionItems { + /** JavaScript code or CSS to be injected into matching pages. */ + code?: string; + /** + * 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. **/ + interface ContentScriptDetails { + /** The name of the content script to inject. */ + name: string; + + /** Specifies which pages this content script will be injected into. */ + matches: string[]; + + /** Excludes pages that this content script would otherwise be injected into. */ + exclude_matches?: string[]; + + /** JavaScript code or CSS to be injected into matching pages. */ + code?: string; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * The soonest that the JavaScript or CSS will be injected into the tab. + * Defaults to 'document_idle'. + */ + run_at?: chrome.extensionTypes.RunAt; + + /** + * 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; + + /** + * Applied after matches to include only those URLs that also match this glob. + * Intended to emulate the @include Greasemonkey keyword. + */ + include_globs?: string[]; + + /** + * Applied after matches to exclude URLs that match this glob. + * Intended to emulate the @exclude Greasemonkey keyword. + */ + exclude_globs?: string[]; + } + interface ContextMenuCreateProperties { + + /** + * The type of menu item. Defaults to 'normal' if not specified. + */ + type?: chrome.ToStringLiteral; + + /** + * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. + */ + 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?: any[]; + + /** + * A function that will be called back when the menu item is clicked. + */ + onclick?: (info: any) => void + + /** + * The ID of a parent menu item; this makes the item a child of a previously added item. + */ + parentId?: chrome.integer | 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?: any[]; + + /** + * 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[]; + + /** + * Whether this context menu item is enabled or disabled. Defaults to true. + */ + enabled?: boolean; + } + interface ContextMenuUpdateProperties { + /** The type of menu item. */ + type?: WebView.ContextType; + + /** The text to be displayed in the item */ + title?: string; + + /** + * 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; + + /** + * List of contexts this menu item will appear in. + */ + contexts?: any[]; + + /** + * A function that will be called back when the menu item is clicked. + * @param callback + */ + onclick?: (info: any) => void; + + /** + * 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?: chrome.integer | 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.) + */ + documentUrlPatterns?: any[]; + + /** + * 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[]; + + /** + * Whether this context menu item is enabled or disabled. + */ + enabled?: boolean; + } + interface OnShowEvent { + /** Call this to prevent showing the context menu. */ + preventDefault: () => void; + } + interface ContextMenus { + /** + * 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; + + /** + * 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: chrome.integer | string, updateProperties: object, callback?: () => void): void; + + /** + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param [callback] + */ + remove(menuItemId: chrome.integer | string, callback?: () => void): void; + + /** + * Removes all context menu items added to this webview. + * @param [callback] + */ + removeAll(callback?: () => void): void; + + /** + * 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<(event: OnShowEvent) => void>; + } + /** Messaging handle to a guest window. */ + interface ContentWindow { + /** + * 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 attached to dialog DOM events. */ + interface DialogController { + /** + * 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; + /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ + cancel(): void; + } + /** Contains all of the results of the find request. */ + interface FindCallbackResults { + /** The number of times searchText was matched on the page. */ + numberOfMatches: chrome.integer; + /** The ordinal number of the current match. */ + activeMatchOrdinal: chrome.integer; + /** Describes a rectangle around the active match in screen coordinates. */ + selectionRect: SelectionRect; + /** Indicates whether this find request was canceled. */ + canceled: boolean; + } + interface FindOptions { + /** + * Flag to find matches in reverse order. + * @default false + */ + backward?: boolean; + /** + * Flag to match with case-sensitivity. + * @default false + */ + matchCase?: boolean; + } + interface NewWindow { + /** + * 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: HTMLWebViewElement): void; + /** + * Cancel the new window request. + */ + discard(): void; + } + interface PermissionRequestHandler { + /** Allow the permission request. */ + allow(): void; + /** Deny the permission request. This is the default behavior if allow is not called. */ + deny(): void; + } + /** + * 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 { + /** Distance from the left edge of the screen to the left edge of the rectangle. */ + left: chrome.integer; + /** Distance from the top edge of the screen to the top edge of the rectangle. */ + top: chrome.integer; + /** Width of the rectangle. */ + width: chrome.integer; + /** Height of the rectangle. */ + height: chrome.integer; + } + + /** An HTTP Header, represented as an object containing a key and either a value or a binaryValue. */ + interface HttpHeader { + name: string; + value?: string; + binaryValue?: ArrayBuffer; + } + + interface ResourceRequest { + url: string; + /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ + requestId: string; + /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ + frameId: chrome.integer; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: chrome.integer; + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ + tabId: chrome.integer; + /** + * How the requested resource will be used. + */ + type: chrome.webRequest.ResourceType; + /** The time when this signal is triggered, in milliseconds since the epoch. */ + timeStamp: chrome.double; + /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. + * @since Chrome 63. + */ + initiator?: string; + } + + interface WebRequestDetails extends ResourceRequest { + /** Standard HTTP method. */ + method: string; + } + + interface WebRequestHeadersDetails extends WebRequestDetails { + /** Optional. The HTTP request headers that are going to be sent out with this request. */ + requestHeaders?: HttpHeader[]; + } + + interface WebRequestBodyDetails extends WebRequestDetails { + /** + * Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'. + * @since Chrome 23. + */ + requestBody: WebRequestBody; + } + + /** + * Contains data uploaded in a URL request. + * @since Chrome 23. + */ + interface UploadData { + /** Optional. An ArrayBuffer with a copy of the data. */ + bytes?: ArrayBuffer; + /** Optional. A string with the file's path and name. */ + file?: string; + } + + interface WebRequestBody { + /** Optional. Errors when obtaining request body data. */ + error?: string; + /** + * Optional. + * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. + */ + formData?: { [key: string]: string[] }; + /** + * Optional. + * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. + */ + raw?: UploadData[]; + } + + interface WebRequestFullDetails extends WebRequestHeadersDetails, WebRequestBodyDetails { + } + + interface WebResponseDetails extends ResourceRequest { + /** HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line). */ + statusLine: string; + /** + * Standard HTTP status code returned by the server. + * @since Chrome 43. + */ + statusCode: chrome.integer; + } + + interface WebResponseHeadersDetails extends WebResponseDetails { + /** Optional. The HTTP response headers that have been received with this response. */ + responseHeaders?: HttpHeader[]; + /** standard HTTP method i.e. GET, POST, PUT, etc. */ + method: string; + } + + interface WebResponseCacheDetails extends WebResponseHeadersDetails { + /** + * Optional. + * The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address. + */ + ip?: string; + /** Indicates if this response was fetched from disk cache. */ + fromCache: boolean; + } + + interface WebRedirectionResponseDetails extends WebResponseCacheDetails { + /** The new URL. */ + redirectUrl: string; + } + + /** An object describing filters to apply to webRequest events. */ + interface RequestFilter { + /** Optional. */ + tabId?: chrome.integer; + /** + * A list of request types. Requests that cannot match any of the types will be filtered out. + */ + types?: chrome.webRequest.ResourceType[]; + /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ + urls: string[]; + + /** Optional. */ + windowId?: chrome.integer; + } + + interface AuthCredentials { + username: string; + password: string; + } + + /** Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests. */ + interface BlockingResponse { + /** + * If true, the request is cancelled. + * Used in onBeforeRequest, this prevents the request from being sent. */ + cancel?: boolean; + /** + * Only used as a response to the onBeforeRequest and onHeadersReceived events. + * If set, the original request is prevented from being sent/completed and is + * instead redirected to the given URL. Redirections to non-HTTP schemes such + * as data: are allowed. Redirects initiated by a redirect action use the + * original request method for the redirect, with one exception: If the + * redirect is initiated at the onHeadersReceived stage, then the redirect + * will be issued using the GET method. + */ + redirectUrl?: string; + /** + * Only used as a response to the onHeadersReceived event. + * If set, the server is assumed to have responded with these + * response headers instead. Only return responseHeaders if you really + * want to modify the headers in order to limit the number of conflicts + * (only one extension may modify responseHeaders for each request). + */ + responseHeaders?: HttpHeader[]; + /** + * Only used as a response to the onAuthRequired event. + * If set, the request is made using the supplied credentials. + */ + authCredentials?: AuthCredentials; + /** + * Only used as a response to the onBeforeSendHeaders event. + * If set, the request is made with these request headers instead. + */ + requestHeaders?: HttpHeader[]; + } + + interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { + /** The authentication scheme, e.g. Basic or Digest. */ + scheme: string; + /** The authentication realm provided by the server, if there is one. */ + realm?: string; + /** The server requesting authentication. */ + challenger: WebAuthChallenger; + /** True for Proxy-Authenticate, false for WWW-Authenticate. */ + isProxy: boolean; + } + + interface WebRequestBodyEvent extends chrome.events.Event<(details: WebRequestBodyDetails) => void> { + addListener(callback: (details: WebRequestBodyDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebRequestHeadersEvent extends chrome.events.Event<(details: WebRequestHeadersDetails) => void> { + addListener(callback: (details: WebRequestHeadersDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface _WebResponseHeadersEvent extends chrome.events.Event<(details: T) => void> { + addListener(callback: (details: T) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseHeadersEvent extends _WebResponseHeadersEvent { } + + interface WebResponseCacheEvent extends _WebResponseHeadersEvent { } + + interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent { } + + interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { + addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } + + interface WebResponseErrorEvent extends _WebResponseHeadersEvent { } + + interface WebResponseErrorDetails extends WebResponseCacheDetails { + /** The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. */ + error: string; + } + + interface WebAuthChallenger { + host: string; + port: chrome.integer; + } + + /** + * 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 { + /** Fired when a request is about to occur. */ + onBeforeRequest: WebRequestBodyEvent; + /** + * Fired before sending an HTTP request, once the request headers are available. + * This may occur after a TCP connection is made to the server, but before any HTTP data is sent. + */ + onBeforeSendHeaders: WebRequestHeadersEvent; + /** + * Fired just before a request is going to be sent to the server + * (modifications of previous onBeforeSendHeaders callbacks + * are visible by the time onSendHeaders is fired). + */ + onSendHeaders: WebRequestHeadersEvent; + /** Fired when HTTP response headers of a request have been received. */ + onHeadersReceived: WebResponseHeadersEvent; + /** + * Fired when an authentication failure is received. + * The listener has three options: it can provide authentication credentials, + * it can cancel the request and display the error page, or it can take no + * action on the challenge. If bad user credentials are provided, this may be + * called multiple times for the same request. + */ + onAuthRequired: WebAuthenticationChallengeEvent; + /** + * Fired when the first byte of the response body is received. + * For HTTP requests, this means that the status line and + * response headers are available. + */ + onResponseStarted: WebResponseCacheEvent; + /** Fired when a server-initiated redirect is about to occur. */ + onBeforeRedirect: WebRedirectionResponseEvent; + /** Fired when a request is completed. */ + onCompleted: WebResponseCacheEvent; + /** Fired when an error occurs. */ + onErrorOccured: WebResponseErrorEvent; + /** + * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onRequest: chrome.webViewRequest.OnRequestEvent; + /** + * This interface supports declarative webRequest rules through + * **onRequest** and **onMessage** events. + * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} + */ + onMessage: chrome.webViewRequest.OnMessageEvent; + } + /** + * 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. + * '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). + * 'disabled' + * > 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'; +} + +declare interface Document { + createElement(element: 'webview'): HTMLWebViewElement; +} + +declare interface Window { + WebView: typeof WebView; +} + +declare const WebView: typeof HTMLWebViewElement; + + +declare interface HTMLElementTagNameMap { + 'webview': HTMLWebViewElement +} + + +///////////////////////// +// WEB APIs & Warnings // +///////////////////////// +/** + * Only warnings since: + * 1. It's not possible as of now to override or remove something from *Window* or *Document*. + * 2. It may also cause other unforseen consequences if it's removed (and if it was possible). + * @see[Disallowed] + */ +/** + * Chrome app - Web APIs + * @see[Docs]{@link https://developer.chrome.com/apps/api_other} + */ +interface ChromeWindow { + /// + /// Disabled Web Features + /// https://developer.chrome.com/apps/app_deprecated + /// + + /** + * ❗ alert is not available in packaged apps. ❗ + * Work-around: Use a custom lightbox / popup. + */ + alert(message?: any): void; + /** + * ❗ confirm is not available in packaged apps. ❗ + * Work-around: Use a custom lightbox / popup. + */ + confirm(message?: string): boolean; + + + /** + * ❗ window.localStorage is not available in packaged apps. Use chrome.storage.local instead. ❗ + */ + // localStorage: typeof localStorage; + + + /** + * ❗ window.location is not available in packaged apps. ❗ + * Links open up with the system web browser. + */ + location: Location; + /** + * ❗ window.history is not available in packaged apps. ❗ + * Links open up with the system web browser. + */ + readonly history: History; + + /// + /// Other APIs + /// + AudioContext: typeof AudioContext; +} + +interface Document { + /** + * ❗ document.cookie is not available in packaged apps. ❗ + * Packaged app pages are not rendered on the server, so there is no need to use these. + */ + cookie: string; + /** + * ❗ document.close is not available in packaged apps. ❗ + */ + close(): void; + /** + * ❗ document.open is not available in packaged apps. ❗ + */ + open(url?: string, name?: string, features?: string, replace?: boolean): Document; + /** + * ❗ document.write is not available in packaged apps. ❗ + */ + write(...content: string[]): void; +} + +/** + * ❗ iframes are not available in packaged apps, use webviews instead. ❗ + */ +interface HTMLIFrameElement { } + +/** + * ❗ Modal dialogs are not available in packaged apps, use lightbox/popup instead. ❗ + */ +interface HTMLDialogElement { } + +interface HTMLElement { + /** + * @requires Permissions: 'app.window.fullscreen', 'app.window.fullscreen.overrideEsc' + * @description + * In Chrome Apps, fullscreen is entered without prompting the user or providing + * exit instructions. HTML5 fullscreen requires the app.window.fullscreen permission + * in the manifest. In normal webpages, the browser intercepts the ESC key to exit + * pointer lock ensuring a consistent escape method for users. That is also the + * behavior in Chrome Apps unless the app.window.fullscreen.overrideEsc permission + * is used to enable the app to call preventDefault on keydown and keyup events. + * + * Then to exit fullscreen, the document exposes a method for that: + * @example + * document.webkitExitFullscreen(); + */ + webkitRequestFullscreen(): void; +} + +interface HTMLElement { + /** + * ❗ Unprefixed version are not available as of Chrome 68, in Chrome apps ❗ + */ + requestFullscreen(): void; + /** + * ❗ Unprefixed version are not available as of Chrome 68, in Chrome apps ❗ + */ + exitrequestFullscreen(): void; + /** + * @requires Permissions: 'pointerLock' + */ + requestPointerLock(): void; + /** + * @requires Permissions: 'pointerLock' + */ + exitPointerLock(): void; +} + +interface Navigator { + /** + * If you provide the 'geolocation' in your Chrome app it will allow the app to + * use the proposed HTML5 geolocation API without prompting the user for permission. + * @see Permissions: 'geolocation' + */ + readonly geolocation: Geolocation; +} + //////////// -// EXPORT // +// GLOBAL // //////////// declare interface Window extends ChromeWindow { chrome: typeof chrome; - WebView: typeof HTMLWebViewElement; - AppView: typeof HTMLAppViewElement; } diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 7915b40433..93864d107b 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -4,7 +4,7 @@ * @author The Chromium Authors */ -import runtime = chrome.app.runtime; +const runtime = chrome.app.runtime; const cwindow = chrome.app.window; // #region FORBIDDEN APIs @@ -449,7 +449,7 @@ const createOptions: chrome.app.CreateWindowOptions = { }; //Create new window on app launch -chrome.app.runtime.onLaunched.addListener((launchData: runtime.LaunchData) => { +chrome.app.runtime.onLaunched.addListener((launchData: chrome.app.runtime.LaunchData) => { chrome.app.window.create('app/url', createOptions, (created_window: chrome.app.AppWindow) => { return; }); @@ -1997,3 +1997,6 @@ document.body.appendChild(appview); appview.connect('id of app'); document.appendChild(appview); //#endregion + + + diff --git a/types/chrome-apps/web-apis.d.ts b/types/chrome-apps/web-apis.d.ts deleted file mode 100644 index 0ecd3793a7..0000000000 --- a/types/chrome-apps/web-apis.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Type definitions for Chrome packaged application development -// Project: http://developer.chrome.com/apps/ -// Definitions by: Nikolai Ommundsen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -///////////////////////// -// WEB APIs & Warnings // -///////////////////////// -/** - * Only warnings since: - * 1. It's not possible as of now to override or remove something from *Window* or *Document*. - * 2. It may also cause other unforseen consequences if it's removed (and if it was possible). - * @see[Disallowed] - */ -/** - * Chrome app - Web APIs - * @see[Docs]{@link https://developer.chrome.com/apps/api_other} - */ -interface ChromeWindow { - /// - /// Disabled Web Features - /// https://developer.chrome.com/apps/app_deprecated - /// - - /** - * ❗ alert is not available in packaged apps. ❗ - * Work-around: Use a custom lightbox / popup. - */ - alert(message?: any): void; - /** - * ❗ confirm is not available in packaged apps. ❗ - * Work-around: Use a custom lightbox / popup. - */ - confirm(message?: string): boolean; - - - /** - * ❗ window.localStorage is not available in packaged apps. Use chrome.storage.local instead. ❗ - */ - // localStorage: typeof localStorage; - - - /** - * ❗ window.location is not available in packaged apps. ❗ - * Links open up with the system web browser. - */ - location: Location; - /** - * ❗ window.history is not available in packaged apps. ❗ - * Links open up with the system web browser. - */ - readonly history: History; - - /// - /// Other APIs - /// - AudioContext: typeof AudioContext; -} - -interface Document { - /** - * ❗ document.cookie is not available in packaged apps. ❗ - * Packaged app pages are not rendered on the server, so there is no need to use these. - */ - cookie: string; - /** - * ❗ document.close is not available in packaged apps. ❗ - */ - close(): void; - /** - * ❗ document.open is not available in packaged apps. ❗ - */ - open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** - * ❗ document.write is not available in packaged apps. ❗ - */ - write(...content: string[]): void; -} - -/** - * ❗ iframes are not available in packaged apps, use webviews instead. ❗ - */ -interface HTMLIFrameElement { } - -/** - * ❗ Modal dialogs are not available in packaged apps, use lightbox/popup instead. ❗ - */ -interface HTMLDialogElement { } - -interface HTMLElement { - /** - * @requires Permissions: 'app.window.fullscreen', 'app.window.fullscreen.overrideEsc' - * @description - * In Chrome Apps, fullscreen is entered without prompting the user or providing - * exit instructions. HTML5 fullscreen requires the app.window.fullscreen permission - * in the manifest. In normal webpages, the browser intercepts the ESC key to exit - * pointer lock ensuring a consistent escape method for users. That is also the - * behavior in Chrome Apps unless the app.window.fullscreen.overrideEsc permission - * is used to enable the app to call preventDefault on keydown and keyup events. - * - * Then to exit fullscreen, the document exposes a method for that: - * @example - * document.webkitExitFullscreen(); - */ - webkitRequestFullscreen(): void; -} - -interface HTMLElement { - /** - * ❗ Unprefixed version are not available as of Chrome 68, in Chrome apps ❗ - */ - requestFullscreen(): void; - /** - * ❗ Unprefixed version are not available as of Chrome 68, in Chrome apps ❗ - */ - exitrequestFullscreen(): void; - /** - * @requires Permissions: 'pointerLock' - */ - requestPointerLock(): void; - /** - * @requires Permissions: 'pointerLock' - */ - exitPointerLock(): void; -} - -interface Navigator { - /** - * If you provide the 'geolocation' in your Chrome app it will allow the app to - * use the proposed HTML5 geolocation API without prompting the user for permission. - * @see Permissions: 'geolocation' - */ - readonly geolocation: Geolocation; -} diff --git a/types/chrome-apps/webview.d.ts b/types/chrome-apps/webview.d.ts deleted file mode 100644 index c23eefe17d..0000000000 --- a/types/chrome-apps/webview.d.ts +++ /dev/null @@ -1,1562 +0,0 @@ -// Type definitions for Chrome packaged application development -// Project: http://developer.chrome.com/apps/ -// 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.8 - -///////////////// -// 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. - */ - -declare class HTMLWebViewElement extends HTMLElement { - /** - * 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' | boolean; - - /** 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; - - /** - * Object reference which can be used to post messages into the guest page. - */ - contentWindow: WebView.ContentWindow; - - /** This sets the guest content's window.name object.**/ - name: 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. - * 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; - - /** Interface which provides access to webRequest events on the guest page. */ - request: WebView.WebRequestEventInterface; - - /** - * 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. - * The src attribute cannot be cleared or removed once it has been set, unless the webview is removed from the DOM. - * The src attribute can also accept data URLs, such as 'data:text/plain,Hello, world!'. - */ - src: string; - - /** Create a new element */ - constructor (); - - /** - * Queries audio state. - * @since Chrome 62. - **/ - getAudioState(callback: (audible: boolean) => void): void; - - /** - * Sets audio mute state of the webview. - * @param mute Mute audio value - * @since Chrome 62. - */ - setAudioMuted(mute: boolean): void; - - /** - * Queries whether audio is muted. - * @since Chrome 62. - */ - isAudioMuted(callback: (muted: boolean) => void): void; - - /** - * Captures the visible region of the webview. - * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. - * May be assigned to the 'src' property of an HTML Image element for display. - * @since Chrome 50. - */ - captureVisibleRegion(callback: (dataUrl: string) => void): void; - /** - * Captures the visible region of the webview. - * @param options Extension type - * @param callback Provides a data URL which encodes an image of the visible area of the captured webview. - * May be assigned to the 'src' property of an HTML Image element for display. - * @since Chrome 50. - */ - captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; - - /** - * Adds content script injection rules to the webview. - * When the webview navigates to a page matching one or more rules, the associated scripts will be injected. - * You can programmatically add rules or update existing rules. - * The following example adds two rules to the webview: 'myRule' and 'anotherRule'. - * @example - * webview.addContentScripts([ - * { - * name: 'myRule', - * matches: ['http://www.foo.com/*'], - * css: { files: ['mystyles.css'] }, - * js: { files: ['jquery.js', 'myscript.js'] }, - * run_at: 'document_start' - * }, - * { - * name: 'anotherRule', - * matches: ['http://www.bar.com/*'], - * js: { code: 'document.body.style.backgroundColor = 'red';' }, - * run_at: 'document_end' - * }]); - * ... - * // Navigates webview. - * webview.src = 'http://www.foo.com'; - * - * @description - * You can defer addContentScripts call until you needs to inject scripts. - * The following example shows how to overwrite an existing rule. - * @example - * webview.addContentScripts([{ - * name: 'rule', - * matches: ['http://www.foo.com/*'], - * js: { files: ['scriptA.js'] }, - * run_at: 'document_start'}]); - * - * // Do something. - * webview.src = 'http://www.foo.com/*'; - * ... - * // Overwrite 'rule' defined before. - * webview.addContentScripts([{ - * name: 'rule', - * matches: ['http://www.bar.com/*'], - * js: { files: ['scriptB.js'] }, - * run_at: 'document_end'}]); - * @description - * If webview has been naviagted to the origin (e.g., foo.com) and - * calls webview.addContentScripts to add 'myRule', - * you need to wait for next navigation to make the scripts injected. - * If you want immediate injection, executeScript will do the right thing. - * Rules are preserved even if the guest process crashes - * or is killed or even if the webview is reparented. - * Refer to the /extensions/content_scripts documentation for more details. - * @param contentScriptList Details of the content scripts to add. - * @since Chrome 44. - */ - addContentScripts(contentScriptList: WebView.ContentScriptDetails[]): void; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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 Called after the data has been successfully cleared. - * @since Chrome 33. - */ - clearData(options: WebView.ClearDataOptions, types: WebView.ClearDataTypeSet, callback?: () => void): void; - - /** - * 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] Called after all the JavaScript has been executed. - */ - executeScript(details: WebView.InjectDetails, callback?: (result?: any[]) => void): void; - - /** - * Initiates a find-in-page request. - * @param searchText The string to find in the page. - * @param [options] Options for the find request. - * @param [callback] Called after all find results have been returned for this find request. - * Provides optionally: - * results: Contains all of the results of the find request. - * results can be omitted if it is not utilized in the callback function body; - * e.g. if the callback is only used to discern when the find request has completed. - */ - find(searchText: string, options?: WebView.FindOptions, callback?: (results?: WebView.FindCallbackResults) => void): void; - - /** - * Navigates forward one history entry if possible. Equivalent to go(1). - * @param [callback] Called after the navigation has either failed or completed successfully. - * Provides *success* which indicates whether the navigation was successful. - */ - forward(callback?: (success: boolean) => void): void; - - /** - * 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(): chrome.integer; - - /** - * Returns the user agent string used by the webview for guest page requests. - * @since Chrome 33. - */ - getUserAgent(): string; - - /** - * Gets the current zoom factor. - * @param callback Called after the current zoom factor is retrieved. Provides the current zoom factor. - * @since Chrome 36. - */ - getZoom(callback: (zoomFactor: chrome.double) => void): void; - - /** - * Gets the current zoom mode. - * @param callback Called with the webview's current zoom mode. - * @since Chrome 43. - */ - getZoomMode(callback: (ZoomMode: WebView.ZoomMode) => void): void; - - /** - * 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] Called after the navigation has either failed or completed successfully. - * Provides a boolean, *success*, which indicates whether the navigation was successful. - */ - go(relativeIndex: chrome.integer, callback?: (success: boolean) => void): void; - - /** - * Injects CSS into the guest page. - * @param details Details of the CSS to insert. - * @param callback Called after the CSS has been inserted. - */ - insertCSS(details: WebView.InjectDetails, callback?: () => void): void; - - /** - * Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. - * @since Chrome 33. - */ - isUserAgentOverridden(): void; - - /** - * Prints the contents of the webview. - * This is equivalent to calling scripted print function from the webview itself. - * @since Chrome 38. - */ - print(): void; - - /** Reloads the current top-level page. */ - reload(): void; - - /** - * 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(); - * @param 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. - * @since Chrome 44. - */ - removeContentScripts(scriptNameList?: string[]): void; - - /** Set an attribute */ - setAttribute(attributeName: string, value: string | number | boolean): void; - - /** - * Override the user agent string used by the webview for guest page requests. - * @param userAgent The user agent string to use. - * @since Chrome 33. - */ - setUserAgentOverride(userAgent: string): void; - - /** - * 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] Called after the page has been zoomed. - * @since Chrome 36. - */ - setZoom(zoomFactor: chrome.double, callback?: () => void): void; - - /** - * Sets the zoom mode of the webview. - * @param ZoomMode Defines how zooming is handled in the webview. - * @param [callback] Called after the zoom mode has been changed. - * @since Chrome 43. - */ - setZoomMode(ZoomMode: WebView.ZoomMode, callback?: () => void): void; - - /** Stops loading the current webview navigation if in progress. */ - stop(): void; - - /** - * Ends the current find session (clearing all highlighting) - * and cancels all find requests in progress. - * @param 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. - * @since Chrome 35. - */ - stopFinding(action?: 'clear' | 'keep' | 'activate'): void; - - /** - * 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 dataUrl The data URL to load. - * @param baseUrl The base URL that will be used for relative links. - * @param virtualUrl The URL that will be displayed to the user (in the address bar). - * @since Chrome 40. - */ - loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; - - /** - * 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; - - - /// - /// DOM Events - /// - /** On close event */ - onclose: ((this: HTMLWebViewElement, ev: WebView.Events.CloseEvent) => any) | null; - - /** Fired when the guest window logs a console message. */ - onconsolemessage: ((this: HTMLWebViewElement, ev: WebView.Events.ConsoleMessageEvent) => any) | null; - /** - * 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. - */ - oncontentload: ((this: HTMLWebViewElement, ev: WebView.Events.ContentLoadEvent) => any) | null; - /** - * 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.) - */ - ondialog: ((this: HTMLWebViewElement, ev: WebView.Events.DialogEvent) => any) | null; - /** - * Fired when the process rendering the guest web content has exited. - */ - onexit: ((this: HTMLWebViewElement, ev: WebView.Events.ExitEvent) => any) | null; - /** - * 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. - */ - onfindupdate: ((this: HTMLWebViewElement, ev: WebView.Events.FindUpdateEvent) => any) | null; - /** - * 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'. - */ - onloadabort: ((this: HTMLWebViewElement, ev: WebView.Events.LoadAbortEvent) => any) | null; - /** - * 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. - */ - onloadcommit: ((this: HTMLWebViewElement, ev: WebView.Events.LoadCommitEvent) => any) | null; - /** - * Fired when a top-level load request has redirected to a different URL. - */ - onloadredirect: ((this: HTMLWebViewElement, ev: WebView.Events.LoadRedirectEvent) => any) | null; - /** - * 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. - */ - onloadstop: ((this: HTMLWebViewElement, ev: WebView.Events.LoadStopEvent) => any) | null; - /** - * Fired when the guest page attempts to open a new browser window. - */ - onnewwwindow: ((this: HTMLWebViewElement, ev: WebView.Events.NewWindowEvent) => any) | null; - /** - * Fired when the guest page needs to request special permission from the embedder. - */ - onpermissionrequest: ((this: HTMLWebViewElement, ev: WebView.Events.PermissionRequestEvent) => any) | null; - /** - * Fired when the process rendering the guest web content has become responsive again after being unresponsive. - */ - onresponsive: ((this: HTMLWebViewElement, ev: WebView.Events.ResponsiveEvent) => any) | null; - /** - * @requires autosize: enabled - * Fired when the embedded web content has been resized via autosize. - * Only fires if autosize is enabled. - */ - onsizechanged: ((this: HTMLWebViewElement, ev: WebView.Events.SizeChangedEvent) => any) | null; - /** - * 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. - */ - onunresponsive: ((this: HTMLWebViewElement, ev: WebView.Events.UnresponsiveEvent) => any) | null - /** - * Fired when the page's zoom changes. - */ - onzoomchange: ((this: HTMLWebViewElement, ev: WebView.Events.ZoomChangeEvent) => any) | null; - - - addEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLElement, ev: WebView.Events.WebViewElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - - /// - /// STYLE - /// - - /** Maximum height */ - maxheight: number; - /** Minimum height */ - minheight: number; - /** Maximum width */ - maxwidth: number; - /** Minimum width */ - minwidth: number; - /** - * Allow scaling? - * @default false - */ - allowscaling?: boolean; -} -///////////// -// WEBVIEW // -///////////// -/** - * WebView Events, Methods and interfaces. - */ -declare namespace WebView { - /** - * WebView Events are different from Chrome Events, they extend the normal DOM Events. - */ - namespace Events { - interface WebViewElementEventMap extends HTMLElementEventMap { - 'close': CloseEvent, - 'consolemessage': ConsoleMessageEvent, - 'contentload': ContentLoadEvent, - 'dialog': DialogEvent, - 'exit': ExitEvent, - 'findupdate': FindUpdateEvent, - 'loadabort': LoadAbortEvent, - 'loadcommit': LoadCommitEvent, - 'loadredirect': LoadRedirectEvent, - 'loadstart': LoadStartEvent, - 'loadstop': LoadStopEvent, - 'newwindow': NewWindowEvent, - 'permissionrequest': PermissionRequestEvent, - 'responsive': ResponsiveEvent, - 'sizechanged': SizeChangedEvent, - 'unresponsive': UnresponsiveEvent, - 'zoomchange': ZoomChangeEvent - } - - /** - * 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. - */ - interface CloseEvent extends Event { } - - type ConsoleMessageLevel = -1 | 0 | 1 | 2; - - /** - * 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. - */ - interface ConsoleMessageEvent extends Event { - /** - * 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; - /** The logged message contents. */ - message: string; - /** The line number of the message source. */ - line: chrome.integer; - /** A string identifying the resource which logged the message. */ - sourceId: string; - } - - /** - * 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'' }) - * }); - */ - interface ContentLoadEvent extends Event { } - - /** - * 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. - */ - 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'; - - /** - * The type of modal dialog requested by the guest. - */ - type DialogMessageType = - 'alert' | - 'confirm' | - 'prompt'; - /** - * 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. - */ - interface DialogEvent extends Event { - /** - * The type of modal dialog requested by the guest. - */ - messageType: DialogMessageType; - /** - * The text the guest attempted to display in the modal dialog. - */ - messageText: string; - /** - * An interface that can be used to respond to the guest's modal request. - */ - dialog: DialogController; - } - - /** - * String indicating the reason for the exit. - */ - type ExitEventReason = - 'normal' | - 'abnormal' | - 'crash' | - 'kill'; - - /** - * Fired when the process rendering the guest web content has exited. - */ - interface ExitEvent extends Event { - /** Chrome's internal ID of the process that exited. */ - processID: chrome.integer; - /** String indicating the reason for the exit. */ - reason: ExitEventReason; - } - - /** - * 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. - */ - interface FindUpdateEvent extends Event { - /** - * The string that is being searched for in the page. - */ - searchText: string; - /** - * The number of matches found for searchText on the page so far. - */ - numberOfMatches: chrome.integer; - /** - * The ordinal number of the current active match, - * if it has been found. This will be 0 until then. - */ - activeMatchOrdinal: chrome.integer; - /** - * Describes a rectangle around the active match, - * if it has been found, in screen coordinates. - */ - selectionRect: SelectionRect; - /** - * Indicates whether the find request was canceled. - */ - canceled: boolean; - /** - * Indicates that all find requests have completed - * and that no more findupdate events will be fired - * until more find requests are made. - */ - finalUpdate: string; - } - - /** - * 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'. - */ - interface LoadAbortEvent extends Event { - /** Requested URL. */ - url: string; - /** Whether the load was top-level or in a subframe. */ - isTopLevel: boolean; - /** - * Unique chrome.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 chrome.integer. - */ - code: chrome.integer; - /** - * 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: LoadAbortReason; - } - - /** - * 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. - */ - interface LoadCommitEvent extends Event { - /** The URL that committed. */ - url: string; - /** Whether the load is top-level or in a subframe. */ - isTopLevel: boolean; - } - - /** - * Fired when a top-level load request has redirected to a different URL. - */ - interface LoadRedirectEvent { - /** 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; - } - /** - * Fired when a load has begun. - */ - interface LoadStartEvent extends Event { - /** Requested URL. */ - url: string; - /** Whether the load is top-level or in a subframe. */ - isTopLevel: boolean; - } - - /** - * 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. - */ - interface LoadStopEvent extends Event { } - - /** The requested disposition of the new window. */ - type WindowOpenDisposition = - 'ignore' | - 'save_to_disk' | - 'current_tab' | - 'new_background_tab' | - 'new_foreground_tab' | - 'new_window' | - 'new_popup'; - - /** - * 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); - * }); - */ - interface NewWindowEvent extends Event { - /** - * 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; - - /** The target URL requested for the new window. */ - targetUrl: string; - - /** The initial width requested for the new window. */ - initialWidth: chrome.integer; - - /** The initial height requested for the new window. */ - initialHeight: chrome.integer; - - /** The requested name of the new window. */ - name: string; - - /** The requested disposition of the new window. */ - windowOpenDisposition: WindowOpenDisposition; - } - - type RequestedPermission = - 'media' | - 'geolocation' | - 'pointerLock' | - 'download' | - 'loadplugin' | - 'filesystem' | - 'fullscreen'; - - /** - * @requires `Permissions:` `audioCapture` and/or `videoCapture` - * @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: - * - * @example - * webview.addEventListener('permissionrequest', (e) => { if (e.permission === 'media') e.request.allow(); }); - */ - interface PermissionRequestEvent extends Event { - /** The type of permission being requested. */ - permission: RequestedPermission; - /** An object which holds details of the requested permission.*/ - request: PermissionRequestHandler; - } - - /** - * 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', () => { - * webview.style.opacity = '0.5'; - * }); - * webview.addEventListener('responsive', () => { - * webview.style.opacity = '1'; - * }); - */ - interface ResponsiveEvent extends Event { - /** Chrome's internal ID of the process that became responsive. */ - processID: chrome.integer; - } - - /** - * Fired when the embedded web content has been resized via autosize. - * Only fires if autosize is enabled. - */ - interface SizeChangedEvent extends Event { - /** Old width of embedded web content. */ - oldWidth: chrome.integer; - /** Old height of embedded web content. */ - oldHeight: chrome.integer; - /** New width of embedded web content. */ - newWidth: chrome.integer; - /** New height of embedded web content. */ - newHeight: chrome.integer; - } - - /** - * 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. - */ - interface UnresponsiveEvent extends Event { - /** Chrome's internal ID of the process that has become unresponsive. */ - processID: chrome.integer; - } - - /** Fired when the page's zoom changes. */ - interface ZoomChangeEvent extends Event { - /** The page's previous zoom factor. */ - oldzoomFactor: chrome.double; - /** The new zoom factor that the page was zoomed to. */ - newzoomFactor: chrome.double; - } - - } - - /** 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). - * @default 0 - */ - since?: chrome.integer; - } - - - /** - * 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 { - /** - * 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, - /** - * JavaScript or CSS file to inject. - */ - file?: string - } - - /** - * WebView element from html - */ - - - /** A set of data types. Missing properties are interpreted as false. */ - interface ClearDataTypeSet { - /** Websites' appcaches. */ - appcache?: boolean; - /** - * The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. - * @since Chrome 43. - */ - 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. - **/ - 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 { - /** - * 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; - - /** JavaScript or CSS file to inject. */ - file?: string; - } - /** The type of injection item: code or a set of files. */ - interface InjectionItems { - /** JavaScript code or CSS to be injected into matching pages. */ - code?: string; - /** - * 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. **/ - interface ContentScriptDetails { - /** The name of the content script to inject. */ - name: string; - - /** Specifies which pages this content script will be injected into. */ - matches: string[]; - - /** Excludes pages that this content script would otherwise be injected into. */ - exclude_matches?: string[]; - - /** JavaScript code or CSS to be injected into matching pages. */ - code?: string; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * The soonest that the JavaScript or CSS will be injected into the tab. - * Defaults to 'document_idle'. - */ - run_at?: chrome.extensionTypes.RunAt; - - /** - * 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; - - /** - * Applied after matches to include only those URLs that also match this glob. - * Intended to emulate the @include Greasemonkey keyword. - */ - include_globs?: string[]; - - /** - * Applied after matches to exclude URLs that match this glob. - * Intended to emulate the @exclude Greasemonkey keyword. - */ - exclude_globs?: string[]; - } - interface ContextMenuCreateProperties { - - /** - * The type of menu item. Defaults to 'normal' if not specified. - */ - type?: chrome.ToStringLiteral; - - /** - * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. - */ - 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?: any[]; - - /** - * A function that will be called back when the menu item is clicked. - */ - onclick?: (info: any) => void - - /** - * The ID of a parent menu item; this makes the item a child of a previously added item. - */ - parentId?: chrome.integer | 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?: any[]; - - /** - * 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[]; - - /** - * Whether this context menu item is enabled or disabled. Defaults to true. - */ - enabled?: boolean; - } - interface ContextMenuUpdateProperties { - /** The type of menu item. */ - type?: WebView.ContextType; - - /** The text to be displayed in the item */ - title?: string; - - /** - * 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; - - /** - * List of contexts this menu item will appear in. - */ - contexts?: any[]; - - /** - * A function that will be called back when the menu item is clicked. - * @param callback - */ - onclick?: (info: any) => void; - - /** - * 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?: chrome.integer | 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.) - */ - documentUrlPatterns?: any[]; - - /** - * 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[]; - - /** - * Whether this context menu item is enabled or disabled. - */ - enabled?: boolean; - } - interface OnShowEvent { - /** Call this to prevent showing the context menu. */ - preventDefault: () => void; - } - interface ContextMenus { - /** - * 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; - - /** - * 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: chrome.integer | string, updateProperties: object, callback?: () => void): void; - - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param [callback] - */ - remove(menuItemId: chrome.integer | string, callback?: () => void): void; - - /** - * Removes all context menu items added to this webview. - * @param [callback] - */ - removeAll(callback?: () => void): void; - - /** - * 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<(event: OnShowEvent) => void>; - } - /** Messaging handle to a guest window. */ - interface ContentWindow { - /** - * 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 attached to dialog DOM events. */ - interface DialogController { - /** - * 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; - /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ - cancel(): void; - } - /** Contains all of the results of the find request. */ - interface FindCallbackResults { - /** The number of times searchText was matched on the page. */ - numberOfMatches: chrome.integer; - /** The ordinal number of the current match. */ - activeMatchOrdinal: chrome.integer; - /** Describes a rectangle around the active match in screen coordinates. */ - selectionRect: SelectionRect; - /** Indicates whether this find request was canceled. */ - canceled: boolean; - } - interface FindOptions { - /** - * Flag to find matches in reverse order. - * @default false - */ - backward?: boolean; - /** - * Flag to match with case-sensitivity. - * @default false - */ - matchCase?: boolean; - } - interface NewWindow { - /** - * 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: HTMLWebViewElement): void; - /** - * Cancel the new window request. - */ - discard(): void; - } - interface PermissionRequestHandler { - /** Allow the permission request. */ - allow(): void; - /** Deny the permission request. This is the default behavior if allow is not called. */ - deny(): void; - } - /** - * 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 { - /** Distance from the left edge of the screen to the left edge of the rectangle. */ - left: chrome.integer; - /** Distance from the top edge of the screen to the top edge of the rectangle. */ - top: chrome.integer; - /** Width of the rectangle. */ - width: chrome.integer; - /** Height of the rectangle. */ - height: chrome.integer; - } - - /** An HTTP Header, represented as an object containing a key and either a value or a binaryValue. */ - interface HttpHeader { - name: string; - value?: string; - binaryValue?: ArrayBuffer; - } - - interface ResourceRequest { - url: string; - /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ - requestId: string; - /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ - frameId: chrome.integer; - /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ - parentFrameId: chrome.integer; - /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ - tabId: chrome.integer; - /** - * How the requested resource will be used. - */ - type: chrome.webRequest.ResourceType; - /** The time when this signal is triggered, in milliseconds since the epoch. */ - timeStamp: chrome.double; - /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. - * @since Chrome 63. - */ - initiator?: string; - } - - interface WebRequestDetails extends ResourceRequest { - /** Standard HTTP method. */ - method: string; - } - - interface WebRequestHeadersDetails extends WebRequestDetails { - /** Optional. The HTTP request headers that are going to be sent out with this request. */ - requestHeaders?: HttpHeader[]; - } - - interface WebRequestBodyDetails extends WebRequestDetails { - /** - * Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'. - * @since Chrome 23. - */ - requestBody: WebRequestBody; - } - - /** - * Contains data uploaded in a URL request. - * @since Chrome 23. - */ - interface UploadData { - /** Optional. An ArrayBuffer with a copy of the data. */ - bytes?: ArrayBuffer; - /** Optional. A string with the file's path and name. */ - file?: string; - } - - interface WebRequestBody { - /** Optional. Errors when obtaining request body data. */ - error?: string; - /** - * Optional. - * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. - */ - formData?: { [key: string]: string[] }; - /** - * Optional. - * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. - */ - raw?: UploadData[]; - } - - interface WebRequestFullDetails extends WebRequestHeadersDetails, WebRequestBodyDetails { - } - - interface WebResponseDetails extends ResourceRequest { - /** HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line). */ - statusLine: string; - /** - * Standard HTTP status code returned by the server. - * @since Chrome 43. - */ - statusCode: chrome.integer; - } - - interface WebResponseHeadersDetails extends WebResponseDetails { - /** Optional. The HTTP response headers that have been received with this response. */ - responseHeaders?: HttpHeader[]; - /** standard HTTP method i.e. GET, POST, PUT, etc. */ - method: string; - } - - interface WebResponseCacheDetails extends WebResponseHeadersDetails { - /** - * Optional. - * The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address. - */ - ip?: string; - /** Indicates if this response was fetched from disk cache. */ - fromCache: boolean; - } - - interface WebRedirectionResponseDetails extends WebResponseCacheDetails { - /** The new URL. */ - redirectUrl: string; - } - - /** An object describing filters to apply to webRequest events. */ - interface RequestFilter { - /** Optional. */ - tabId?: chrome.integer; - /** - * A list of request types. Requests that cannot match any of the types will be filtered out. - */ - types?: chrome.webRequest.ResourceType[]; - /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ - urls: string[]; - - /** Optional. */ - windowId?: chrome.integer; - } - - interface AuthCredentials { - username: string; - password: string; - } - - /** Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests. */ - interface BlockingResponse { - /** - * If true, the request is cancelled. - * Used in onBeforeRequest, this prevents the request from being sent. */ - cancel?: boolean; - /** - * Only used as a response to the onBeforeRequest and onHeadersReceived events. - * If set, the original request is prevented from being sent/completed and is - * instead redirected to the given URL. Redirections to non-HTTP schemes such - * as data: are allowed. Redirects initiated by a redirect action use the - * original request method for the redirect, with one exception: If the - * redirect is initiated at the onHeadersReceived stage, then the redirect - * will be issued using the GET method. - */ - redirectUrl?: string; - /** - * Only used as a response to the onHeadersReceived event. - * If set, the server is assumed to have responded with these - * response headers instead. Only return responseHeaders if you really - * want to modify the headers in order to limit the number of conflicts - * (only one extension may modify responseHeaders for each request). - */ - responseHeaders?: HttpHeader[]; - /** - * Only used as a response to the onAuthRequired event. - * If set, the request is made using the supplied credentials. - */ - authCredentials?: AuthCredentials; - /** - * Only used as a response to the onBeforeSendHeaders event. - * If set, the request is made with these request headers instead. - */ - requestHeaders?: HttpHeader[]; - } - - interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { - /** The authentication scheme, e.g. Basic or Digest. */ - scheme: string; - /** The authentication realm provided by the server, if there is one. */ - realm?: string; - /** The server requesting authentication. */ - challenger: WebAuthChallenger; - /** True for Proxy-Authenticate, false for WWW-Authenticate. */ - isProxy: boolean; - } - - interface WebRequestBodyEvent extends chrome.events.Event<(details: WebRequestBodyDetails) => void> { - addListener(callback: (details: WebRequestBodyDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebRequestHeadersEvent extends chrome.events.Event<(details: WebRequestHeadersDetails) => void> { - addListener(callback: (details: WebRequestHeadersDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface _WebResponseHeadersEvent extends chrome.events.Event<(details: T) => void> { - addListener(callback: (details: T) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebResponseHeadersEvent extends _WebResponseHeadersEvent { } - - interface WebResponseCacheEvent extends _WebResponseHeadersEvent { } - - interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent { } - - interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { - addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; - } - - interface WebResponseErrorEvent extends _WebResponseHeadersEvent { } - - interface WebResponseErrorDetails extends WebResponseCacheDetails { - /** The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. */ - error: string; - } - - interface WebAuthChallenger { - host: string; - port: chrome.integer; - } - - /** - * 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 { - /** Fired when a request is about to occur. */ - onBeforeRequest: WebRequestBodyEvent; - /** - * Fired before sending an HTTP request, once the request headers are available. - * This may occur after a TCP connection is made to the server, but before any HTTP data is sent. - */ - onBeforeSendHeaders: WebRequestHeadersEvent; - /** - * Fired just before a request is going to be sent to the server - * (modifications of previous onBeforeSendHeaders callbacks - * are visible by the time onSendHeaders is fired). - */ - onSendHeaders: WebRequestHeadersEvent; - /** Fired when HTTP response headers of a request have been received. */ - onHeadersReceived: WebResponseHeadersEvent; - /** - * Fired when an authentication failure is received. - * The listener has three options: it can provide authentication credentials, - * it can cancel the request and display the error page, or it can take no - * action on the challenge. If bad user credentials are provided, this may be - * called multiple times for the same request. - */ - onAuthRequired: WebAuthenticationChallengeEvent; - /** - * Fired when the first byte of the response body is received. - * For HTTP requests, this means that the status line and - * response headers are available. - */ - onResponseStarted: WebResponseCacheEvent; - /** Fired when a server-initiated redirect is about to occur. */ - onBeforeRedirect: WebRedirectionResponseEvent; - /** Fired when a request is completed. */ - onCompleted: WebResponseCacheEvent; - /** Fired when an error occurs. */ - onErrorOccured: WebResponseErrorEvent; - /** - * Provides the Declarative Event API consisting of addRules, removeRules, and getRules. - * This interface supports declarative webRequest rules through - * **onRequest** and **onMessage** events. - * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} - */ - onRequest: chrome.webViewRequest.OnRequestEvent; - /** - * This interface supports declarative webRequest rules through - * **onRequest** and **onMessage** events. - * @see[See declarativeWebRequest for API details.]{@link http://developer.chrome.com/extensions/declarativeWebRequest.html} - */ - onMessage: chrome.webViewRequest.OnMessageEvent; - } - /** - * 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. - * '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). - * 'disabled' - * > 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'; -} - -declare interface Document { - createElement(element: 'webview'): HTMLWebViewElement; -} - -declare const WebView: typeof HTMLWebViewElement; From 681c02d749adb67ed8f24ee066ca79a99c7467f0 Mon Sep 17 00:00:00 2001 From: zamu87 Date: Tue, 28 Aug 2018 13:23:40 +0200 Subject: [PATCH 251/289] correct tls Server options --- types/hapi/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 3d3b69b959..b152d34e5b 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -2904,7 +2904,7 @@ export interface ServerOptions { * Default value: none. * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. */ - tls?: boolean | https.RequestOptions; + tls?: boolean | https.ServerOptions; /** * Default value: constructed from runtime server information. From 8884e18dc9096f1c00b085d60b93c4ebc795c4aa Mon Sep 17 00:00:00 2001 From: MaximeAnsquer Date: Tue, 28 Aug 2018 13:34:35 +0200 Subject: [PATCH 252/289] StompJS: Fix errorCallback signature (again) --- types/stompjs/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/stompjs/index.d.ts b/types/stompjs/index.d.ts index 4a6237ea81..7540f58e7e 100644 --- a/types/stompjs/index.d.ts +++ b/types/stompjs/index.d.ts @@ -26,9 +26,9 @@ export class Client { debug(...args: string[]): any; - connect(headers: { login: string, passcode: string, host?: string }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame) => any): any; - connect(headers: { }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame) => any): any; - connect(login: string, passcode: string, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame) => any, host?: string): any; + connect(headers: { login: string, passcode: string, host?: string }, connectCallback: (frame?: Frame | string) => any, errorCallback?: (error: Frame) => any): any; + connect(headers: { }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any; + connect(login: string, passcode: string, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any, host?: string): any; disconnect(disconnectCallback: () => any, headers?: {}): any; send(destination: string, headers?: {}, body?: string): any; From e3b85004853b352988d4790b87f67cfde0248dcc Mon Sep 17 00:00:00 2001 From: MaximeAnsquer Date: Tue, 28 Aug 2018 13:42:10 +0200 Subject: [PATCH 253/289] StompJS: Fix errorCallback and connectCallback --- types/stompjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/stompjs/index.d.ts b/types/stompjs/index.d.ts index 7540f58e7e..ced22109d3 100644 --- a/types/stompjs/index.d.ts +++ b/types/stompjs/index.d.ts @@ -26,7 +26,7 @@ export class Client { debug(...args: string[]): any; - connect(headers: { login: string, passcode: string, host?: string }, connectCallback: (frame?: Frame | string) => any, errorCallback?: (error: Frame) => any): any; + connect(headers: { login: string, passcode: string, host?: string }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any; connect(headers: { }, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any): any; connect(login: string, passcode: string, connectCallback: (frame?: Frame) => any, errorCallback?: (error: Frame | string) => any, host?: string): any; disconnect(disconnectCallback: () => any, headers?: {}): any; From 28b7cee0236dbdf9a6056bc2b693bfcf2241c1fa Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Tue, 28 Aug 2018 13:52:21 +0200 Subject: [PATCH 254/289] jss: Remove noisy comments and display public api only --- types/jss/index.d.ts | 3 --- types/jss/jss-tests.ts | 3 --- 2 files changed, 6 deletions(-) diff --git a/types/jss/index.d.ts b/types/jss/index.d.ts index b19b82ab0e..c8e0f13c6c 100644 --- a/types/jss/index.d.ts +++ b/types/jss/index.d.ts @@ -138,9 +138,6 @@ export declare class JSS { * Creates a new instance of JSS. */ export function create(options?: Partial): JSS; -/** - * Creates a GenerateClassName function - */ export function createGenerateClassName(): GenerateClassName; declare const sharedInstance: JSS; /** diff --git a/types/jss/jss-tests.ts b/types/jss/jss-tests.ts index 8822264282..4c7fcc9270 100644 --- a/types/jss/jss-tests.ts +++ b/types/jss/jss-tests.ts @@ -47,9 +47,6 @@ const rule = attachedStyleSheet.addRule('dynamicRule', { color: 'indigo' }); rule.prop('border-radius', 5).prop('color'); // $ExpectType string attachedStyleSheet.classes.dynamicRule; // $ExpectType string -const generateClassName = createGenerateClassName(); -const dynamicRuleClassName = generateClassName(rule, attachedStyleSheet); - attachedStyleSheet.deleteRule('dynamicRule'); // test that `addRule` supports the shorthand signature From 3a620f7ff7e165a4af5383441f80ccb8e202eadc Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 28 Aug 2018 15:39:26 +0300 Subject: [PATCH 255/289] definitions for hat --- types/hat/hat-tests.ts | 10 ++++++++++ types/hat/index.d.ts | 28 ++++++++++++++++++++++++++++ types/hat/tsconfig.json | 23 +++++++++++++++++++++++ types/hat/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/hat/hat-tests.ts create mode 100644 types/hat/index.d.ts create mode 100644 types/hat/tsconfig.json create mode 100644 types/hat/tslint.json diff --git a/types/hat/hat-tests.ts b/types/hat/hat-tests.ts new file mode 100644 index 0000000000..1b91702742 --- /dev/null +++ b/types/hat/hat-tests.ts @@ -0,0 +1,10 @@ +import * as hat from 'hat'; + +const randomId = hat(); + +const rack = hat.rack(); +rack('car'); +const tractorId = rack('tractor'); +rack.get(tractorId); +rack.set(randomId, 'bicycle'); +rack.hats; diff --git a/types/hat/index.d.ts b/types/hat/index.d.ts new file mode 100644 index 0000000000..58a7bdc983 --- /dev/null +++ b/types/hat/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for hat 0.0 +// Project: https://github.com/substack/node-hat +// Definitions by: Sasha Grin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface HatsList { + [key: string]: any; +} + +interface Rack { + bits: number; + base: number; + hats: HatsList; + + (data: any): string; + get(id: string): any; + set(id: string, value: any): Rack; +} + +type CreateRack = (bits?: number, base?: number, expandBy?: number) => Rack; + +interface Hat { + (bits?: number, base?: number): string; + rack: CreateRack; +} + +declare const hat: Hat; +export = hat; diff --git a/types/hat/tsconfig.json b/types/hat/tsconfig.json new file mode 100644 index 0000000000..c13e03fd48 --- /dev/null +++ b/types/hat/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hat-tests.ts" + ] +} diff --git a/types/hat/tslint.json b/types/hat/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hat/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f316ca3d151d30d39c4b5c5eb2f8541bd580071b Mon Sep 17 00:00:00 2001 From: Ivan Sieder - SiMedia Date: Tue, 28 Aug 2018 15:37:31 +0200 Subject: [PATCH 256/289] added gamedig typings --- types/gamedig/gamedig-tests.ts | 18 +++ types/gamedig/index.d.ts | 285 +++++++++++++++++++++++++++++++++ types/gamedig/tsconfig.json | 24 +++ types/gamedig/tslint.json | 1 + 4 files changed, 328 insertions(+) create mode 100644 types/gamedig/gamedig-tests.ts create mode 100644 types/gamedig/index.d.ts create mode 100644 types/gamedig/tsconfig.json create mode 100644 types/gamedig/tslint.json diff --git a/types/gamedig/gamedig-tests.ts b/types/gamedig/gamedig-tests.ts new file mode 100644 index 0000000000..3af9334b70 --- /dev/null +++ b/types/gamedig/gamedig-tests.ts @@ -0,0 +1,18 @@ +import Gamedig = require("gamedig"); + +Gamedig.query({ + type: "tf2", + host: "127.0.0.1" +}, (error, state) => { + if (error) throw error(); + + const { + name, + map, + password, + maxplayers, + players, + bots, + notes + } = state; +}); diff --git a/types/gamedig/index.d.ts b/types/gamedig/index.d.ts new file mode 100644 index 0000000000..a2ccf75de9 --- /dev/null +++ b/types/gamedig/index.d.ts @@ -0,0 +1,285 @@ +// Type definitions for Gamedig 1.0 +// Project: https://github.com/sonicsnes/node-gamedig +// Definitions by: Ivan Sieder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export type Type = + "7d2d" + | "ageofchivalry" + | "aoe2" + | "alienarena" + | "alienswarm" + | "arkse" + | "avp2" + | "avp2010" + | "americasarmy" + | "americasarmy2" + | "americasarmy3" + | "americasarmypg" + | "arma" + | "arma2" + | "arma3" + | "armagetron" + | "baldursgate" + | "bat1944" + | "bf1942" + | "bfv" + | "bf2" + | "bf2142" + | "bfbc2" + | "bf3" + | "bf4" + | "bfh" + | "breach" + | "breed" + | "brink" + | "buildandshoot" + | "cod" + | "coduo" + | "cod2" + | "cod3" + | "cod4" + | "codwaw" + | "codmw2" + | "codmw3" + | "callofjuarez" + | "chaser" + | "chrome" + | "codenameeagle" + | "commandos3" + | "cacrenegade" + | "conanexiles" + | "contactjack" + | "cs16" + | "cscz" + | "css" + | "csgo" + | "crossracing" + | "crysis" + | "crysiswars" + | "crysis2" + | "daikatana" + | "dmomam" + | "darkesthour" + | "dayz" + | "dayzmod" + | "deadlydozenpt" + | "dh2005" + | "descent3" + | "deusex" + | "devastation" + | "dinodday" + | "dirttrackracing2" + | "dnl" + | "dod" + | "dods" + | "doi" + | "doom3" + | "dota2" + | "drakan" + | "etqw" + | "fear" + | "f12002" + | "f1c9902" + | "farcry" + | "farcry2" + | "fortressforever" + | "flashpoint" + | "ffow" + | "fivem" + | "garrysmod" + | "graw" + | "graw2" + | "giantscitizenkabuto" + | "globaloperations" + | "geneshift" + | "ges" + | "gore" + | "gunmanchronicles" + | "hldm" + | "hl2dm" + | "halo" + | "halo2" + | "heretic2" + | "hexen2" + | "hidden" + | "had2" + | "homefront" + | "homeworld2" + | "hurtworld" + | "igi2" + | "il2" + | "insurgency" + | "ironstorm" + | "jamesbondnightfire" + | "jc2mp" + | "killingfloor" + | "killingfloor2" + | "kingpin" + | "kisspc" + | "kspdmp" + | "kzmod" + | "left4dead" + | "left4dead2" + | "m2mp" + | "medievalengineers" + | "mohaa" + | "mohpa" + | "mohab" + | "mohsh" + | "mohbt" + | "moh2010" + | "mohwf" + | "minecraft" + | "minecraftpe" + | "minecraftping" + | "mnc" + | "mtavc" + | "mtasa" + | "mumble" + | "mumbleping" + | "mutantfactions" + | "nascarthunder2004" + | "netpanzer" + | "nmrih" + | "ns" + | "ns2" + | "nfshp2" + | "nab" + | "nwn" + | "nwn2" + | "nexuiz" + | "nitrofamily" + | "nolf" + | "nolf2" + | "nucleardawn" + | "openarena" + | "openttd" + | "operationflashpoint" + | "painkiller" + | "postal2" + | "prey" + | "primalcarnage" + | "quake1" + | "quake2" + | "quake3" + | "quake4" + | "ragdollkungfu" + | "r6" + | "r6roguespear" + | "r6ravenshield" + | "rallisportchallenge" + | "rallymasters" + | "redorchestra" + | "redorchestraost" + | "redorchestra2" + | "redline" + | "rtcw" + | "ricochet" + | "riseofnations" + | "rune" + | "rust" + | "samp" + | "spaceengineers" + | "ss" + | "ss2" + | "shatteredhorizon" + | "ship" + | "shogo" + | "shootmania" + | "sin" + | "sinep" + | "soldat" + | "sof" + | "sof2" + | "stalker" + | "stbc" + | "stvef" + | "stvef2" + | "swbf" + | "swbf2" + | "swjk" + | "swjk2" + | "swrc" + | "starbound" + | "starmade" + | "suicidesurvival" + | "swat4" + | "svencoop" + | "synergy" + | "tacticalops" + | "teamfactor" + | "tfc" + | "tf2" + | "teamspeak2" + | "teamspeak3" + | "terminus" + | "terraria" + | "thps3" + | "thps4" + | "thu2" + | "towerunite" + | "trackmania2" + | "trackmaniaforever" + | "tremulous" + | "tribes1" + | "tribesvengeance" + | "tron20" + | "turok2" + | "universalcombat" + | "unreal" + | "unturned" + | "ut" + | "ut2003" + | "ut2004" + | "ut3" + | "urbanterror" + | "v8supercar" + | "ventrilo" + | "vietcong" + | "vietcong2" + | "warsow" + | "wheeloftime" + | "wolfenstein2009" + | "wolfensteinet" + | "xpandrally" + | "zombiemaster" + | "zps"; + +export interface Player { + name?: string; + ping?: number; + score?: number; + team?: string; + address?: string; +} + +export interface QueryOptions { + type: Type; + host: string; + port?: number; + notes?: object; + maxAttempts?: number; + socketTimeout?: number; + attemptTimeout?: number; +} + +export interface QueryResult { + name: string; + map: string; + password: boolean; + maxplayers: number; + players: Player[]; + bots: Player[]; + notes: object; + raw?: object; + query?: object; +} + +export function query( + options: QueryOptions, + callback: (error: any, state: QueryResult) => void +): void; + +export function query(options: QueryOptions): Promise; diff --git a/types/gamedig/tsconfig.json b/types/gamedig/tsconfig.json new file mode 100644 index 0000000000..ae26ece7da --- /dev/null +++ b/types/gamedig/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gamedig-tests.ts" + ] +} diff --git a/types/gamedig/tslint.json b/types/gamedig/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gamedig/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 80b0171ab7eed3a6af84839703ba506bebb6e318 Mon Sep 17 00:00:00 2001 From: Mohamed Kamagate Date: Tue, 28 Aug 2018 08:10:16 -0700 Subject: [PATCH 257/289] Add tolerance parameter to WebHooks.contructEvent --- types/stripe/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 4d8aba7d9a..dcab22ed2f 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -7192,7 +7192,7 @@ declare namespace Stripe { } class WebHooks { - constructEvent(requestBody: any, signature: string | string[], endpointSecret: string): webhooks.StripeWebhookEvent; + constructEvent(requestBody: any, signature: string | string[], endpointSecret: string, tolerance: number): webhooks.StripeWebhookEvent; } class EphemeralKeys { From 9095eefdccfcec3cf0ce671ca05b8046407ecb61 Mon Sep 17 00:00:00 2001 From: Mohamed Kamagate Date: Tue, 28 Aug 2018 08:43:56 -0700 Subject: [PATCH 258/289] Stripe : Make tolerance an optional parameter --- types/stripe/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index dcab22ed2f..06b7fbbb70 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -7192,7 +7192,7 @@ declare namespace Stripe { } class WebHooks { - constructEvent(requestBody: any, signature: string | string[], endpointSecret: string, tolerance: number): webhooks.StripeWebhookEvent; + constructEvent(requestBody: any, signature: string | string[], endpointSecret: string, tolerance?: number): webhooks.StripeWebhookEvent; } class EphemeralKeys { From 38428c149490f6153908941328813e30b856cf13 Mon Sep 17 00:00:00 2001 From: Dmytro Borysov Date: Tue, 28 Aug 2018 18:36:59 +0200 Subject: [PATCH 259/289] fix(hedron): withBreakpoints HOC injects prop --- types/hedron/hedron-tests.tsx | 24 +++++++++++++++++++++++- types/hedron/index.d.ts | 14 ++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/types/hedron/hedron-tests.tsx b/types/hedron/hedron-tests.tsx index 8b2ce82f01..3fe25ddff1 100644 --- a/types/hedron/hedron-tests.tsx +++ b/types/hedron/hedron-tests.tsx @@ -4,7 +4,29 @@ import * as hedron from 'hedron'; - test + + test + ; + +// withBreakpoints test +interface Props { + numeric: number; + str: string; +} + +class ComponentWithBreakpoints extends React.Component { + render() { + // `breakpoints` prop is accessible in component + this.props.breakpoints; + + return null; + } +} + +const WithBreakpoints = hedron.withBreakpoints(ComponentWithBreakpoints); + +// breakpoints props is not needed +; diff --git a/types/hedron/index.d.ts b/types/hedron/index.d.ts index 1e19aaee7a..8ce464c017 100644 --- a/types/hedron/index.d.ts +++ b/types/hedron/index.d.ts @@ -150,8 +150,14 @@ export interface HiddenProps { lg?: boolean; } -export interface BreakpointProviderProps { - breakpoints: { sm?: number; md?: number; lg?: number }; +export interface Breakpoints { + sm?: number; + md?: number; + lg?: number; +} + +export interface BreakpointsProps { + breakpoints: Breakpoints; } export class Column extends React.Component> {} @@ -159,8 +165,8 @@ export class Page extends React.Component> {} export class Hidden extends React.Component> {} export class BreakpointProvider extends React.Component< - BreakpointProviderProps & React.HTMLProps + BreakpointsProps & React.HTMLProps > {} export function withBreakpoints( - wrappedComponent: React.ComponentClass + wrappedComponent: React.ComponentClass ): React.ComponentClass; From 6e9c836e20feda680acae39786b5c004a4d32fd4 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 12:48:20 -0700 Subject: [PATCH 260/289] adds typings for the 'env-paths' package --- types/env-paths/env-paths-tests.ts | 4 ++++ types/env-paths/index.d.ts | 18 ++++++++++++++++++ types/env-paths/tsconfig.json | 19 +++++++++++++++++++ types/env-paths/tslint.json | 3 +++ 4 files changed, 44 insertions(+) create mode 100644 types/env-paths/env-paths-tests.ts create mode 100644 types/env-paths/index.d.ts create mode 100644 types/env-paths/tsconfig.json create mode 100644 types/env-paths/tslint.json diff --git a/types/env-paths/env-paths-tests.ts b/types/env-paths/env-paths-tests.ts new file mode 100644 index 0000000000..b143fb47b5 --- /dev/null +++ b/types/env-paths/env-paths-tests.ts @@ -0,0 +1,4 @@ +import envPaths = require('env-paths'); + +// $ExpectType Paths +envPaths('./'); diff --git a/types/env-paths/index.d.ts b/types/env-paths/index.d.ts new file mode 100644 index 0000000000..c759f3875c --- /dev/null +++ b/types/env-paths/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for env-paths 1.0 +// Project: https://github.com/sindresorhus/env-paths +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = envPaths; + +declare function envPaths(name: string, opts?: { suffix: string; }): envPaths.Paths; + +declare namespace envPaths { + interface Paths { + readonly data: string; + readonly config: string; + readonly cache: string; + readonly log: string; + readonly temp: string; + } +} diff --git a/types/env-paths/tsconfig.json b/types/env-paths/tsconfig.json new file mode 100644 index 0000000000..62dcbca022 --- /dev/null +++ b/types/env-paths/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "env-paths-tests.ts" + ] +} diff --git a/types/env-paths/tslint.json b/types/env-paths/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/env-paths/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From d89146730452089b576a79135f0c02f430a4bba9 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 12:29:44 -0700 Subject: [PATCH 261/289] adds typings for the 'elegant-spinner' package --- .../elegant-spinner/elegant-spinner-tests.ts | 8 ++++++++ types/elegant-spinner/index.d.ts | 12 ++++++++++++ types/elegant-spinner/tsconfig.json | 19 +++++++++++++++++++ types/elegant-spinner/tslint.json | 3 +++ 4 files changed, 42 insertions(+) create mode 100644 types/elegant-spinner/elegant-spinner-tests.ts create mode 100644 types/elegant-spinner/index.d.ts create mode 100644 types/elegant-spinner/tsconfig.json create mode 100644 types/elegant-spinner/tslint.json diff --git a/types/elegant-spinner/elegant-spinner-tests.ts b/types/elegant-spinner/elegant-spinner-tests.ts new file mode 100644 index 0000000000..5d2ddb9dc7 --- /dev/null +++ b/types/elegant-spinner/elegant-spinner-tests.ts @@ -0,0 +1,8 @@ +import elegantSpinner = require('elegant-spinner'); + +const frameFunction = elegantSpinner(); + +// $ExpectType string +frameFunction(); + +const frames = elegantSpinner.frames; diff --git a/types/elegant-spinner/index.d.ts b/types/elegant-spinner/index.d.ts new file mode 100644 index 0000000000..fbb8d4710a --- /dev/null +++ b/types/elegant-spinner/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for elegant-spinner 1.0 +// Project: https://github.com/sindresorhus/elegant-spinner +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = elegantSpinner; + +declare function elegantSpinner(): () => string; + +declare namespace elegantSpinner { + const frames: ReadonlyArray; +} diff --git a/types/elegant-spinner/tsconfig.json b/types/elegant-spinner/tsconfig.json new file mode 100644 index 0000000000..cdd768d4c6 --- /dev/null +++ b/types/elegant-spinner/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "elegant-spinner-tests.ts" + ] +} diff --git a/types/elegant-spinner/tslint.json b/types/elegant-spinner/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/elegant-spinner/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 9b6a1cd6acffe3379a6f79bd859401072668cb7f Mon Sep 17 00:00:00 2001 From: Ricky Kirkham Date: Tue, 28 Aug 2018 13:38:56 -0700 Subject: [PATCH 262/289] fix errors in getAccessTokenAsync doc --- types/office-js/index.d.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 793bbb067c..f3e4bb6fd5 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1132,12 +1132,14 @@ declare namespace Office { asyncContext?: any } /** - * The Office Auth namespace, Office.context.auth, provides a method that allows the Office host to obtain and access the add-in token. - * Indirectly, enable the add-in to access the signed-in user's Microsoft Graph data without requiring the user to sign in a second time. + * The Office Auth namespace, Office.context.auth, provides a method that allows the Office host to obtain an access token to the add-in's web application. + * Indirectly, this also enables the add-in to access the signed-in user's Microsoft Graph data without requiring the user to sign in a second time. + * + * @beta */ interface Auth { /** - * Calls the Azure Active Directory V 2.0 endpoint to get an access token to your add-in's web application. Allows add-ins to identify users. + * Calls the Azure Active Directory V 2.0 endpoint to get an access token to your add-in's web application. Enables add-ins to identify users. * Server side code can use this token to access Microsoft Graph for the add-in's web application by using the * {@link https://docs.microsoft.com/azure/active-directory/develop/active-directory-v2-protocols-oauth-on-behalf-of | "on behalf of" OAuth flow}. * @@ -1148,11 +1150,8 @@ declare namespace Office { * * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements | IdentityAPI} * - * This API requires a single sign-on configuration that bridges the add-in to an Azure application. Office users sign-in with Organizational - * Accounts and Microsoft Accounts. Microsoft Azure returns tokens intended for both user account types to access resources in the Microsoft Graph. - * * @param options - Optional. Accepts an AuthOptions object to define sign-on behaviors. - * @param callback - Optional. Accepts a callback method to handle the token acquisition attempt. + * @param callback - Optional. Accepts a callback method that can use parse the token for the user's ID or use the token in the "on behalf of" flow to get access to Microsoft Graph. * If AsyncResult.status is "succeeded", then AsyncResult.value is the raw AAD v. 2.0-formatted access token. * * @beta @@ -1170,7 +1169,7 @@ declare namespace Office { */ forceConsent?: boolean, /** - * Prompts the user to add (or to switch if already added) his or her Office account. + * Prompts the user to add his or her Office account (or to switch to it, if it is already added). */ forceAddAccount?: boolean, /** From 29306b60a4ed40be5d112f5a267dda16c2125ca2 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 14:00:31 -0700 Subject: [PATCH 263/289] adds typings for the 'ip-address' package. --- types/ip-address/index.d.ts | 110 ++++++++++++++++++++++++ types/ip-address/ip-address-tests.ts | 121 +++++++++++++++++++++++++++ types/ip-address/tsconfig.json | 19 +++++ types/ip-address/tslint.json | 3 + 4 files changed, 253 insertions(+) create mode 100644 types/ip-address/index.d.ts create mode 100644 types/ip-address/ip-address-tests.ts create mode 100644 types/ip-address/tsconfig.json create mode 100644 types/ip-address/tslint.json diff --git a/types/ip-address/index.d.ts b/types/ip-address/index.d.ts new file mode 100644 index 0000000000..59dbb07d57 --- /dev/null +++ b/types/ip-address/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for ip-address 5.8 +// Project: https://github.com/beaugunderson/ip-address +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace ipAddress; + +export interface v6Helpers { + spanAllZeroes(s: string): string; + spanAll(s: string, optionalOffset?: number): string; + spanLeadingZeroes(address: string): string; + simpleGroup(addressString: string, offset?: number): string; +} + +export interface TeredoObject { + readonly prefix: string; + readonly server4: string; + readonly client4: string; + readonly flags: string; + readonly coneNat: any; + readonly microsoft: { + readonly reserved: any, + readonly universalLocal: any, + readonly groupIndividual: any, + readonly nonce: any, + }; + udpPort: string; +} + +export interface SixToFourResponse { + readonly prefix: string; + readonly gateway: string; +} + +export class Address4 { + constructor(address: string); + static fromHex(hex: string): Address4; + static fromInteger(integer: number): Address4; + static fromBigInteger(bigInteger: any): Address4; + + valid: boolean; + address: string; + parsedAddress: string; + groups: number; + v4: boolean; + subnet: string; + subnetMask: number; + + isValid(): boolean; + correctForm(): string; + isCorrect(): boolean; + toHex(): string; + toArray(): any; + toGroup6(): string; + bigInteger(): any; + startAddress(): Address4; + startAddressExclusive(): Address4; + endAddress(): Address4; + endAddressExclusive(): Address4; + mask(optionalMask?: number): string; + getBitsBase2(start: number, end: number): string; + isInSubnet(): boolean; + binaryZeroPad(): string; +} + +export class Address6 { + constructor(address: string, optionalGroups?: number); + static fromBigInteger(bigInteger: any): Address6; + static fromURL(url: string): Address6; + static fromAddress4(address4: string): Address6; + static fromArpa(arpaFormAddress: string): Address6; + static fromByteArray(bytes: any): Address6; + static fromUnsignedByteArray(bytes: any): Address6; + + valid: boolean; + address: string; + groups: number; + v4: boolean; + subnet: string; + subnetMask: number; + + microsoftTranscription(): string; + mask(optionalMask?: number): string; + possibleSubnets(optionalSubnetSize?: number): string; + startAddress(): Address6; + startAddressExclusive(): Address6; + endAddress(): Address6; + endAddressExclusive(): Address6; + getScope(): string; + getType(): string; + getBits(start: number, end: number): any; + getBitsBase2(start: number, end: number): string; + getBitsBase16(start: number, end: number): string; + getBitsPastSubnet(): string; + reverseForm(options?: { omitSuffix: boolean }): string; + correctForm(): string; + binaryZeroPad(): string; + canonicalForm(): string; + decimal(): string; + bigInteger(): any; + to4(): string; + to4in6(): string; + inspectTeredo(): TeredoObject; + inspect6to4(): SixToFourResponse; + to6to4(): Address6; + toByteArray(): any; + toUnsignedByteArray(): any; +} + +export const v6: {helpers: v6Helpers}; diff --git a/types/ip-address/ip-address-tests.ts b/types/ip-address/ip-address-tests.ts new file mode 100644 index 0000000000..76b4e471aa --- /dev/null +++ b/types/ip-address/ip-address-tests.ts @@ -0,0 +1,121 @@ +import ipAddress = require('ip-address'); + +// Test Address4 Typings +const address4 = new ipAddress.Address4('127.0.0.1'); + +const address4Valid = address4.valid; +const address4String = address4.address; +const address4Parsed = address4.parsedAddress; +const address4Groups = address4.groups; +const address4v4 = address4.v4; +const address4Subnet = address4.subnet; +const address4Mask = address4.subnetMask; + +// $ExpectType Address4 +ipAddress.Address4.fromHex('127.0.0.1'); +// $ExpectType Address4 +ipAddress.Address4.fromInteger(127001); +// $ExpectType Address4 +address4.startAddress(); +// $ExpectType Address4 +address4.startAddressExclusive(); +// $ExpectType Address4 +address4.endAddress(); +// $ExpectType Address4 +address4.endAddressExclusive(); + +// $ExpectType string +address4.correctForm(); +// $ExpectType string +address4.toHex(); +// $ExpectType string +address4.toGroup6(); +// $ExpectType string +address4.mask(); +// $ExpectType string +address4.mask(0); +// $ExpectType string +address4.getBitsBase2(0, 1); +// $ExpectType string +address4.binaryZeroPad(); + +// $ExpectType boolean +address4.isValid(); +// $ExpectType boolean +address4.isCorrect(); +// $ExpectType boolean +address4.isInSubnet(); + +// Test Address6 Typings +const address6 = new ipAddress.Address6('127.0.0.1'); + +const address6Valid = address6.valid; +const address6String = address6.address; +const address6Groups = address6.groups; +const address6v4 = address6.v4; +const address6Subnet = address6.subnet; +const address6Mask = address6.subnetMask; + +// $ExpectType Address6 +address6.startAddress(); +// $ExpectType Address6 +address6.startAddressExclusive(); +// $ExpectType Address6 +address6.endAddress(); +// $ExpectType Address6 +address6.endAddressExclusive(); +// $ExpectType Address6 +address6.to6to4(); + +// $ExpectType string +address6.microsoftTranscription(); +// $ExpectType string +address6.mask(); +// $ExpectType string +address6.mask(0); +// $ExpectType string +address6.possibleSubnets(); +// $ExpectType string +address6.possibleSubnets(1); +// $ExpectType string +address6.getScope(); +// $ExpectType string +address6.getType(); +// $ExpectType string +address6.getBitsBase2(0, 1); +// $ExpectType string +address6.getBitsBase16(0, 1); +// $ExpectType string +address6.getBitsPastSubnet(); +// $ExpectType string +address6.reverseForm(); +// $ExpectType string +address6.correctForm(); +// $ExpectType string +address6.binaryZeroPad(); +// $ExpectType string +address6.canonicalForm(); +// $ExpectType string +address6.decimal(); +// $ExpectType string +address6.to4(); +// $ExpectType string +address6.to4in6(); + +// $ExpectType TeredoObject +address6.inspectTeredo(); + +// $ExpectType SixToFourResponse +address6.inspect6to4(); + +// Test v6 Typings +const v6 = ipAddress.v6; + +// $ExpectType string +v6.helpers.simpleGroup(address6.address); +// $ExpectType string +v6.helpers.spanAll(address6.address); +// $ExpectType string +v6.helpers.spanAllZeroes(address6.address); +// $ExpectType string +v6.helpers.spanLeadingZeroes(address6.address); diff --git a/types/ip-address/tsconfig.json b/types/ip-address/tsconfig.json new file mode 100644 index 0000000000..79254ab191 --- /dev/null +++ b/types/ip-address/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ip-address-tests.ts" + ] +} diff --git a/types/ip-address/tslint.json b/types/ip-address/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/ip-address/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 86f0182f170a777ccfe57e75b82aa352c192e4da Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Sat, 25 Aug 2018 13:30:06 -0700 Subject: [PATCH 264/289] adds typings for the 'toposort' package --- types/toposort/index.d.ts | 3 ++- types/toposort/toposort-tests.ts | 17 ++++------------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/types/toposort/index.d.ts b/types/toposort/index.d.ts index 8da78b7d11..c2c9940c3a 100644 --- a/types/toposort/index.d.ts +++ b/types/toposort/index.d.ts @@ -3,4 +3,5 @@ // Definitions by: Daniel Byrne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export default function toposort(graph: ReadonlyArray<[string, string]>): ReadonlyArray; +declare function toposort(graph: ReadonlyArray<[string, string]>): ReadonlyArray; +export = toposort; diff --git a/types/toposort/toposort-tests.ts b/types/toposort/toposort-tests.ts index 201277fefa..84f554033b 100644 --- a/types/toposort/toposort-tests.ts +++ b/types/toposort/toposort-tests.ts @@ -1,18 +1,9 @@ -import toposort from 'toposort'; +import toposort = require('toposort'); const testGraph: ReadonlyArray<[string, string]> = [ - [ - 'string1', - 'string2', - ], - [ - 'string2', - 'string3', - ], - [ - 'string3', - 'string1', - ], + ["string1", "string2"], + ["string2", "string3"], + ["string3", "string1"] ]; // $ExpectType ReadonlyArray From 99efda12b1f332fff422d818be40f46ee26f33bd Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Mon, 27 Aug 2018 12:56:07 -0700 Subject: [PATCH 265/289] adds typings for the 'is-running' package. --- types/is-running/index.d.ts | 8 ++++++++ types/is-running/is-running-tests.ts | 4 ++++ types/is-running/tsconfig.json | 23 +++++++++++++++++++++++ types/is-running/tslint.json | 3 +++ 4 files changed, 38 insertions(+) create mode 100644 types/is-running/index.d.ts create mode 100644 types/is-running/is-running-tests.ts create mode 100644 types/is-running/tsconfig.json create mode 100644 types/is-running/tslint.json diff --git a/types/is-running/index.d.ts b/types/is-running/index.d.ts new file mode 100644 index 0000000000..e573a44193 --- /dev/null +++ b/types/is-running/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-running 2.1 +// Project: https://github.com/nisaacson/is-running +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isRunning(pid: number): boolean; + +export = isRunning; diff --git a/types/is-running/is-running-tests.ts b/types/is-running/is-running-tests.ts new file mode 100644 index 0000000000..5f8ad2983a --- /dev/null +++ b/types/is-running/is-running-tests.ts @@ -0,0 +1,4 @@ +import isRunning = require("is-running"); + +// $ExpectType boolean +isRunning(100); diff --git a/types/is-running/tsconfig.json b/types/is-running/tsconfig.json new file mode 100644 index 0000000000..3a03f10b96 --- /dev/null +++ b/types/is-running/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-running-tests.ts" + ] +} diff --git a/types/is-running/tslint.json b/types/is-running/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/is-running/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 375f7aa133dce13a7d1978bc414ae712dbb4e200 Mon Sep 17 00:00:00 2001 From: Ricky Kirkham Date: Tue, 28 Aug 2018 15:41:12 -0700 Subject: [PATCH 266/289] review changes --- types/office-js/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index f3e4bb6fd5..17dc31810f 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1151,7 +1151,7 @@ declare namespace Office { * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements | IdentityAPI} * * @param options - Optional. Accepts an AuthOptions object to define sign-on behaviors. - * @param callback - Optional. Accepts a callback method that can use parse the token for the user's ID or use the token in the "on behalf of" flow to get access to Microsoft Graph. + * @param callback - Optional. Accepts a callback method that can parse the token for the user's ID or use the token in the "on behalf of" flow to get access to Microsoft Graph. * If AsyncResult.status is "succeeded", then AsyncResult.value is the raw AAD v. 2.0-formatted access token. * * @beta @@ -1169,7 +1169,7 @@ declare namespace Office { */ forceConsent?: boolean, /** - * Prompts the user to add his or her Office account (or to switch to it, if it is already added). + * Prompts the user to add their Office account (or to switch to it, if it is already added). */ forceAddAccount?: boolean, /** From 5c64bb948b8f679684a2ec582924a6f26cced38c Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Sun, 26 Aug 2018 11:43:27 -0700 Subject: [PATCH 267/289] adds typings for the 'abstract-leveldown' package --- .../abstract-leveldown-tests.ts | 13 +++ types/abstract-leveldown/index.d.ts | 103 ++++++++++++++++++ types/abstract-leveldown/tsconfig.json | 23 ++++ types/abstract-leveldown/tslint.json | 3 + 4 files changed, 142 insertions(+) create mode 100644 types/abstract-leveldown/abstract-leveldown-tests.ts create mode 100644 types/abstract-leveldown/index.d.ts create mode 100644 types/abstract-leveldown/tsconfig.json create mode 100644 types/abstract-leveldown/tslint.json diff --git a/types/abstract-leveldown/abstract-leveldown-tests.ts b/types/abstract-leveldown/abstract-leveldown-tests.ts new file mode 100644 index 0000000000..c5edadf069 --- /dev/null +++ b/types/abstract-leveldown/abstract-leveldown-tests.ts @@ -0,0 +1,13 @@ +import { AbstractLevelDOWN } from 'abstract-leveldown'; + +const test = (levelDown: AbstractLevelDOWN) => { + levelDown.put("key", "value", (err?) => { }); + levelDown.put(1, "value", { something: true }, (err?) => { }); + + levelDown.get("key", (err?) => { }); + levelDown.get(1, { something: true }, (err?) => { }); +}; +// $ExpectType void +test(new AbstractLevelDOWN('here')); +// $ExpectType void +test(AbstractLevelDOWN('there')); diff --git a/types/abstract-leveldown/index.d.ts b/types/abstract-leveldown/index.d.ts new file mode 100644 index 0000000000..2caf073432 --- /dev/null +++ b/types/abstract-leveldown/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for abstract-leveldown 5.0 +// Project: https://github.com/Level/abstract-leveldown +// Definitions by: Meirion Hughes +// Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface AbstractOptions { + readonly [k: string]: any; +} + +export type ErrorCallback = (err: Error | undefined) => void; +export type ErrorValueCallback = (err: Error | undefined, value: V) => void; +export type ErrorKeyValueCallback = (err: Error | undefined, key: K, value: V) => void; + +export interface AbstractOpenOptions extends AbstractOptions { + createIfMissing?: boolean; + errorIfExists?: boolean; +} + +export interface AbstractGetOptions extends AbstractOptions { + asBuffer?: boolean; +} + +export interface AbstractLevelDOWN extends AbstractOptions { + open(cb: ErrorCallback): void; + open(options: AbstractOpenOptions, cb: ErrorCallback): void; + + close(cb: ErrorCallback): void; + + get(key: K, cb: ErrorValueCallback): void; + get(key: K, options: AbstractGetOptions, cb: ErrorValueCallback): void; + + put(key: K, value: V, cb: ErrorCallback): void; + put(key: K, value: V, options: AbstractOptions, cb: ErrorCallback): void; + + del(key: K, cb: ErrorCallback): void; + del(key: K, options: AbstractOptions, cb: ErrorCallback): void; + + batch(): AbstractChainedBatch; + batch(array: ReadonlyArray>, cb: ErrorCallback): AbstractChainedBatch; + batch(array: ReadonlyArray>, options: AbstractOptions, cb: ErrorCallback): AbstractChainedBatch; + + iterator(options?: AbstractIteratorOptions): AbstractIterator; +} + +export interface AbstractLevelDOWNConstructor { + new (location: string): AbstractLevelDOWN; + (location: string): AbstractLevelDOWN; +} + +export interface AbstractIteratorOptions extends AbstractOptions { + gt?: K; + gte?: K; + lt?: K; + lte?: K; + reverse?: boolean; + limit?: number; + keys?: boolean; + values?: boolean; + keyAsBuffer?: boolean; + valueAsBuffer?: boolean; +} + +export type AbstractBatch = PutBatch | DelBatch; + +export interface PutBatch { + readonly type: 'put'; + readonly key: K; + readonly value: V; +} + +export interface DelBatch { + readonly type: 'del'; + readonly key: K; +} + +export interface AbstractChainedBatch extends AbstractChainedBatchConstructor, AbstractOptions { + put: (key: K, value: V) => this; + del: (key: K) => this; + clear: () => this; + write(cb: ErrorCallback): any; + write(options: any, cb: ErrorCallback): any; +} + +export interface AbstractChainedBatchConstructor { + new(db: any): AbstractChainedBatch; + (db: any): AbstractChainedBatch; +} + +export interface AbstractIterator extends AbstractChainedBatchConstructor { + db: AbstractLevelDOWN; + next(cb: ErrorKeyValueCallback): this; + end(cb: ErrorCallback): void; +} + +export interface AbstractIteratorConstructor { + new(db: any): AbstractIterator; + (db: any): AbstractIterator; +} + +export const AbstractLevelDOWN: AbstractLevelDOWNConstructor; +export const AbstractIterator: AbstractIteratorConstructor; +export const AbstractChainedBatch: AbstractChainedBatchConstructor; diff --git a/types/abstract-leveldown/tsconfig.json b/types/abstract-leveldown/tsconfig.json new file mode 100644 index 0000000000..286b867f00 --- /dev/null +++ b/types/abstract-leveldown/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", + "abstract-leveldown-tests.ts" + ] +} diff --git a/types/abstract-leveldown/tslint.json b/types/abstract-leveldown/tslint.json new file mode 100644 index 0000000000..256ee54775 --- /dev/null +++ b/types/abstract-leveldown/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From b3fbc0ad8f46b07bd1fabc5dc435ccc42465c483 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 10:14:39 -0700 Subject: [PATCH 268/289] adds typings for the 'bloem' package --- types/bloem/bloem-tests.ts | 15 +++++++++++++++ types/bloem/index.d.ts | 39 ++++++++++++++++++++++++++++++++++++++ types/bloem/tsconfig.json | 23 ++++++++++++++++++++++ types/bloem/tslint.json | 3 +++ 4 files changed, 80 insertions(+) create mode 100644 types/bloem/bloem-tests.ts create mode 100644 types/bloem/index.d.ts create mode 100644 types/bloem/tsconfig.json create mode 100644 types/bloem/tslint.json diff --git a/types/bloem/bloem-tests.ts b/types/bloem/bloem-tests.ts new file mode 100644 index 0000000000..bcebbecebb --- /dev/null +++ b/types/bloem/bloem-tests.ts @@ -0,0 +1,15 @@ +import bloem = require('bloem'); + +const base = new bloem.Bloem(1, 2, Buffer.from('1', 'hex')); +const safe = new bloem.SafeBloem(1, 2, Buffer.from('2', 'hex')); +const scaling = new bloem.ScalingBloem(1, + {ratio: 1, initial_capacity: 2, scaling: 3} +); + +// options are optional +const scaling2 = new bloem.ScalingBloem(1); + +// $ExpectType number +bloem.calculateSize(1, 2); +// $ExpectType number +bloem.calculateSlices(1, 2); diff --git a/types/bloem/index.d.ts b/types/bloem/index.d.ts new file mode 100644 index 0000000000..a913e9f883 --- /dev/null +++ b/types/bloem/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for bloem 0.2 +// Project: https://github.com/wiedi/node-bloem +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace bloem; + +export function calculateSize(capacity: number, error_rate: number): number; +export function calculateSlices(size: number, capacity: number): number; + +export class Bloem { + constructor(size: number, slices: number, buffer: Buffer); + + has(key: Buffer): boolean; + add(key: Buffer): void; +} + +export class SafeBloem { + constructor(capacity: number, error_rate: number, buffer: Buffer); + + has(key: Buffer): boolean; + add(key: Buffer): boolean; +} + +export class ScalingBloem { + constructor( + error_rate: number, + options?: { + ratio?: number; + initial_capacity?: number; + scaling?: number; + } + ); + + has(key: Buffer): boolean; + add(key: Buffer): void; +} diff --git a/types/bloem/tsconfig.json b/types/bloem/tsconfig.json new file mode 100644 index 0000000000..f5ecad97bd --- /dev/null +++ b/types/bloem/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", + "bloem-tests.ts" + ] +} \ No newline at end of file diff --git a/types/bloem/tslint.json b/types/bloem/tslint.json new file mode 100644 index 0000000000..6fafe521cb --- /dev/null +++ b/types/bloem/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" + } From f502e26e8c8680759c93129e115f44c4d6eb2080 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 15:45:57 -0700 Subject: [PATCH 269/289] adds typings for the 'koa-better-body' package --- types/koa-better-body/index.d.ts | 33 +++++++++++++++++++ .../koa-better-body/koa-better-body-tests.ts | 11 +++++++ types/koa-better-body/tsconfig.json | 19 +++++++++++ types/koa-better-body/tslint.json | 3 ++ 4 files changed, 66 insertions(+) create mode 100644 types/koa-better-body/index.d.ts create mode 100644 types/koa-better-body/koa-better-body-tests.ts create mode 100644 types/koa-better-body/tsconfig.json create mode 100644 types/koa-better-body/tslint.json diff --git a/types/koa-better-body/index.d.ts b/types/koa-better-body/index.d.ts new file mode 100644 index 0000000000..ab7cf5b21f --- /dev/null +++ b/types/koa-better-body/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for koa-better-body 3.0 +// Project: https://github.com/tunnckoCore/koa-better-body +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Context } from 'koa'; + +declare function KoaBetterBody(options?: KoaBetterBody.Options): KoaBetterBody.Body; + +declare namespace KoaBetterBody { + interface Options { + fields?: boolean | string; + files?: boolean | string; + multipart?: boolean; + textLimit?: string; + formLimit?: string; + urlencodedLimit?: string; + jsonLimit?: string; + bufferLimit?: string; + jsonStrict?: boolean; + detectJSON?: () => any; + strict?: boolean; + delimiter?: symbol; + decodeURIComponent?: any; + maxKeys?: number; + buffer?: boolean; + } + + type Body = (context: Context, next: () => void) => Generator; +} + +export = KoaBetterBody; diff --git a/types/koa-better-body/koa-better-body-tests.ts b/types/koa-better-body/koa-better-body-tests.ts new file mode 100644 index 0000000000..2f4deb2d49 --- /dev/null +++ b/types/koa-better-body/koa-better-body-tests.ts @@ -0,0 +1,11 @@ +import body = require('koa-better-body'); + +// $ExpectType Body +body(); + +const testOptions: body.Options = { + jsonLimit: '100mb', +}; + +// $ExpectType Body +body(testOptions); diff --git a/types/koa-better-body/tsconfig.json b/types/koa-better-body/tsconfig.json new file mode 100644 index 0000000000..74a794a11c --- /dev/null +++ b/types/koa-better-body/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-better-body-tests.ts" + ] +} diff --git a/types/koa-better-body/tslint.json b/types/koa-better-body/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/koa-better-body/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 6836ef6562982bb564befcf8f33244361e38b806 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 11:59:22 -0700 Subject: [PATCH 270/289] adds typings for the 'cli-truncate' package --- types/cli-truncate/cli-truncate-tests.ts | 19 +++++++++++++++++++ types/cli-truncate/index.d.ts | 12 ++++++++++++ types/cli-truncate/tsconfig.json | 23 +++++++++++++++++++++++ types/cli-truncate/tslint.json | 3 +++ 4 files changed, 57 insertions(+) create mode 100644 types/cli-truncate/cli-truncate-tests.ts create mode 100644 types/cli-truncate/index.d.ts create mode 100644 types/cli-truncate/tsconfig.json create mode 100644 types/cli-truncate/tslint.json diff --git a/types/cli-truncate/cli-truncate-tests.ts b/types/cli-truncate/cli-truncate-tests.ts new file mode 100644 index 0000000000..677108e6ad --- /dev/null +++ b/types/cli-truncate/cli-truncate-tests.ts @@ -0,0 +1,19 @@ +import cliTruncate = require('cli-truncate'); + +// Truncate at different positions +// $ExpectType string +cliTruncate('unicorn', 4); // default position: 'end' + +// $ExpectType string +cliTruncate('unicorn', 4, {position: 'start'}); + +// $ExpectType string +cliTruncate('unicorn', 4, {position: 'middle'}); + +// Truncate Unicode surrogate pairs +// $ExpectType string +cliTruncate('uni\uD83C\uDE00corn', 5); + +// Truncate full-width characters +// $ExpectType string +cliTruncate('안녕하세요', 3); diff --git a/types/cli-truncate/index.d.ts b/types/cli-truncate/index.d.ts new file mode 100644 index 0000000000..f02ec427b8 --- /dev/null +++ b/types/cli-truncate/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for cli-truncate 1.1 +// Project: https://github.com/sindresorhus/cli-truncate +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = cliTruncate; + +declare function cliTruncate( + input: string, + columns: number, + options?: {position?: 'start' | 'middle' | 'end'}, +): string; diff --git a/types/cli-truncate/tsconfig.json b/types/cli-truncate/tsconfig.json new file mode 100644 index 0000000000..efc2a3a1c7 --- /dev/null +++ b/types/cli-truncate/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", + "cli-truncate-tests.ts" + ] +} diff --git a/types/cli-truncate/tslint.json b/types/cli-truncate/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/cli-truncate/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From e6c19da9e7c3fad4ff4d6eff128e3470b3ceba62 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 09:44:52 -0700 Subject: [PATCH 271/289] adds typings for the 'triple-beam' package. --- types/triple-beam/index.d.ts | 22 ++++++++++++++++++++++ types/triple-beam/triple-beam-tests.ts | 13 +++++++++++++ types/triple-beam/tsconfig.json | 23 +++++++++++++++++++++++ types/triple-beam/tslint.json | 3 +++ 4 files changed, 61 insertions(+) create mode 100644 types/triple-beam/index.d.ts create mode 100644 types/triple-beam/triple-beam-tests.ts create mode 100644 types/triple-beam/tsconfig.json create mode 100644 types/triple-beam/tslint.json diff --git a/types/triple-beam/index.d.ts b/types/triple-beam/index.d.ts new file mode 100644 index 0000000000..3f6cdda734 --- /dev/null +++ b/types/triple-beam/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for triple-beam 1.3 +// Project: https://github.com/winstonjs/triple-beam +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace TripleBeam; + +export const LEVEL: string; +export const MESSAGE: string; +export const SPLAT: string; +export const configs: Configs; + +export interface Config { + readonly levels: {[k: string]: number}; + readonly colors: {[k: string]: string}; + } + +export interface Configs { + readonly cli: Config; + readonly npm: Config; + readonly syslog: Config; +} diff --git a/types/triple-beam/triple-beam-tests.ts b/types/triple-beam/triple-beam-tests.ts new file mode 100644 index 0000000000..de583abdde --- /dev/null +++ b/types/triple-beam/triple-beam-tests.ts @@ -0,0 +1,13 @@ +import tripleBeam = require('triple-beam'); + +const level: string = tripleBeam.LEVEL; +const message: string = tripleBeam.MESSAGE; +const splat: string = tripleBeam.SPLAT; +const configsObj: tripleBeam.Configs = tripleBeam.configs; + +const cli: tripleBeam.Config = configsObj.cli; +const npm: tripleBeam.Config = configsObj.npm; +const syslog: tripleBeam.Config = configsObj.syslog; + +const levels = cli.levels; +const colors = cli.colors; diff --git a/types/triple-beam/tsconfig.json b/types/triple-beam/tsconfig.json new file mode 100644 index 0000000000..9b58bd5007 --- /dev/null +++ b/types/triple-beam/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", + "triple-beam-tests.ts" + ] +} diff --git a/types/triple-beam/tslint.json b/types/triple-beam/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/triple-beam/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ad7a113daf102ec5c0df8f515678f309abe93b49 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 16:50:19 -0700 Subject: [PATCH 272/289] fixes needless namespace --- types/bloem/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/bloem/index.d.ts b/types/bloem/index.d.ts index a913e9f883..bcf6b35820 100644 --- a/types/bloem/index.d.ts +++ b/types/bloem/index.d.ts @@ -5,8 +5,6 @@ /// -export as namespace bloem; - export function calculateSize(capacity: number, error_rate: number): number; export function calculateSlices(size: number, capacity: number): number; From 73c566bec37c215041132f14973ec997afc05483 Mon Sep 17 00:00:00 2001 From: JackLewisGit Date: Wed, 29 Aug 2018 10:05:09 +1000 Subject: [PATCH 273/289] Update c3-tests.ts Added zoom type to zoom_examples() --- types/c3/c3-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/c3/c3-tests.ts b/types/c3/c3-tests.ts index 6d7ea67287..5c554320f9 100644 --- a/types/c3/c3-tests.ts +++ b/types/c3/c3-tests.ts @@ -334,6 +334,7 @@ function zoom_examples() { data: {}, zoom: { enabled: false, + type: 'scroll', rescale: true, extent: [1, 100], // enable more zooming onzoom: (domain) => { /* code */ }, From 7a2180c99e70af7b6971a5651bddfb3bf43ee6b6 Mon Sep 17 00:00:00 2001 From: JackLewisGit Date: Wed, 29 Aug 2018 10:05:31 +1000 Subject: [PATCH 274/289] Update index.d.ts Added zoom type to ZoomOptions --- types/c3/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index 0d94347ca3..e047b22c7e 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -806,6 +806,10 @@ export interface ZoomOptions { * Enable zooming. */ enabled?: boolean; + /** + * Set interaction type for zooming + */ + type?: 'scroll' | 'drag'; /** * Enable to rescale after zooming. If true set, y domain will be updated according to the zoomed region. */ From 1f6b5d5be4311401f11a8533460474cb213527bf Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 17:58:03 -0700 Subject: [PATCH 275/289] adds typings for the 'wif' package --- types/wif/index.d.ts | 27 +++++++++++++++++++++++++++ types/wif/tsconfig.json | 19 +++++++++++++++++++ types/wif/tslint.json | 3 +++ types/wif/wif-tests.ts | 16 ++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 types/wif/index.d.ts create mode 100644 types/wif/tsconfig.json create mode 100644 types/wif/tslint.json create mode 100644 types/wif/wif-tests.ts diff --git a/types/wif/index.d.ts b/types/wif/index.d.ts new file mode 100644 index 0000000000..21b4175905 --- /dev/null +++ b/types/wif/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for wif 2.0 +// Project: https://github.com/bitcoinjs/wif +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface WIFReturn { + readonly version: number; + readonly privateKey: Buffer; + readonly compressed: boolean; +} + +export function decodeRaw(buffer: Buffer, version?: number): WIFReturn; +export function decode(string: string, version: number): WIFReturn; + +export function encodeRaw( + version: number, + privateKey: Buffer, + compressed: boolean +): Buffer; + +export function encode( + version: number | WIFReturn, + privateKey: Buffer, + compressed: boolean +): Buffer; diff --git a/types/wif/tsconfig.json b/types/wif/tsconfig.json new file mode 100644 index 0000000000..f412a0b7cc --- /dev/null +++ b/types/wif/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "wif-tests.ts" + ] +} diff --git a/types/wif/tslint.json b/types/wif/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/wif/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/wif/wif-tests.ts b/types/wif/wif-tests.ts new file mode 100644 index 0000000000..b833d7b1f5 --- /dev/null +++ b/types/wif/wif-tests.ts @@ -0,0 +1,16 @@ +import wif = require('wif'); + +const testString = 'test'; +const testBuffer = Buffer.from(testString); + +// $ExpectType WIFReturn +wif.decodeRaw(testBuffer); +// $ExpectType WIFReturn +wif.decodeRaw(testBuffer, 0); +// $ExpectType WIFReturn +wif.decode(testString, 0); + +// $ExpectType Buffer +wif.encodeRaw(1, testBuffer, true); +// $ExpectType Buffer +wif.encode(1, testBuffer, true); From 5d602f18d25ed09c86e809d20da97361c1234ec7 Mon Sep 17 00:00:00 2001 From: Daniel Byrne Date: Tue, 28 Aug 2018 19:04:27 -0700 Subject: [PATCH 276/289] adds typings for the 'koa-convert' package --- types/koa-convert/index.d.ts | 13 +++++++++++++ types/koa-convert/koa-convert-tests.ts | 16 ++++++++++++++++ types/koa-convert/tsconfig.json | 19 +++++++++++++++++++ types/koa-convert/tslint.json | 3 +++ 4 files changed, 51 insertions(+) create mode 100644 types/koa-convert/index.d.ts create mode 100644 types/koa-convert/koa-convert-tests.ts create mode 100644 types/koa-convert/tsconfig.json create mode 100644 types/koa-convert/tslint.json diff --git a/types/koa-convert/index.d.ts b/types/koa-convert/index.d.ts new file mode 100644 index 0000000000..ed5cd38480 --- /dev/null +++ b/types/koa-convert/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for koa-convert 1.2 +// Project: https://github.com/koajs/convert +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Context, Middleware } from "koa"; + +declare function convert( + mw: (context: Context, next: () => void) => Generator +): Middleware; + +export = convert; diff --git a/types/koa-convert/koa-convert-tests.ts b/types/koa-convert/koa-convert-tests.ts new file mode 100644 index 0000000000..0a795e522b --- /dev/null +++ b/types/koa-convert/koa-convert-tests.ts @@ -0,0 +1,16 @@ +import convert = require('koa-convert'); +import Koa = require('koa'); + +const app = new Koa(); + +app.use(modernMiddleware); + +app.use(convert(legacyMiddleware)); + +function * legacyMiddleware(next: any) { + yield next; +} + +function modernMiddleware(ctx: Koa.Context, next: any) { + return next().then(() => {}); +} diff --git a/types/koa-convert/tsconfig.json b/types/koa-convert/tsconfig.json new file mode 100644 index 0000000000..c86211adaa --- /dev/null +++ b/types/koa-convert/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-convert-tests.ts" + ] +} diff --git a/types/koa-convert/tslint.json b/types/koa-convert/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/koa-convert/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 79a9103a5870e06072a780ac599c938689548383 Mon Sep 17 00:00:00 2001 From: Constantine Lebedev Date: Tue, 28 Aug 2018 17:12:35 +0200 Subject: [PATCH 277/289] Add typings for react-sound package --- types/react-sound/index.d.ts | 34 +++++++++++++++++++++++++ types/react-sound/react-sound-tests.tsx | 33 ++++++++++++++++++++++++ types/react-sound/tsconfig.json | 26 +++++++++++++++++++ types/react-sound/tslint.json | 1 + 4 files changed, 94 insertions(+) create mode 100644 types/react-sound/index.d.ts create mode 100644 types/react-sound/react-sound-tests.tsx create mode 100644 types/react-sound/tsconfig.json create mode 100644 types/react-sound/tslint.json diff --git a/types/react-sound/index.d.ts b/types/react-sound/index.d.ts new file mode 100644 index 0000000000..4670feb5f9 --- /dev/null +++ b/types/react-sound/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for react-sound 1.2 +// Project: https://github.com/leoasis/react-sound +// Definitions by: Konstantin Lebedev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +declare namespace ReactSound { + type PlayStatus = 'PLAYING' | 'STOPPED' | 'PAUSED'; + + interface ReactSoundProps { + url: string; + playStatus: PlayStatus; + playFromPosition?: number; + position?: number; + volume?: number; + playbackRate?: number; + autoLoad?: boolean; + loop?: boolean; + onError?: () => void; + onLoading?: () => void; + onLoad?: () => void; + onPlaying?: () => void; + onPause?: () => void; + onResume?: () => void; + onStop?: () => void; + onFinishedPlaying?: () => void; + onBufferChange?: () => void; + } +} + +declare const ReactSound: React.ComponentClass; +export = ReactSound; diff --git a/types/react-sound/react-sound-tests.tsx b/types/react-sound/react-sound-tests.tsx new file mode 100644 index 0000000000..2775ac607a --- /dev/null +++ b/types/react-sound/react-sound-tests.tsx @@ -0,0 +1,33 @@ +import ReactSound from "react-sound"; +import * as React from "react"; + +const ReactSoundRequiredOptions: JSX.Element = ( + +); + +const callbackFn = () => ({}); + +const ReactSoundAllOptions: JSX.Element = ( + +); diff --git a/types/react-sound/tsconfig.json b/types/react-sound/tsconfig.json new file mode 100644 index 0000000000..e755ca5056 --- /dev/null +++ b/types/react-sound/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "react-sound-tests.tsx" + ] +} diff --git a/types/react-sound/tslint.json b/types/react-sound/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-sound/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 97d404dce0489dc55ba923718829b514160d8046 Mon Sep 17 00:00:00 2001 From: Ben Frengley Date: Wed, 29 Aug 2018 18:52:50 +1200 Subject: [PATCH 278/289] Fix when() and when.resolve() when input is a value/promise union type --- types/when/index.d.ts | 13 +++---------- types/when/when-tests.ts | 4 ++++ 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/types/when/index.d.ts b/types/when/index.d.ts index 0b016a9ea0..117c929cbe 100644 --- a/types/when/index.d.ts +++ b/types/when/index.d.ts @@ -3,13 +3,8 @@ // Definitions by: Derek Cicerone , Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function When(value: When.Promise): When.Promise; -declare function When(value: When.Thenable): When.Promise; -declare function When(value: T): When.Promise; - -declare function When(value: When.Promise, transform: (val: T) => U): When.Promise; -declare function When(value: When.Thenable, transform: (val: T) => U): When.Promise; -declare function When(value: T, transform: (val: T) => U): When.Promise; +declare function When(promiseOrValue: T | When.Promise | When.Thenable): When.Promise; +declare function When(promiseOrValue: T | When.Promise | When.Thenable, transform: (val: T) => U): When.Promise; declare namespace When { // Helper interfaces @@ -236,9 +231,7 @@ declare namespace When { * - fulfilled with promiseOrValue's value after it is fulfilled * - rejected with promiseOrValue's reason after it is rejected */ - function resolve(promise: Promise): Promise; - function resolve(foreign: Thenable): Promise; - function resolve(value?: T): Promise; + function resolve(promiseOrValue: T | Promise | Thenable): Promise; interface Deferred { notify(update: any): void; diff --git a/types/when/when-tests.ts b/types/when/when-tests.ts index e1e3f0fd7c..416758aadb 100644 --- a/types/when/when-tests.ts +++ b/types/when/when-tests.ts @@ -33,6 +33,7 @@ class Data implements IData { var promise: when.Promise; var promise2: when.Promise; var foreign = new ForeignPromise(1); +var promiseOrValue = 1 as number | when.Promise; var error = new Error("boom!"); var example: () => void; var native: Promise; @@ -46,12 +47,14 @@ var native: Promise; promise = when(1); promise = when(when(1)); promise = when(foreign); +promise = when(promiseOrValue); /* when(x, f) */ promise = when(1, val => val + val); promise = when(when(1), val => val + val); promise = when(foreign, val => val + val); +promise = when(promiseOrValue, val => val + val); /* when.try(f, ...args) */ @@ -204,6 +207,7 @@ promise = when.promise((resolve, reject) => reject(error)); promise = when.resolve(1); promise = when.resolve(promise); promise = when.resolve(foreign); +promise = when.resolve(promiseOrValue); /* when.reject(error) */ From 0bf73e621a800b6e16a62deed1918d7a9799d81c Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 29 Aug 2018 09:56:50 +0300 Subject: [PATCH 279/289] change import to require --- types/hat/hat-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hat/hat-tests.ts b/types/hat/hat-tests.ts index 1b91702742..3156a138f0 100644 --- a/types/hat/hat-tests.ts +++ b/types/hat/hat-tests.ts @@ -1,4 +1,4 @@ -import * as hat from 'hat'; +import hat = require('hat'); const randomId = hat(); From 8fb0189dd4432b854d72d9e78fcdea53829b24fe Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Wed, 29 Aug 2018 12:08:17 +0200 Subject: [PATCH 280/289] ioredis: new option maxRetriesPerRequest --- types/ioredis/index.d.ts | 11 +++++++++++ types/ioredis/ioredis-tests.ts | 1 + 2 files changed, 12 insertions(+) diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index d44278cad6..017fc04505 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -841,6 +841,17 @@ declare namespace IORedis { * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858 */ retryStrategy?(times: number): number | false; + /** + * By default, all pending commands will be flushed with an error every + * 20 retry attempts. That makes sure commands won't wait forever when + * the connection is down. You can change this behavior by setting + * `maxRetriesPerRequest`. + * + * Set maxRetriesPerRequest to `null` to disable this behavior, and + * every command will wait forever until the connection is alive again + * (which is the default behavior before ioredis v4). + */ + maxRetriesPerRequest?: number | null; /** * 1/true means reconnect, 2 means reconnect and resend failed command. Returning false will ignore * the error and do nothing. diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index f39edffa0a..848f0b2841 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -46,6 +46,7 @@ new Redis({ password: 'auth', db: 0, retryStrategy() { return false; }, + maxRetriesPerRequest: 20, showFriendlyErrorStack: true, tls: { servername: 'tlsservername' From a3a71e170c54ad5470df7ba0c9fd9023e3f45bff Mon Sep 17 00:00:00 2001 From: DenisFrezzato Date: Wed, 29 Aug 2018 12:07:18 +0200 Subject: [PATCH 281/289] Fix type of replace action. --- types/react-navigation/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 61aab60a7c..def659fc6a 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -276,7 +276,8 @@ export interface NavigationInitAction extends NavigationInitActionPayload { } export interface NavigationReplaceActionPayload { - key: string; + key?: string; + newKey?: string; routeName: string; params?: NavigationParams; action?: NavigationNavigateAction; From d7782a0b7db029a56982413f18482ab5fe220bba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Einar=20Nor=C3=B0fj=C3=B6r=C3=B0?= Date: Wed, 29 Aug 2018 11:26:31 +0000 Subject: [PATCH 282/289] Remove global crossfilter export --- types/crossfilter/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/crossfilter/index.d.ts b/types/crossfilter/index.d.ts index a009e920dd..bae8a06565 100644 --- a/types/crossfilter/index.d.ts +++ b/types/crossfilter/index.d.ts @@ -110,7 +110,6 @@ declare namespace CrossFilter { } } -declare var crossfilter: CrossFilter.CrossFilterStatic; declare module "crossfilter" { var crossfilter: CrossFilter.CrossFilterStatic; export = crossfilter; From 3b25f3f9030117c75e1b80d0c190bd5af4aa6238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Einar=20Nor=C3=B0fj=C3=B6r=C3=B0?= Date: Wed, 29 Aug 2018 11:35:27 +0000 Subject: [PATCH 283/289] import crossfilter in the tests --- types/crossfilter/crossfilter-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/crossfilter/crossfilter-tests.ts b/types/crossfilter/crossfilter-tests.ts index 5d9981b6d1..e96d83a7e2 100644 --- a/types/crossfilter/crossfilter-tests.ts +++ b/types/crossfilter/crossfilter-tests.ts @@ -1,4 +1,4 @@ - +import * as crossfilter from 'crossfilter'; interface Payment { From ba51d1a6b41ebe091cd0eb3b62367baa27c567ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Einar=20Nor=C3=B0fj=C3=B6r=C3=B0?= Date: Wed, 29 Aug 2018 12:11:00 +0000 Subject: [PATCH 284/289] Update dc test --- types/dc/dc-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/dc/dc-tests.ts b/types/dc/dc-tests.ts index 7e1a49727e..c431e3c714 100644 --- a/types/dc/dc-tests.ts +++ b/types/dc/dc-tests.ts @@ -1,4 +1,4 @@ -import * as CrossFilter from 'crossfilter'; +import * as crossfilter from 'crossfilter'; import * as d3 from "d3"; import * as dc from "dc"; From a6b3df396b71a1a48c47728acfdb432a0e7e6ec5 Mon Sep 17 00:00:00 2001 From: Livio Brunner Date: Wed, 29 Aug 2018 14:41:56 +0200 Subject: [PATCH 285/289] Fix VanillaTilt typings Use export default instead of just export --- types/vanilla-tilt/index.d.ts | 153 +++++++++++------------ types/vanilla-tilt/vanilla-tilt-tests.ts | 4 +- 2 files changed, 76 insertions(+), 81 deletions(-) diff --git a/types/vanilla-tilt/index.d.ts b/types/vanilla-tilt/index.d.ts index 5f4c80a783..a3e11c8ebe 100644 --- a/types/vanilla-tilt/index.d.ts +++ b/types/vanilla-tilt/index.d.ts @@ -4,104 +4,99 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). + * Options which configures the tilting */ -export namespace VanillaTilt { +export interface TiltOptions { /** - * Options which configures the tilting + * Reverse the tilt direction */ - interface TiltOptions { - /** - * Reverse the tilt direction - */ - reverse?: boolean; - /** - * Max tilt rotation (degrees) - */ - max?: number; - /** - * Transform perspective, the lower the more extreme the tilt gets. - */ - perspective?: number; - /** - * 2 = 200%, 1.5 = 150%, etc.. - */ - scale?: number; - /** - * Speed of the enter/exit transition - */ - speed?: number; - /** - * Set a transition on enter/exit. - */ - transition?: boolean; - /** - * What axis should be disabled. Can be X or Y. - */ - axis?: null | "x" | "y"; - /** - * If the tilt effect has to be reset on exit. - */ - reset?: boolean; - /** - * Easing on enter/exit. - */ - easing?: string; - /** - * if it should have a "glare" effect - */ - glare?: boolean; - /** - * the maximum "glare" opacity - */ - "max-glare"?: number; - /** - * false = VanillaTilt creates the glare elements for you, otherwise - * you need to add .js-tilt-glare>.js-tilt-glare-inner by yourself - */ - "glare-prerender"?: boolean; - } + reverse?: boolean; + /** + * Max tilt rotation (degrees) + */ + max?: number; + /** + * Transform perspective, the lower the more extreme the tilt gets. + */ + perspective?: number; + /** + * 2 = 200%, 1.5 = 150%, etc.. + */ + scale?: number; + /** + * Speed of the enter/exit transition + */ + speed?: number; + /** + * Set a transition on enter/exit. + */ + transition?: boolean; + /** + * What axis should be disabled. Can be X or Y. + */ + axis?: null | "x" | "y"; + /** + * If the tilt effect has to be reset on exit. + */ + reset?: boolean; + /** + * Easing on enter/exit. + */ + easing?: string; + /** + * if it should have a "glare" effect + */ + glare?: boolean; + /** + * the maximum "glare" opacity + */ + "max-glare"?: number; + /** + * false = VanillaTilt creates the glare elements for you, otherwise + * you need to add .js-tilt-glare>.js-tilt-glare-inner by yourself + */ + "glare-prerender"?: boolean; +} - interface TiltValues { - /** - * The current tilt on the X axis - */ - tiltX: number; - /** - * The current tilt on the Y axis - */ - tiltY: number; - /** - * The current percentage on the X axis - */ - percentageX: number; - /** - * The current percentage on the Y axis - */ - percentageY: number; - } +export interface TiltValues { + /** + * The current tilt on the X axis + */ + tiltX: number; + /** + * The current tilt on the Y axis + */ + tiltY: number; + /** + * The current percentage on the X axis + */ + percentageX: number; + /** + * The current percentage on the Y axis + */ + percentageY: number; +} - interface HTMLVanillaTiltElement extends HTMLElement { - vanillaTilt: VanillaTilt; - } +export interface HTMLVanillaTiltElement extends HTMLElement { + vanillaTilt: VanillaTilt; } /** * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). */ -export class VanillaTilt { +export default class VanillaTilt { /** * Creates a new instance of a VanillaTilt element. * @param element The element, which should be a VanillaTilt element * @param settings Settings which configures the element */ - constructor(element: HTMLElement, settings?: VanillaTilt.TiltOptions); + constructor(element: HTMLElement, settings?: TiltOptions); /** * Initializes one or multiple elements * @param elements The element, which should tilt * @param settings Settings, which configures the elements */ - static init(elements: HTMLElement | HTMLElement[], settings?: VanillaTilt.TiltOptions): void; + static init(elements: HTMLElement | HTMLElement[], settings?: TiltOptions): void; /** * Resets the styling */ @@ -109,7 +104,7 @@ export class VanillaTilt { /** * Get values of instance */ - getValues(): VanillaTilt.TiltValues; + getValues(): TiltValues; /** * Destroys the instance and removes the listeners. */ diff --git a/types/vanilla-tilt/vanilla-tilt-tests.ts b/types/vanilla-tilt/vanilla-tilt-tests.ts index 52520dcfcc..4ed9cd9b7c 100644 --- a/types/vanilla-tilt/vanilla-tilt-tests.ts +++ b/types/vanilla-tilt/vanilla-tilt-tests.ts @@ -1,4 +1,4 @@ -import { VanillaTilt } from 'vanilla-tilt'; +import VanillaTilt, { TiltValues } from 'vanilla-tilt'; const element: VanillaTilt = new VanillaTilt(document.createElement('a'), { axis: 'y', @@ -24,7 +24,7 @@ VanillaTilt.init([document.createElement('a')], { axis: null }); -const values: VanillaTilt.TiltValues = element.getValues(); +const values: TiltValues = element.getValues(); values.percentageX; values.percentageY; values.tiltX; From 0dc195e3a79ff8509aa8af1a4d3fa8fe8d307740 Mon Sep 17 00:00:00 2001 From: Wouter van Heeswijk Date: Wed, 29 Aug 2018 14:58:22 +0200 Subject: [PATCH 286/289] Specify return type as ThroughStream --- types/split/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/split/index.d.ts b/types/split/index.d.ts index f4cd33dd5e..a519381b0f 100644 --- a/types/split/index.d.ts +++ b/types/split/index.d.ts @@ -4,13 +4,15 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// - +import { Transform, TransformOptions } from 'stream'; +import { ThroughStream } from 'through'; interface SplitOptions { maxLength: number } -declare function split(matcher?: any, mapper?: any, options?: SplitOptions): any; +declare function split(matcher?: any, mapper?: any, options?: SplitOptions): ThroughStream; export = split; From 8d74e8882bb6c5abfce1d26bdfed06e3ca7d3269 Mon Sep 17 00:00:00 2001 From: Wouter van Heeswijk Date: Wed, 29 Aug 2018 15:10:14 +0200 Subject: [PATCH 287/289] Increase version number for split package --- types/split/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/split/index.d.ts b/types/split/index.d.ts index a519381b0f..00684def37 100644 --- a/types/split/index.d.ts +++ b/types/split/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for split v0.3.3 +// Type definitions for split v1.0.1 // Project: https://github.com/dominictarr/split // Definitions by: Marcin Porębski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 25150ff6b4cf9516aef1a9e7db175d4d7425dff5 Mon Sep 17 00:00:00 2001 From: Wouter van Heeswijk Date: Wed, 29 Aug 2018 15:14:04 +0200 Subject: [PATCH 288/289] Remove unused imports --- types/split/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/split/index.d.ts b/types/split/index.d.ts index 00684def37..abe4d616ba 100644 --- a/types/split/index.d.ts +++ b/types/split/index.d.ts @@ -6,7 +6,6 @@ /// /// -import { Transform, TransformOptions } from 'stream'; import { ThroughStream } from 'through'; interface SplitOptions { From ec6a6ef2993633715acd565eda674c6a629fe7d0 Mon Sep 17 00:00:00 2001 From: 3af <33279089+3af@users.noreply.github.com> Date: Wed, 29 Aug 2018 20:56:21 +0200 Subject: [PATCH 289/289] papaparse - add trimHeaders and transform ParseConfig options (#28501) * [papaparse]: Add trimHeaders (#28202) and transform options trimHeaders was added in 4.4.0, transform in 4.5.0 * [papaparse]: Add cursor to ParseMeta --- types/papaparse/index.d.ts | 4 ++++ types/papaparse/papaparse-tests.ts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index bbd75e9e61..de820c771f 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -6,6 +6,7 @@ // John Reilly // Alberto Restifo // Behind The Math +// 3af // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -93,6 +94,7 @@ export interface ParseConfig { newline?: string; // default: "\r\n" quoteChar?: string; // default: '"' header?: boolean; // default: false + trimHeaders?: boolean; // default: false dynamicTyping?: boolean; // default: false preview?: number; // default: 0 encoding?: string; // default: "" @@ -109,6 +111,7 @@ export interface ParseConfig { error?(error: ParseError, file?: File): void; // default: undefined chunk?(results: ParseResult, parser: Parser): void; // default: undefined beforeFirstChunk?(chunk: string): string | void; // default: undefined + transform?(value: string, field: string | number): any; // default: undefined } export interface UnparseConfig { @@ -138,6 +141,7 @@ export interface ParseMeta { aborted: boolean; // Whether process was aborted fields: Array; // Array of field names truncated: boolean; // Whether preview consumed all input + cursor: number; } /** diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 5edcf9a251..5db22091ca 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -20,6 +20,7 @@ res.errors[0].code; Papa.parse("3,3,3", { delimiter: ';', comments: false, + trimHeaders: false, step: function (results, p) { p.abort(); @@ -30,6 +31,9 @@ Papa.parse("3,3,3", { var file = new File(null, null, null); Papa.parse(file, { + transform: function(value, field) { + + }, complete: function (a, b) { a.meta.fields; b.name;