diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 86b77f8c6b..2d28d19f8c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1104,6 +1104,7 @@ /types/ffprobe-static/ @iamstevetran /types/fhir-js-client/ @rmchndrng /types/fibers/ @soywiz +/types/fibjs/ @richardo2016 /types/figures/ @BendingBender /types/file-exists/ @BendingBender /types/file-saver/ @cyrilschumacher @DaIgeb @chrismbarr @@ -3383,7 +3384,7 @@ /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @sirreal @iplus26 @KurtPreston +/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston /types/react-lazyload/ @m0a /types/react-leaflet/ @danzel @davschne @yuit /types/react-list/ @buptyyf @tomshen diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 828aab87c2..7faa5da4f8 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -832,8 +832,9 @@ declare namespace AceAjax { /** * [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft} + * @param scrollLeft The new scroll left value **/ - setScrollLeft(): void; + setScrollLeft(scrollLeft: number): void; /** * [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft} diff --git a/types/ace/test/edit_session.ts b/types/ace/test/edit_session.ts index 4713495f7a..29b3bb6bd8 100644 --- a/types/ace/test/edit_session.ts +++ b/types/ace/test/edit_session.ts @@ -18,6 +18,23 @@ function createFoldTestSession() { return session; } +function createScrollTestRenderer(): AceAjax.VirtualRenderer | null { + var el = document.createElement("div"); + + if (!el.getBoundingClientRect) { + console.log("Skipping test: This test only runs in the browser"); + return null; + } + + el.style.left = "20px"; + el.style.top = "30px"; + el.style.width = "300px"; + el.style.height = "100px"; + document.body.appendChild(el); + + return new AceAjax.VirtualRenderer(el); +} + function assertArray(a, b) { assert.equal(a + "", b + ""); assert.ok(a.length == b.length); @@ -915,5 +932,25 @@ const aceEditSessionTests = { session = new AceAjax.EditSession(new Array(30).join("\n")); session.documentToScreenPosition(2, 0); session.documentToScreenPosition(2, 0); + }, + + "test setScrollTop()": function() { + var renderer = createScrollTestRenderer(); + var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]); + renderer.setSession(session); + assert.equal(renderer.getScrollTop(), 0); + session.setScrollTop(40); + assert.equal(renderer.getScrollTop(), 40); + renderer.getScrollTop() + }, + + "test setScrollLeft()": function() { + var renderer = createScrollTestRenderer(); + var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]); + renderer.setSession(session); + assert.equal(renderer.getScrollLeft(), 0); + session.setScrollLeft(40); + assert.equal(renderer.getScrollLeft(), 40); + renderer.getScrollLeft() } -}; \ No newline at end of file +}; diff --git a/types/bencode/bencode-tests.ts b/types/bencode/bencode-tests.ts new file mode 100644 index 0000000000..f6ad3c8292 --- /dev/null +++ b/types/bencode/bencode-tests.ts @@ -0,0 +1,6 @@ +import * as bencode from "bencode"; + +bencode.byteLength("abcde"); // $ExpectType number +bencode.encodingLength("abcde"); // $ExpectType number +bencode.encode([1, 2, 3, 4], new Buffer([]), 1); // $ExpectType Buffer +bencode.decode(new Buffer("abcde"), 1, 3); // $ExpectType any diff --git a/types/bencode/index.d.ts b/types/bencode/index.d.ts new file mode 100644 index 0000000000..444513192c --- /dev/null +++ b/types/bencode/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for bencode 2.0 +// Project: https://github.com/themasch/node-bencode#readme +// Definitions by: Tobenna +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function byteLength(value: any): number; +export function encodingLength(value: any): number; +export function encode(data: any, buffer?: Buffer, offset?: number): Buffer; +export function decode( + data: Buffer, + start?: number, + end?: number, + encoding?: string +): any; diff --git a/types/bencode/tsconfig.json b/types/bencode/tsconfig.json new file mode 100644 index 0000000000..47220efa5a --- /dev/null +++ b/types/bencode/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", + "bencode-tests.ts" + ] +} diff --git a/types/bencode/tslint.json b/types/bencode/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bencode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bigi/bigi-tests.ts b/types/bigi/bigi-tests.ts index 0e4822aeb6..23bffb0477 100644 --- a/types/bigi/bigi-tests.ts +++ b/types/bigi/bigi-tests.ts @@ -14,3 +14,6 @@ const b6 = b4.multiply(b5); console.log(b6); // => BigInteger { '0': 420, '1': 0, t: 1, s: 0 } + +console.log(b1.compareTo(b2)); +// => 70 diff --git a/types/bigi/index.d.ts b/types/bigi/index.d.ts index 7b44ff75e4..de849587ac 100644 --- a/types/bigi/index.d.ts +++ b/types/bigi/index.d.ts @@ -23,7 +23,7 @@ declare class bigi { clamp(): void; clearBit(n: number): bigi; clone(): bigi; - compareTo(a: bigi): bigi; + compareTo(a: bigi): number; copyTo(r: any): void; dAddOffset(n: any, w: any): void; dMultiply(n: number): void; diff --git a/types/chance/chance-tests.ts b/types/chance/chance-tests.ts index 00d8752118..238fd97cf3 100644 --- a/types/chance/chance-tests.ts +++ b/types/chance/chance-tests.ts @@ -71,3 +71,18 @@ euro = chance.euro({opt: 'abc'}); let coin = chance.coin(); coin = chance.coin(); + +// Make sure date works with min and max parameters +let date: string|Date = chance.date(); + +let min = new Date(); +let max = new Date(); +date = chance.date({min, max}); + +min = new Date(); +min.setFullYear(new Date().getFullYear() - 15); +max = new Date(); +max.setFullYear(new Date().getFullYear() + 15); +date = chance.date({min, max}); +date = chance.date({min}); +date = chance.date({max}); diff --git a/types/chance/index.d.ts b/types/chance/index.d.ts index 07418e45be..17708acc5a 100644 --- a/types/chance/index.d.ts +++ b/types/chance/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chance 1.0.13 +// Type definitions for Chance 1.0.16 // Project: http://chancejs.com // Definitions by: Chris Bowdon // Brice BERNARD @@ -189,6 +189,8 @@ declare namespace Chance { year?: number; month?: number; day?: number; + min?: Date; + max?: Date; } interface Month { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 8063cf2629..de72e30427 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -12,6 +12,7 @@ // Simon Archer // Ken Elkabany // Slavik Nychkalo +// Francesco Benedetto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -483,7 +484,7 @@ declare namespace Chart { pointHoverBackgroundColor?: ChartColor | ChartColor[]; pointHoverBorderColor?: ChartColor | ChartColor[]; pointHoverBorderWidth?: number | number[]; - pointStyle?: PointStyle | HTMLImageElement | Array; + pointStyle?: PointStyle | HTMLImageElement | HTMLCanvasElement | Array; xAxisID?: string; yAxisID?: string; type?: string; @@ -517,6 +518,7 @@ declare namespace Chart { barThickness?: number; maxBarThickness?: number; scaleLabel?: ScaleTitleOptions; + time?: TimeScale; offset?: boolean; beforeUpdate?(scale?: any): void; beforeSetDimension?(scale?: any): void; @@ -538,7 +540,6 @@ declare namespace Chart { categoryPercentage?: number; barPercentage?: number; distribution?: 'linear' | 'series'; - time?: TimeScale; } // tslint:disable-next-line no-empty-interface diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 957c409a4f..a1713aa6f9 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,25 +1,30 @@ // 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 +// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/// +/// -/////////////// -// WebView ref: https://chromium.googlesource.com/chromium/src/+/68.0.3432.1/chrome/common/extensions/api/webview_tag.json -/////////////// +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// WebView ref // +// https://chromium.googlesource.com/chromium/src/+/68.0.3432.1/chrome/common/extensions/api/webview_tag.json // +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// -// Accessibility Features -//////////////////// -/** - * 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. - * @since Availability: Since Chrome 37. - * 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. - */ declare namespace chrome { + //////////////////// + // Accessibility Features + //////////////////// + /** + * 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). */ @@ -36,7 +41,7 @@ declare namespace chrome { * • controllable_by_this_extension: can be controlled by this extension * • controlled_by_this_extension: controlled by this extension */ - levelOfControl: string; + 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. */ incognitoSpecific?: boolean; } @@ -55,7 +60,7 @@ declare namespace chrome { * • 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?: string; + scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; } interface AccessibilityFeaturesClearArg { @@ -67,7 +72,7 @@ declare namespace chrome { * • 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?: string; + scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; } interface AccessibilityFeaturesSetting { @@ -96,13 +101,63 @@ declare namespace chrome { clear(details: AccessibilityFeaturesClearArg, callback?: () => void): void; } + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. + * @since Since Chrome 42. + */ export var animationPolicy: AccessibilityFeaturesSetting; } @@ -111,8 +166,8 @@ declare namespace chrome { //////////////////// /** * Use the chrome.alarms API to schedule code to run periodically or at a specified time in the future. - * Availability: Since Chrome 22. - * Permissions: "alarms" + * Permissions: 'alarms' + * @since Availability: Since Chrome 22. */ namespace alarms { interface AlarmCreateInfo { @@ -137,14 +192,19 @@ declare namespace chrome { /** * 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. - * 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. + * 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. * @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; /** - * 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. - * 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. + * 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. + * 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. * @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. @@ -153,39 +213,39 @@ declare namespace chrome { /** * Gets an array of all the alarms. * @param callback The callback parameter should be a function that looks like this: - * function(array of Alarm alarms) {...}; + * @example function(array of Alarm alarms) {...}; */ export 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: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export 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: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export 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: - * function(boolean wasCleared) {...}; + * @example function(boolean wasCleared) {...}; */ export 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: - * function( Alarm alarm) {...}; + * @example function( Alarm alarm) {...}; */ export 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: - * function( Alarm alarm) {...}; + * @example function( Alarm alarm) {...}; */ export function get(name: string, callback: (alarm: Alarm) => void): void; @@ -193,54 +253,125 @@ declare namespace chrome { export var onAlarm: AlarmEvent; } - - //////////////////// - // App - //////////////////// - namespace app { - interface AppDetails extends chrome.runtime.Manifest { - id: string; - } - - export function getDetails(): AppDetails; - } - //////////////////// // 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. + */ 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'; + interface EmbedRequest { + /** + * 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; + } + + type actionType = 'new_note'; + interface LaunchData { + /** + * The ID of the file or URL handler that the app is being invoked with. + * Handler IDs are the top-level keys in the file_handlers and/or url_handlers dictionaries in the manifest. + */ id?: string; + /** + * The file entries for the onLaunched event triggered by a matching file handler in the file_handlers manifest key. + */ items?: LaunchDataItem[]; + /** + * The URL for the onLaunched event triggered by a matching URL handler in the url_handlers manifest key. + */ url?: string; + /** + * The referrer URL for the onLaunched event triggered by a matching URL handler in the url_handlers manifest key. + */ referrerUrl?: string; + /** + * Whether the app is being launched in a Chrome OS kiosk session. + */ isKioskSession?: boolean; + /** + * Whether the app is being launched in a Chrome OS public session. + * @since Since Chrome 47. + */ isPublicSession?: boolean; + /** + * Where the app is launched from. + */ source?: LaunchSource; - actionData?: {}; + /** + * 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 | + * | | | The user wants to quickly take a new note. | + * |____________________|____________|____________________________________________| + * @since Since Chrome 54. + */ + actionData?: actionType; } interface LaunchDataItem { + /** + * Entry for the item + */ entry: FileEntry; - type: string; + /** + * The MIME type of the file. + */ + type?: string; } + interface EmbedRequestedEvent extends chrome.events.Event<(request: EmbedRequest) => void> { } + interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> { } interface RestartedEvent extends chrome.events.Event<() => void> { } + /** + * Fired when an embedding app requests to embed this app. This event is only available on dev channel with the flag --enable-app-view. + * @since Since Chrome 38. + */ + export var onEmbedRequest: EmbedRequestedEvent; + /** + * Fired when an app is launched from the launcher. + */ export 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; } //////////////////// // App Window //////////////////// + /** + * 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 { left?: number; @@ -250,114 +381,327 @@ declare namespace chrome { } interface BoundsSpecification { + /** The X coordinate of the content or window. */ left?: number; + /** The Y coordinate of the content or window. */ top?: number; + /** The width of the content or window. */ width?: number; + /** The height of the content or window. */ height?: number; + /** The minimum width of the content or window. */ minWidth?: number; + /** The minimum height of the content or window. */ minHeight?: number; + /** The maximum width of the content or window. */ maxWidth?: number; + /** The maximum height of the content or window. */ maxHeight?: number; } interface Bounds { + /** This property can be used to read or write the current X coordinate of the content or window. */ left: number; + /** This property can be used to read or write the current Y coordinate of the content or window. */ top: number; + /** This property can be used to read or write the current width of the content or window. */ width: number; + /** This property can be used to read or write the current height of the content or window. */ height: number; - minWidth?: number; - minHeight?: number; - maxWidth?: number; - maxHeight?: number; + /** 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; + /** 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; + /** 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; + /** 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; + /** Set the left and top position of the content or window. */ setPosition(left: number, top: number): void; + /** Set the width and height of the content or window. */ setSize(width: number, height: number): void; - setMinimumSize(minWidth: number, minHeight: number): void; - setMaximumSize(maxWidth: number, maxHeight: number): 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; + /** + * 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; } interface FrameOptions { - type?: string; + /** + * Frame type: none or chrome (defaults to 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: 'none'; + } + interface FrameOptionsChrome { + /** + * Frame type: none or chrome (defaults to 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'; + /** + * 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. + */ color?: string; + /** + * Allows the frame color of the window when active to be set. Frame coloring is only available if the frame type is chrome. + * Frame coloring is only available if the frame type is chrome. + * @since Frame coloring is new in Chrome 36. + */ activeColor?: string; + /** + * Allows the frame color of the window when inactive to be set differently to the active color. Frame coloring is only available if the frame type is chrome. + * inactiveColor must be used in conjunction with color. + * @since Frame coloring is new in Chrome 36. + */ inactiveColor?: string; } interface CreateWindowOptions { + /** + * Id to identify the window. + * + * This will be used to remember the size and position of the window and restore that geometry when a window with the same id is later opened. + * If a window with a given id is created while another window with the same id already exists, + * the currently opened window will be focused instead of creating a new window. + */ id?: string; + /** + * Used to specify the initial position, initial size and constraints of the window's content (excluding window decorations). + * If an id is also specified and a window with a matching id has been shown before, the remembered bounds will be used instead. + * Note that the padding between the inner and outer bounds is determined by the OS. + * Therefore setting the same bounds property for both the innerBounds and outerBounds will result in an error. + * @since This property is new in Chrome 36. + */ innerBounds?: BoundsSpecification; + /** + * Used to specify the initial position, initial size and constraints of the window (including window decorations such as the title bar and frame). + * If an id is also specified and a window with a matching id has been shown before, the remembered bounds will be used instead. + * Note that the padding between the inner and outer bounds is determined by the OS. + * Therefore setting the same bounds property for both the innerBounds and outerBounds will result in an error. + * @since This property is new in Chrome 36. + */ outerBounds?: BoundsSpecification; + /** + * Minimum width of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ minWidth?: number; + /** + * Minimum height of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ minHeight?: number; + /** + * Maximum width of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ maxWidth?: number; + /** + * Maximum height of the window. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ maxHeight?: number; + /** Type of window to create */ + type?: 'shell'; /** - * @description - * @type {(string | FrameOptions)} string ("none", "chrome") or FrameOptions - * @memberof CreateWindowOptions + * 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. + * @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. + * @since Since Chrome 54. + */ + icon?: string; + /** + * Frame type: none or chrome (defaults to 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. + * @since Use of FrameOptions is new in M36. + */ + frame?: 'none' | 'chrome' | FrameOptions | FrameOptionsChrome; + /** + * 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, + * the remembered bounds of the window will be used instead. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ - frame?: string | FrameOptions; bounds?: ContentBounds; - alphaEnabled?: boolean; /** - * @description - * @type {string} "normal", "fullscreen", "maximized", "minimized" - * @memberof CreateWindowOptions + * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. + */ + state?: 'normal' | 'fullscreen' | 'maximized' | 'minimized'; + /** + * 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. */ - state?: string; hidden?: boolean; + /** + * If true, the window will be resizable by the user. Defaults to true. + */ resizable?: boolean; + /** + * @deprecated Deprecated since Chrome 34. Multiple windows with the same id is no longer supported. + * By default if you specify an id for the window, + * the window will only be created if another window with the same id doesn't already exist. + * If a window with the same id already exists that window is activated instead. + * If you do want to create multiple windows with the same id, you can set this property to false. + */ singleton?: boolean; + /** + * 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. + */ alwaysOnTop?: boolean; + /** If true, the window will be focused when created. Defaults to true. */ focused?: boolean; + /** + * If true, and supported by the platform, the window will be visible on all workspaces. + * @since Since Chrome 39. + */ visibleOnAllWorkspaces?: boolean; } interface AppWindow { + /** Focus the window. */ focus: () => void; + /** + * Fullscreens the window. + * The user will be able to restore the window by pressing ESC. + * An application can prevent the fullscreen state to be left when ESC is pressed by requesting the + * app.window.fullscreen.overrideEsc permission and canceling the event by calling .preventDefault(), + * in the keydown and keyup handlers, like this: + * @example window.onkeydown = window.onkeyup = function(e) { if (e.keyCode == 27 <<--``ESC``) { e.preventDefault(); } + * Note window.fullscreen() will cause the entire window to become fullscreen and does not require a user gesture. + * The HTML5 fullscreen API can also be used to enter fullscreen mode(see Web APIs for more details). + **/ fullscreen: () => void; + /** Is the window fullscreen? This will be true if the window has been created fullscreen or was made fullscreen via the AppWindow or HTML5 fullscreen APIs. */ isFullscreen: () => boolean; + /** Minimize the window. */ minimize: () => void; + /** Is the window minimized? */ isMinimized: () => boolean; + /** Maximize the window. */ maximize: () => void; + /** Is the window maximized? */ isMaximized: () => boolean; + /** Restore the window, exiting a maximized, minimized, or fullscreen state. */ restore: () => void; + /** + * Move the window to the position (|left|, |top|). + * @deprecated Deprecated since Chrome 43. Use outerBounds. + */ moveTo: (left: number, top: number) => void; + /** + * Resize the window to |width|x|height| pixels in size. + * @deprecated Deprecated since Chrome 43. Use outerBounds. + */ resizeTo: (width: number, height: number) => void; + /** Draw attention to the window. */ drawAttention: () => void; + /** Clear attention to the window. */ clearAttention: () => void; + /** Close the window. */ close: () => void; - show: () => void; + /** Show the window. Does nothing if the window is already visible. Focus the window if |focused| is set to true or omitted. */ + show: (focused?: boolean) => void; + /** Hide the window. Does nothing if the window is already hidden. */ hide: () => void; + /** + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + * @description Get the window's inner bounds as a ContentBounds object. + */ getBounds: () => ContentBounds; + /** + * Set the window's inner bounds. + * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. + */ setBounds: (bounds: ContentBounds) => void; + /** Is the window always on top? */ isAlwaysOnTop: () => boolean; + /** Set whether the window should stay above most other windows. Requires the alwaysOnTopWindows permission. */ setAlwaysOnTop: (alwaysOnTop: boolean) => void; + /** Set whether the window is visible on all workspaces. (Only for platforms that support this). */ setVisibleOnAllWorkspaces: (alwaysVisible: boolean) => void; + /** The JavaScript 'window' object for the created child. */ contentWindow: Window; + /** The id the window was created with. */ id: string; + /** + * The position, size and constraints of the window's content, which does not include window decorations. + * @since This property is new in Chrome 36. + * */ innerBounds: Bounds; + /** + * The position, size and constraints of the window, which includes window decorations, such as the title bar and frame. + * @since This property is new in Chrome 36. + */ outerBounds: Bounds; + + + /** Fired when the window is resized. */ onBoundsChanged: WindowEvent; + /** + * Fired when the window is closed. + * Note, this should be listened to from a window other than the window being closed, for example from the background page. + * This is because the window being closed will be in the process of being torn down when the event is fired, + * which means not all APIs in the window's script context will be functional. + */ onClosed: WindowEvent; + /** Fired when the window is fullscreened (either via the AppWindow or HTML5 APIs). */ onFullscreened: WindowEvent; + /** Fired when the window is maximized. */ onMaximized: WindowEvent; + /** Fired when the window is minimized. */ onMinimized: WindowEvent; + /** Fired when the window is restored from being minimized or maximized. */ onRestored: WindowEvent; } - - export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; - export function current(): AppWindow; - export function get(id: string): AppWindow; - export function getAll(): AppWindow[]; - export function canSetVisibleOnAllWorkspaces(): boolean; - interface WindowEvent extends chrome.events.Event<() => void> { } - - export var onBoundsChanged: WindowEvent; - export var onClosed: WindowEvent; - export var onFullscreened: WindowEvent; - export var onMaximized: WindowEvent; - export var onMinimized: WindowEvent; - export var onRestored: WindowEvent; + /** + * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. + * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). + * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. + * + * @param url + * @param [options] + * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; + */ + export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; + /** + * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). + */ + export function current(): AppWindow; + /** + * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. + */ + export function get(id: string): AppWindow; + /** + * Gets an array of all currently created app windows. This method is new in Chrome 33. + */ + export function getAll(): AppWindow[]; + /** + * Whether the current platform supports windows being visible on all workspaces. + */ + export function canSetVisibleOnAllWorkspaces(): boolean; } @@ -365,8 +709,9 @@ 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 Chrome 59 + * 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. */ namespace audio { export type StreamType = 'INPUT' | 'OUTPUT'; @@ -376,8 +721,8 @@ declare namespace chrome { /** 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"; - /** The user-friendly name (e.g. "USB Microphone"). */ + 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'; + /** The user-friendly name (e.g. 'USB Microphone'). */ displayName: string; /** Device name. */ deviceName: string; @@ -443,15 +788,15 @@ declare namespace chrome { addListener(callback: (devices: AudioDeviceInfo[]) => void): void; } /** - * @description 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. + * 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. */ interface Filter { /** - * @description If set, only audio devices whose stream type is included in this list will satisfy the filter. + * If set, only audio devices whose stream type is included in this list will satisfy the filter. */ streamTypes?: StreamType[]; /** - * @description If set, only audio devices whose active state matches this value will satisfy the filter. + * If set, only audio devices whose active state matches this value will satisfy the filter. */ isActive?: boolean; } @@ -490,42 +835,68 @@ declare namespace chrome { //////////////////// /** * Use the chrome.bluetooth API to connect to a Bluetooth device. All functions report failures via chrome.runtime.lastError. - * Manifest: "bluetooth": {...} + * Manifest: 'bluetooth': {...} * @since Chrome 37 */ namespace bluetooth { interface AdapterState { + /** The address of the adapter, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; + /** The human-readable name of the adapter. */ name: string; + /** Indicates whether or not the adapter has power. */ powered: boolean; + /** Indicates whether or not the adapter is available (i.e. enabled). */ available: boolean; + /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } interface Device { + /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; + /** 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; + /** The Device ID record of the device, where available. */ vendorIdSource?: 'bluetooth' | 'usb'; vendorId?: number; productId?: number; deviceId?: number; - type?: "computer" | "phone" | "modem" | "audio" | "carAudio" | "video" | "peripheral" | "joystick" | "gamepad" | "keyboard" | "mouse" | "tablet" | "keyboardMouseCombo"; + /** + * 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. + * When in doubt you should use the |deviceClass| field directly. + */ + type?: 'computer' | 'phone' | 'modem' | 'audio' | 'carAudio' | 'video' | 'peripheral' | 'joystick' | 'gamepad' | 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + /** Indicates whether or not the device is paired with the system. */ paired?: boolean; + /** Indicates whether the device is currently connected to the system. */ connected?: boolean; /** + * Indicates whether the device is currently connecting to the system. * @since Chrome 48 */ connecting?: boolean; /** + * Indicates whether the device is connectable. * @since Chrome 48 */ connectable?: boolean; + /** + * UUIDs of protocols, profiles and services advertised by the device. + * For classic Bluetooth devices, this list is obtained from EIR data and SDP tables. + * For Low Energy devices, this list is obtained from AD and GATT primary services. + * For dual mode devices this may be obtained from both. + */ 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. * @since Chrome 44 */ inquiryRssi: number; /** + * 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; @@ -572,25 +943,438 @@ declare namespace chrome { } /** * The chrome.bluetoothLowEnergy API is used to communicate with Bluetooth Smart (Low Energy) devices using the Generic Attribute Profile (GATT). - * Manifest: "bluetooth": {...} + * 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. */ namespace bluetoothLowEnergy { + interface Service { + /** The UUID of the service, e.g. 0000180d-0000-1000-8000-00805f9b34fb. */ + uuid: string; + /** Indicates whether the type of this service is primary or secondary. */ + isPrimary: boolean; + /** + * Returns the identifier assigned to this service. + * Use the instance ID to distinguish between services from a peripheral with the same UUID and to make function calls that take in a service identifier. + * Present, if this instance represents a remote service. + **/ + instanceId?: string; + /** + * The device address of the remote peripheral that the GATT service belongs to. + * Present, if this instance represents a remote service. + */ + deviceAddress?: string; + } + enum 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; + /** The GATT service this characteristic belongs to. */ + service?: Service; + /** The properties of this characteristic. */ + properties: CharacteristicProperties[]; + /** Returns the identifier assigned to this characteristic. Use the instance ID to distinguish between characteristics from a peripheral with the same UUID and to make function calls that take in a characteristic identifier. Present, if this instance represents a remote characteristic. */ + instanceId?: string; + /** 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' + } + interface Descriptor { + /** The UUID of the characteristic descriptor, e.g. 00002902-0000-1000-8000-00805f9b34fb. */ + uuid: string; + /** The GATT characteristic this descriptor belongs to. */ + characteristic?: Characteristic; + /** + * The permissions of this descriptor. + * @since Since Chrome 52. + */ + permissions: DescriptorPermissions[]; + /** Returns the identifier assigned to this descriptor. Use the instance ID to distinguish between descriptors from a peripheral with the same UUID and to make function calls that take in a descriptor identifier. Present, if this instance represents a remote characteristic. */ + instanceId?: string; + /** The currently cached descriptor value. This value gets updated when the value of the descriptor is read. */ + value?: ArrayBuffer; + } + interface RequestDevice { + /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ + address: string; + /** The human-readable name of the device. */ + name?: string; + /** 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; + } + interface Request { + /** Unique ID for this request. Use this ID when responding to this request. */ + requestId: number; + /** Device that send this request. */ + device: RequestDevice; + /** Value to write (if this is a write request). */ + value?: ArrayBuffer; + } + interface IProperties { + /** + * Flag indicating whether a connection to the device is left open when the event page of the application is unloaded. The default value is false. + * @see [HowToManageAppLifecycle]{@link https://developer.chrome.com/apps/app_lifecycle} + * @default false + */ + persistent: boolean; + } + interface INotification { + /** New value of the characteristic. */ + value: ArrayBuffer; + /** Optional flag for sending an indication instead of a notification. */ + shouldIndicate: boolean; + } + enum AdvertisementType { + 'broadcast', 'peripheral' + } + interface Advertisement { + /** Type of advertisement. */ + type: AdvertisementType; + /** 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[] }; + /** 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[] }; + } + interface IResponse { + /** Id of the request this is a response to. */ + requestId: number; + /** If this is an error response, this should be true. */ + isError: boolean; + /** Response value. Write requests and error responses will ignore this parameter. */ + value?: ArrayBuffer; + } /** - * NOT IMPLEMENTED YET - * @see https://developer.chrome.com/apps/bluetoothLowEnergy - * */ + * 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. + */ + 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. + */ + function connect(deviceAddress: string, properties: IProperties, callback: () => void): void; + /** + * Closes the app's connection to the device with the given address. Note that this will not always destroy the physical link itself, since there may be other apps with open connections. + * @param deviceAddress The Bluetooth address of the remote device. + * @param [callback] Called when the disconnect request has completed. + */ + function disconnect(deviceAddress: string, callback?: () => void): void; + /** + * 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. + */ + 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. + * @since Since Chrome 52. + * @param service The service to create. + * @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. + */ + 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. + */ + 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. + * @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. + */ + 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. + */ + 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. + */ + 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. + */ + function getDescriptor(descriptorId: string, callback: (result: Descriptor) => void): void; + /** + * Create a locally hosted GATT descriptor. This descriptor must be hosted under a valid characteristic. If the characteristic 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 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. + */ + 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. + */ + 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. + */ + 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. + */ + 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. + */ + function startCharacteristicNotifications(characteristicId: string, 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 properties Notification session properties (optional). + * @param callback Called when the request has completed. + */ + function startCharacteristicNotifications(characteristicId: string, properties: IProperties, callback: () => void): void; + /** + * Disable value notifications/indications from the specified characteristic. After a successful call, the application will stop receiving notifications/indications from this characteristic. + * @param characteristicId The instance ID of the GATT characteristic on which this app's notification session should be stopped. + * @param [callback] Called when the request has completed (optional). + */ + function stopCharacteristicNotifications(characteristicId: string, callback?: () => void): void; + /** + * Notify a remote device of a new value for a characteristic. + * If the shouldIndicate flag in the notification object is true, an indication will be sent instead of a notification. + * Note, the characteristic needs to correctly set the 'notify' or 'indicate' property during creation for this call to succeed. + * 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 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. + */ + 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. + */ + 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. + */ + function writeDescriptorValue(descriptorId: string, value: ArrayBuffer, callback: () => void): void; + /** + * Register the given service with the local GATT server. + * If the service ID is invalid, 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 serviceId Unique ID of a created service. + * @param callback Callback with the result of the register operation. + */ + function registerService(serviceId: string, callback: () => void): void; + /** + * Unregister the given service with the local GATT server. + * If the service ID is invalid, 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 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; + /** + * Remove the specified service, unregistering it if it was registered. + * If the service ID is invalid, 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 serviceId Unique ID of a current registered service. + * @param [callback] Callback called once the service is removed. + */ + function removeService(serviceId: string, callback?: () => void): void; + /** + * Create an advertisement and register it for advertising. + * To call this function, the app must have + * the bluetooth:low_energy and bluetooth:peripheral permissions set to true. + * Additionally this API is only available to auto launched apps in Kiosk Mode + * of by setting the 'enable-ble-advertising-in-apps' flag. + * See https://developer.chrome.com/apps/manifest/bluetooth + * Note: On some hardware, central and peripheral modes at the same time + * is supported but on hardware that doesn't support this, + * making this call will switch the device to peripheral mode. + * In the case of hardware which does not support both central and peripheral mode, + * attempting to use the device in both modes will lead to undefined behavior + * or prevent other central-role applications from behaving correctly + * (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. + */ + function registerAdvertisement(advertisement: Advertisement, callback: (advertisementId: number) => void): void; + /** + * Unregisters an advertisement and stops its advertising. + * If the advertisement fails to unregister the only way + * 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. + */ + 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. + */ + function resetAdvertising(callback: () => void): void; + /** + * 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. + * 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. + * @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. + */ + function setAdvertisingInterval(minInterval: number, maxInterval: number, 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. + * @param response The response to the request. + */ + 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>; + /** + * 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>; + /** Fired when a GATT service that was previously discovered on a remote device has been removed. */ + var 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, + * or a value change notification/indication. + * This event will only be sent if the app has enabled notifications + * by calling startCharacteristicNotifications. + */ + var 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>; + /** + * Fired when a connected central device requests to read the value of + * a characteristic registered on the local GATT server. + * Not responding to this request for a long time may lead to a disconnection. + * This event 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. + */ + var 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. + * Not responding to this request for a long time may lead to a disconnection. + * This event 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. + */ + var 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. + * Not responding to this request for a long time may lead to a disconnection. + * This event 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. + */ + var 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. + * Not responding to this request for a long time may lead to a disconnection. + * This event 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. + */ + var onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; } /** * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. * @since Chrome 37 - * Manifest: "bluetooth": {...} + * Manifest: 'bluetooth': {...} * Important: This API works only on OS X, Windows and Chrome OS. */ namespace bluetoothSocket { - /** NOT IMPLEMENTED YET */ + /* NOT IMPLEMENTED YET */ } //////////////////// @@ -631,7 +1415,7 @@ declare namespace chrome { /** * 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": {...} + * Manifest: 'commands': {...} */ namespace commands { interface Command { @@ -663,17 +1447,17 @@ declare namespace chrome { /** * 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" + * Permissions: 'contextMenus' */ namespace contextMenus { /** * 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"; + export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio' | 'launcher' | 'browser_action' | 'page_action'; /** * The type of menu item. **/ - export type ItemType = "normal" | "checkbox" | "radio" | "separator"; + export type ItemType = 'normal' | 'checkbox' | 'radio' | 'separator'; interface OnClickData { /** @@ -746,7 +1530,7 @@ declare namespace chrome { 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". */ + /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ title?: string; /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ contexts?: string[]; @@ -873,7 +1657,7 @@ declare namespace chrome { /** * Use the chrome.documentScan API to discover and retrieve images from attached paper document scanners. * Availability: Since Chrome 44. - * Permissions: "documentScan" + * Permissions: 'documentScan' * Important: This API works only on Chrome OS. */ namespace documentScan { @@ -885,7 +1669,7 @@ declare namespace chrome { } interface DocumentScanCallbackArg { - /** The data image URLs in a form that can be passed as the "src" value to an image tag. */ + /** The data image URLs in a form that can be passed as the 'src' value to an image tag. */ dataUrls: string[]; /** The MIME type of dataUrls. */ mimeType: string; @@ -1062,13 +1846,13 @@ declare namespace chrome { */ interface ImageDetails { /** - * @description The format of the resulting image. Default is "jpeg". + * @description 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. + * @description When format is 'jpeg', controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. * @type {number} * @memberof ImageDetails */ @@ -1121,13 +1905,13 @@ declare namespace chrome { */ matchAboutBlank?: boolean; /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". + * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. * @type {RunAt} * @memberof InjectDetails */ runAt: RunAt; /** - * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to "author". + * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to 'author'. * @since Since Chrome 66. * @type {CSSOrigin} * @memberof InjectDetails @@ -1139,32 +1923,118 @@ declare namespace chrome { //////////////////// // 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. + */ namespace fileSystem { interface AcceptOptions { + /** + * This is the optional text description for this option. + * If not present, a description will be automatically generated; + * typically containing an expanded list of valid extensions (e.g. 'text/html' may expand to '*.html, *.htm'). + */ description?: string; + /** + * Mime-types to accept, e.g. 'image/jpeg' or 'audio/*'. One of mimeTypes or extensions must contain at least one valid element. + */ mimeTypes?: string[]; + /** + * Extensions to accept, e.g. 'jpg' | 'gif' | 'crx'. + */ extensions?: string[]; } interface ChooseEntryOptions { - type?: string; + /** + * 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?: '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. */ 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[]; + /** + * 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. + */ 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. + */ acceptsMultiple?: boolean; } + type ChildChangeType = 'created' | 'removed' | 'changed'; + + interface Volume { + /** The ID of the requested volume. */ + volumeId: string; + /** Whether the requested file system should be writable. The default is read-only. */ + writable?: boolean; + } + + /** + * 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; + /** + * 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; + /** Gets whether this Entry is writable or not. */ export 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; + /** Ask the user to choose a file or directory. */ export 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; + /** Ask the user to choose a file or directory. */ export function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; + /** Returns the file entry with the given id if it can be restored. This call will fail with a runtime error otherwise. */ export function restoreEntry(id: string, callback: (entry: Entry) => void): void; + /** Returns whether the app has permission to restore the entry with the given id. */ export function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; + /** + * 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; + /** + * 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. + */ + export 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>; } @@ -1174,7 +2044,7 @@ declare namespace chrome { /** * 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" + * Permissions: 'fileSystemProvider' * Important: This API works only on Chrome OS. */ namespace fileSystemProvider { @@ -1204,7 +2074,7 @@ declare namespace chrome { /** File size in bytes. */ size: number; /** The last modified time of this entry. */ - modificationTime: Date; + modificationTime: any; /** Optional. 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. */ @@ -1460,7 +2330,7 @@ declare namespace chrome { /** * 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. + * 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. @@ -1486,7 +2356,7 @@ declare namespace chrome { export var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; /** Raised when deleting an entry is requested. If recursive is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ export var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; - /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the "EXISTS" error code. */ + /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the 'EXISTS' error code. */ export var onCreateFileRequested: FilePathRequestedEvent; /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ export var onCopyEntryRequested: SourceTargetPathRequestedEvent; @@ -1526,9 +2396,17 @@ declare namespace chrome { /** * 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" + * Permissions: 'gcm' */ namespace gcm { + interface IGCMData { + 'collapse_key'?: 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; @@ -1536,13 +2414,15 @@ declare namespace chrome { messageId: string; /** Optional. Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ timeToLive?: number; - /** 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: Object; + /** + * @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. + **/ + data: IGCMData; } interface IncomingMessage { /** The message data. */ - data: Object; + data: IGCMData; /** * Optional. * The sender who issued the message. @@ -1571,7 +2451,7 @@ 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. */ + /** The maximum size (in bytes) of all key/value pairs in a message. Default: 4096 */ export var MAX_MESSAGE_SIZE: number; /** @@ -1629,9 +2509,11 @@ declare namespace chrome { namespace i18n { /** Holds detected ISO language code and its percentage in the input string */ interface DetectedLanguage { - /** 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}. - * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ + /** + * @description An ISO language code such as 'en' or 'fr'. + * @description For a complete list of languages supported by this method: + * @see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}. + * @description For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ language: string; /** The percentage of the detected language */ @@ -1659,7 +2541,7 @@ declare namespace chrome { * @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. */ - export function getMessage(messageName: string, substitutions?: any): string; + export 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. @@ -1678,7 +2560,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.identity API to get OAuth2 access tokens. - * Permissions: "identity" + * Permissions: 'identity' * @since Chrome 29. */ namespace identity { @@ -1697,7 +2579,7 @@ declare namespace chrome { /** * Optional. * 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. + * account is only supported when the 'enable-new-profile-management' flag is set. * @since Chrome 37. */ account?: AccountInfo; @@ -1797,14 +2679,14 @@ declare namespace chrome { //////////////////// /** * Use the chrome.idle API to detect when the machine's idle state changes. - * Permissions: "idle" + * Permissions: 'idle' * @since Chrome 6. */ namespace idle { interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> { } /** - * 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. + * 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: @@ -1818,7 +2700,7 @@ declare namespace chrome { */ export 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. */ + /** 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; } @@ -2071,7 +2953,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.notifications API to create rich notifications using templates and show these notifications to users in the system tray. - * Permissions: "notifications" + * Permissions: 'notifications' * @since Chrome 28. */ namespace notifications { @@ -2307,7 +3189,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.power API to override the system's power management features. - * Permissions: "power" + * Permissions: 'power' * @since Chrome 27. */ namespace power { @@ -2322,7 +3204,7 @@ declare namespace chrome { //////////////////// /** * 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" + * Permissions: 'printerProvider' * @since Chrome 44. */ namespace printerProvider { @@ -2347,7 +3229,7 @@ declare namespace chrome { title: string; /** Print ticket in CJT format. */ ticket: Object; - /** The document content type. Supported formats are "application/pdf" and "image/pwg-raster". */ + /** The document content type. Supported formats are 'application/pdf' and 'image/pwg-raster'. */ contentType: string; /** Blob containing the document data to print. Format must match |contentType|. */ document: Blob; @@ -2400,7 +3282,7 @@ declare namespace chrome { interface InstalledDetails { /** * The reason that this event is being dispatched. - * One of: "install", "update", "chrome_update", or "shared_module_update" + * One of: 'install', 'update', 'chrome_update', or 'shared_module_update' */ reason: string; /** @@ -2452,17 +3334,17 @@ declare namespace chrome { interface PlatformInfo { /** * The operating system chrome is running on. - * One of: "mac", "win", "android", "cros", "linux", or "openbsd" + * One of: 'mac', 'win', 'android', 'cros', 'linux', or 'openbsd' */ os: string; /** * The machine's processor architecture. - * One of: "arm", "x86-32", or "x86-64" + * One of: 'arm', 'x86-32', or 'x86-64' */ arch: string; /** * The native client architecture. This may be different from arch on some platforms. - * One of: "arm", "x86-32", or "x86-64" + * One of: 'arm', 'x86-32', or 'x86-64' */ nacl_arch: string; } @@ -2629,14 +3511,14 @@ declare namespace chrome { 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?: { /** - * 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: - * "requirements": { - * "3D": { - * "features": ["webgl"] + * 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: + * 'requirements': { + * '3D': { + * 'features': ['webgl'] * } * } */ @@ -2644,10 +3526,10 @@ declare namespace chrome { features?: Array; }; /** - * 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 + * 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 * } * } */ @@ -2754,7 +3636,7 @@ 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. 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; @@ -3029,7 +3911,7 @@ declare namespace chrome { interface SocketProperties { /** * Flag indicating if the socket remains open when the event page of the - * application is unloaded. The default value is "false." When 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. * @@ -3051,7 +3933,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". + * default value is 'false'. */ persistent: boolean; @@ -3061,7 +3943,7 @@ declare namespace chrome { /** * Flag indicating 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" + * queue backlog. See setPaused. The default value is 'false' */ paused: boolean; @@ -3203,7 +4085,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. + * found in the 'socket' API. * * @since Chrome 33 * @see https://developer.chrome.com/apps/sockets_udp @@ -3236,7 +4118,7 @@ declare namespace chrome { 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 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 @@ -3343,9 +4225,9 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-bind * @param socketId The socket ID. * @param address The address of the local machine. DNS name, IPv4 and IPv6 - * formats are supported. Use "0.0.0.0" to accept packets + * formats are supported. Use '0.0.0.0' to accept packets * from all local available network interfaces. - * @param port The port of the local machine. Use "0" to bind to a free + * @param port The port of the local machine. Use '0' to bind to a free * port. * @param callback Called when the bind operation completes. */ @@ -3499,7 +4381,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.storage API to store, retrieve, and track changes to user data. - * Permissions: "storage" + * Permissions: 'storage' * @since Chrome 20. */ namespace storage { @@ -3526,7 +4408,7 @@ 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). + * 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. * Callback on success, or on failure (in which case runtime.lastError will be set). */ @@ -3622,7 +4504,7 @@ declare namespace chrome { //////////////////// /** * Use the system.cpu API to query CPU metadata. - * Permissions: "system.cpu" + * Permissions: 'system.cpu' * @since Chrome 32. */ namespace system.cpu { @@ -3651,7 +4533,7 @@ declare namespace chrome { modelName: string; /** * 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". + * The currently supported codes are 'mmx', 'sse', 'sse2', 'sse3', 'ssse3', 'sse4_1', 'sse4_2', and 'avx'. */ features: string[]; /** Information about each logical processor. */ @@ -3667,7 +4549,7 @@ declare namespace chrome { //////////////////// /** * Use the system.display API to query display metadata. - * Permissions: "system.display" + * Permissions: 'system.display' * @since Chrome 30. */ namespace system.display { @@ -3830,7 +4712,7 @@ declare namespace chrome { interface DisplayInfo { /** The unique identifier of the display. */ id: string; - /** The user-friendly name (e.g. "HP LCD monitor"). */ + /** 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. */ mirroringSourceId: string; @@ -4003,7 +4885,7 @@ declare namespace chrome { //////////////////// /** * The chrome.system.memory API. - * Permissions: "system.memory" + * Permissions: 'system.memory' * @since Chrome 32. */ namespace system.memory { @@ -4036,7 +4918,7 @@ 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" + * Permissions: 'system.storage' * @since Chrome 30. */ namespace system.storage { @@ -4092,7 +4974,7 @@ declare namespace chrome { //////////////////// /** * 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. - * Permissions: "tts" + * Permissions: 'tts' * @since Chrome 14. */ namespace tts { @@ -4104,7 +4986,7 @@ declare namespace chrome { 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. - * One of: "start", "end", "word", "sentence", "marker", "interrupted", "cancelled", "error", "pause", or "resume" + * One of: 'start', 'end', 'word', 'sentence', 'marker', 'interrupted', 'cancelled', 'error', 'pause', or 'resume' */ type: string; } @@ -4115,7 +4997,7 @@ declare namespace chrome { lang?: string; /** * Optional. This voice's gender. - * One of: "male", or "female" + * One of: 'male', or 'female' */ gender?: string; /** Optional. The name of the voice. */ @@ -4162,7 +5044,7 @@ declare namespace chrome { extensionId?: string; /** * Optional. Gender of voice for synthesized speech. - * One of: "male", or "female" + * One of: 'male', or 'female' */ gender?: string; /** Optional. The TTS event types the voice must support. */ @@ -4412,7 +5294,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.vpnProvider API to implement a VPN client. - * Permissions: "vpnProvider" + * Permissions: 'vpnProvider' * Important: This API works only on Chrome OS. * @since Chrome 43. */ @@ -4429,7 +5311,7 @@ declare namespace chrome { */ 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[]; /** Optional. A list of search domains. (default: no search domain) */ @@ -4462,7 +5344,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. */ @@ -4499,7 +5381,7 @@ declare namespace chrome { //////////////////// /** * Use the chrome.wallpaper API to change the ChromeOS wallpaper. - * Permissions: "wallpaper" + * Permissions: 'wallpaper' * Important: This API works only on Chrome OS. * @since Chrome 43. */ @@ -4511,7 +5393,7 @@ declare namespace chrome { url?: string; /** * The supported wallpaper layouts. - * One of: "STRETCH", "CENTER", or "CENTER_CROPPED" + * One of: 'STRETCH', 'CENTER', or 'CENTER_CROPPED' */ layout: string; /** The file name of the saved wallpaper. */ @@ -4533,7 +5415,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, 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, and more (see Usage). */ namespace webview { /** Options that determine what data should be cleared by `clearData`. */ @@ -4611,7 +5493,7 @@ declare namespace chrome { */ 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. + * @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 */ @@ -4624,38 +5506,501 @@ declare namespace chrome { file?: string } - interface WebViewElementEventMap { - 'close': Event, - 'consolemessage': IConsolemessage, - 'contentload': Event, - 'dialog': IDialog, - 'exit': IExit, - 'findupdate': IFindupdate, - 'loadabort': ILoadabort, - 'loadcommit': ILoadcommit, - 'loadredirect': ILoadredirect, - 'loadstart': ILoadstart, - 'loadstop': Event, - 'newwindow': INewwindow, - 'permissionrequest': IPermissionrequest, - 'responsive': IResponsive, - 'sizechanged': ISizechanged, - 'unresponsive': IUnresponsive, - 'zoomchange': IZoomchange, - } - - /** - * @description - * @export - * @interface HTMLWebViewElement - * @extends {Element} + * @description WebView element from html */ interface HTMLWebViewElement extends Element { - executeScript?: (details: InjectDetails, callback?: (result: any) => void) => void; + /** + * 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; - contentWindow: Window; - addEventListener(type: K, listener: (this: HTMLWebViewElement, ev: WebViewElementEventMap[K]) => any, useCapture?: boolean): void; + /** + * 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. + */ + 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: IConsoleMessage) => 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: IDialog) => 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * Fired when a load has begun. + */ + addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: ILoadstart) => 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) { + * var newWebview = document.createElement('webview'); + * document.body.appendChild(newWebview); + * e.window.attach(newWebview); + * }); + */ + addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: INewwindow) => 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: IPermissionrequest) => 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; + /** 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; + /** 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; + /** Fired when the page's zoom changes. */ + addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: IZoomchange) => void, useCapture?: boolean): void; + /** + * @description Queries audio state. + */ + getAudioState(callback: (audible: boolean) => void): void; + + /** + * @description Sets audio mute state of the webview. + * @param {boolean} mute Mute audio value + */ + setAudioMuted(mute: boolean): void; + + /** + * @description 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. + */ + captureVisibleRegion(callback: (dataUrl: string) => void): void; + /** + * @description Captures the visible region of the webview. + * @param {*} options + * @param {(dataUrl: string) => void} callback + */ + 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'. + * 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'; + * You can defer addContentScripts call until you needs to inject scripts. + * The following example shows how to overwrite an existing rule. + * + * 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'}]); + * 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. + */ + 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. + */ + 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. + */ + 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. + */ + 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 + */ + 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 + */ + 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 + */ + find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; + + /** + * @description 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. + */ + getProcessId(): void; + + /** + * @description Returns the user agent string used by the webview for guest page requests. + */ + getUserAgent(): void; + + /** + * @description Gets the current zoom factor. + * @param callback + */ + getZoom(callback: (zoomFactor: number) => void): void; + + /** + * @description 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 + */ + 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 + */ + insertCSS(details: InjectDetails, callback?: () => void): void; + + /** + * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). + */ + isUserAgentOverridden(): void; + + /** + * @description 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. + */ + 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. + */ + 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. + */ + 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 + */ + 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 + */ + setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; + + /** + * @description 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. + */ + 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). + */ + 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. + */ + 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';
+            });
+ */ + + 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 + */ + + 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'' });
+            });
+ */ + + 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 + */ + + 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 + */ + + 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 + */ + + 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 + */ + + 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 + */ + + loadcommit: chrome.events.Event; + + /** + * @description Fired when a top-level load request has redirected to a different URL. + * @param callback + */ + + loadredirect: chrome.events.Event; + + /** + * @description Fired when a load has begun. + * @param callback + */ + + loadstart: chrome.events.Event; + + /** + * @description Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.

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

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

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

webview.addEventListener('newwindow', function(e) {
+              var newWebview = document.createElement('webview');
+              document.body.appendChild(newWebview);
+              e.window.attach(newWebview);
+            });
+ * @param callback + */ + + 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 + */ + + 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 + */ + + responsive: chrome.events.Event; + + /** + * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. + * @param callback + */ + + 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 + */ + + unresponsive: chrome.events.Event; + + /** + * @description Fired when the page's zoom changes. + * @param callback + */ + + zoomchange: chrome.events.Event; } /**Options that determine what data should be cleared by clearData. */ @@ -4717,21 +6062,21 @@ declare namespace chrome { /** * 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"; + * '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. */ 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. + * @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. */ code?: string @@ -4787,7 +6132,7 @@ declare namespace chrome { js?: InjectionItems /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". + * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. */ run_at?: chrome.extensionTypes.RunAt; @@ -4820,7 +6165,7 @@ declare namespace chrome { 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". + * @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'. */ title?: string @@ -4836,7 +6181,7 @@ declare namespace chrome { /** * @description A function that will be called back when the menu item is clicked. - * @param {any} [object Object] + * @param callback */ onclick?: (info: any) => void @@ -4885,7 +6230,7 @@ declare namespace chrome { /** * @description A function that will be called back when the menu item is clicked. - * @param {any} [object Object] + * @param callback */ onclick?: (info: any) => void @@ -4914,28 +6259,28 @@ declare namespace chrome { /** * @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 {any} [object Object] + * @param callback */ create(createProperties: object, callback?: () => void): void; /** * @description Updates a previously created context menu item. - * @param {any} id The ID of the item to update. + * @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 {any} [object Object] + * @param callback */ update(id: number | string, updateProperties: object, callback?: () => void): void; /** * @description Removes a context menu item. - * @param {any} menuItemId The ID of the context menu item to remove. - * @param {any} [object Object] + * @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 {any} [object Object] + * @param callback */ removeAll(callback?: () => void): void; @@ -4956,8 +6301,8 @@ 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.

- * @param {any} message Message object to send to the guest. + * @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. */ postMessage(message: any, targetOrigin: string): void; @@ -5118,7 +6463,11 @@ declare namespace chrome { 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.

*/ + /** + * Fescribes 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 { /** @@ -5141,388 +6490,39 @@ declare namespace chrome { */ height: number } - /**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(
-          function(details) { return {cancel: true}; },
-          {urls: ["*://www.evil.com/*"]},
-          ["blocking"]);

Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events. See declarativeWebRequest for API details.

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:

var rule = {
-          conditions: [
-            new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } })
-          ],
-          actions: [ new chrome.webViewRequest.CancelRequest() ]
-        };
-        myWebview.request.onRequest.addRules([rule]);
*/ + /** + * @description Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts.

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

webview.request.onBeforeRequest.addListener(
+         * @example function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
+         * @description Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
+         * @see http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest
+         * @description Note that conditions and actions for declarative webview webRequests should be instantiated from their chrome.webViewRequest.* counterparts. The following example code declaratively blocks all requests to 'example.com' on the webview myWebview:
+         * @example var rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
+         **/
         interface WebRequestEventInterface {
         }
         /**
         * Defines the how zooming is handled in the webview.
         * Enum values:
-        * "per-origin"
+        * '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"
+        * '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"
+        * '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";
-
-        /**
-        * @description Queries audio state.
-        * @param {any} [object Object]
-         */
-        export function getAudioState(callback: (audible: boolean) => void): void;
-
-        /**
-        * @description Sets audio mute state of the webview.
-        * @param {boolean} mute Mute audio value
-         */
-        export function setAudioMuted(mute: boolean): void;
-
-        /**
-        * @description Queries whether audio is muted.
-        * @param {any} [object Object]
-         */
-        export function 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.
-         */
-        export function captureVisibleRegion(callback: (dataUrl: string) => void): void;
-        /**
-         * @description Captures the visible region of the webview.
-         * @param {*} options
-         * @param {(dataUrl: string) => void} callback
-         */
-        export function captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void;
-
-        /**
-        * @description 

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'.

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';

You can defer addContentScripts call until you needs to inject scripts.

The following example shows how to overwrite an existing rule.

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'}]);

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 content scripts documentation for more details.

- * @param {ContentScriptDetails[]} contentScriptList Details of the content scripts to add. - */ - export function 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. - */ - export function 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. - */ - export function 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. - */ - export function canGoForward(): void; - - /** - * @description

Clears browsing data for the webview partition.

- * @param {any} options Options determining which data to clear. - * @param {any} types The types of data to be cleared. - * @param {any} [object Object] - */ - export function 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 {any} details Details of the script to run. - * @param {any} [object Object] - */ - export function 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 {any} options Options for the find request. - * @param {any} [object Object] - */ - export function find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; - - /** - * @description Navigates forward one history entry if possible. Equivalent to go(1). - * @param {any} [object Object] - */ - export function 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. - */ - export function getProcessId(): void; - - /** - * @description Returns the user agent string used by the webview for guest page requests. - */ - export function getUserAgent(): void; - - /** - * @description Gets the current zoom factor. - * @param {any} [object Object] - */ - export function getZoom(callback: (zoomFactor: number) => void): void; - - /** - * @description Gets the current zoom mode. - * @param {any} [object Object] - */ - export function 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 {any} [object Object] - */ - export function go(relativeIndex: number, callback?: (success: boolean) => void): void; - - /** - * @description Injects CSS into the guest page. - * @param {any} details Details of the CSS to insert. - * @param {any} [object Object] - */ - export function insertCSS(details: InjectDetails, callback?: () => void): void; - - /** - * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). - */ - export function isUserAgentOverridden(): void; - - /** - * @description Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. - */ - export function print(): void; - - /** - * @description Reloads the current top-level page. - */ - export function reload(): void; - - /** - * @description

Removes content scripts from a webview.

The following example removes "myRule" which was added before.

webview.removeContentScripts(['myRule']);

You can remove all the rules by calling:

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. - */ - export function 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. - */ - export function 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 {any} [object Object] - */ - export function setZoom(zoomFactor: number, callback?: () => void): void; - - /** - * @description Sets the zoom mode of the webview. - * @param {any} ZoomMode Defines how zooming is handled in the webview. - * @param {any} [object Object] - */ - export function setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; - - /** - * @description Stops loading the current webview navigation if in progress. - */ - export function 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. - */ - export function 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). - */ - export function 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. - */ - export function 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';
-        });
- */ - - export function 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 {any} [object Object] - */ - - export var 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"' });
-        });
- */ - - export var 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var loadcommit: chrome.events.Event; - - /** - * @description Fired when a top-level load request has redirected to a different URL. - * @param {any} [object Object] - */ - - export var loadredirect: chrome.events.Event; - - /** - * @description Fired when a load has begun. - * @param {any} [object Object] - */ - - export var 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.

- */ - - export function 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var responsive: chrome.events.Event; - - /** - * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. - * @param {any} [object Object] - */ - - export var 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 {any} [object Object] - */ - - export var unresponsive: chrome.events.Event; - - /** - * @description Fired when the page's zoom changes. - * @param {any} [object Object] - */ - - export var zoomchange: chrome.events.Event; - /**IConsolemessage (Auto generated interface) */ - interface IConsolemessage { + export type ZoomMode = 'per-origin' | 'per-view' | 'disabled'; + + export enum ConsoleMessageLevel { + LOG_VERBOSE = -1, + LOG_INFO = 0, + LOG_WARNING = 1, + LOG_ERROR = 2 + } + interface IConsoleMessage { /** * @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. */ - level: number + level: ConsoleMessageLevel; /** * @description The logged message contents. @@ -5539,7 +6539,6 @@ declare namespace chrome { */ sourceId: string } - /**IDialog (Auto generated interface) */ interface IDialog { /** @@ -5557,7 +6556,6 @@ declare namespace chrome { */ dialog: DialogController } - /**IExit (Auto generated interface) */ interface IExit { /** @@ -5570,7 +6568,6 @@ declare namespace chrome { */ reason: 'normal' | 'abnormal' | 'crash' | 'kill' } - /**IFindupdate (Auto generated interface) */ interface IFindupdate { /** @@ -5603,7 +6600,6 @@ declare namespace chrome { */ finalUpdate: string } - /**ILoadabort (Auto generated interface) */ interface ILoadabort { /** @@ -5626,7 +6622,6 @@ declare namespace chrome { */ 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' } - /**ILoadcommit (Auto generated interface) */ interface ILoadcommit { /** @@ -5703,7 +6698,6 @@ declare namespace chrome { */ windowOpenDisposition: 'ignore' | 'save_to_disk' | 'current_tab' | 'new_background_tab' | 'new_foreground_tab' | 'new_window' | 'new_popup' } - /**IPermissionrequest (Auto generated interface) */ interface IPermissionrequest { /** @@ -5714,8 +6708,9 @@ declare namespace chrome { /** * @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: object + request: GeolocationPermissionRequest | PointerLockPermissionRequest | DownloadPermissionRequest | LoadPluginPermissionRequest | FullscreenPermissionRequest; } + /**IResponsive (Auto generated interface) */ interface IResponsive { diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index f976fc57b4..c0dc6402a6 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1,7 +1,7 @@ import runtime = chrome.app.runtime; import cwindow = chrome.app.window; -var createOptions: cwindow.CreateWindowOptions = { +const createOptions: cwindow.CreateWindowOptions = { id: "My Window", bounds: { left: 0, @@ -324,5 +324,40 @@ function testSystemNetwork() { }); } -import webview = chrome.webview; -let element: webview.HTMLWebViewElement; +const gcmMessage = {}; +gcmMessage.data = { + /*goog: 'any', should not be allowed, and it is not :) */ + 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 === chrome.webview.ConsoleMessageLevel.LOG_ERROR) { + 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.bluetoothLowEnergy.connect('1111111', () => { }); diff --git a/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts b/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts new file mode 100644 index 0000000000..c46d48d563 --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/com.wikitude.phonegap.wikitudeplugin-tests.ts @@ -0,0 +1,33 @@ +const startupConfiguration: any = { camera_position: 'back' }; + +// Some code samples from the wikitude ionic starter +WikitudePlugin.loadARchitectWorld( + success => { + console.log('ARchitect World loaded successfully.'); + }, + fail => { + console.log('Failed to load ARchitect World!'); + }, + 'www/assets/07_3dModels_6_3dModelAtGeoLocation/index.html', + ['geo'], + startupConfiguration +); + +WikitudePlugin.setOnUrlInvokeCallback(url => { + if (url.indexOf('captureScreen') > -1) { + WikitudePlugin.captureScreen( + absoluteFilePath => { + WikitudePlugin.callJavaScript( + `World.testFunction('Screenshot saved at: ${absoluteFilePath}');` + ); + }, + errorMessage => { + console.log(errorMessage); + }, + true, + null + ); + } else { + alert(url + 'not handled'); + } +}); diff --git a/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts b/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts new file mode 100644 index 0000000000..50307d57c8 --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for com.wikitude.phonegap.wikitudeplugin 7.2 +// Project: https://github.com/Wikitude/wikitude-cordova-plugin +// Definitions by: zbarbuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// The following types are taken directly (unmodified) from the wikitude-ionic-3-starter-app +// https://github.com/pbreuss/wikitude-ionic-3-starter-app +// Latest commit at time of writing was 647cd546f6d1805765c4cee725566e246ca6259d + +/** + * Wrapper for the Wikitude SDK Phonegap Plugin - to use with IONIC2 + * (c) 2016 Schneeweis.Technology + */ +interface WikitudePlugin { + isDeviceSupported( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + requiredFeatures: [string] + ): void; + + loadARchitectWorld( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + architectWorldPath: string, + requiredFeatures: [string], + startupConfiguration: JSON | object + ): void; + + close(): void; + + hide(): void; + + show(): void; + + // test type ok? + callJavaScript(js: any): void; + + setOnUrlInvokeCallback(onUrlInvokeCallback: (success: string) => void): void; + + setLocation(latitude: any, longitude: any, altitude: any, accuracy: any): void; + + captureScreen( + successCallback: (success: string) => void, + errorCallback: (message: string) => void, + includeWebView: boolean, + imagePathInBundleOrNullForPhotoLibrary: string | null + ): void; + + setErrorHandler(errorHandler: (message: string) => void): void; + + setDeviceSensorsNeedCalibrationHandler( + startCalibrationHandler: (message: string) => void + ): void; + + setDeviceSensorsFinishedCalibrationHandler( + finishedCalibrationHandler: (message: string) => void + ): void; + + setBackButtonCallback(onBackButtonCallback: (message: string) => void): void; + + /* Lifecycle updates */ + + onResume(): void; + onBackButton(): void; + onPause(): void; + + onWikitudeOK(): void; + onWikitudeError(): void; + + _sdkKey: string; + FeatureGeo: string; + Feature2DTracking: string; + CameraPositionUndefined: number; + CameraPositionFront: number; + CameraPositionBack: number; + CameraFocusRangeNone: number; + CameraFocusRangeNear: number; + CameraFocusRangeFar: number; +} + +declare var WikitudePlugin: WikitudePlugin; diff --git a/types/com.wikitude.phonegap.wikitudeplugin/tsconfig.json b/types/com.wikitude.phonegap.wikitudeplugin/tsconfig.json new file mode 100644 index 0000000000..ed0ce7783e --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "com.wikitude.phonegap.wikitudeplugin-tests.ts" + ] +} diff --git a/types/com.wikitude.phonegap.wikitudeplugin/tslint.json b/types/com.wikitude.phonegap.wikitudeplugin/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/com.wikitude.phonegap.wikitudeplugin/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/connect-mongo/tsconfig.json b/types/connect-mongo/tsconfig.json index ca12068b57..c0c9ab3043 100644 --- a/types/connect-mongo/tsconfig.json +++ b/types/connect-mongo/tsconfig.json @@ -7,7 +7,10 @@ "paths": { "mongodb": [ "mongodb/v2" - ] + ], + "mongoose": [ + "mongoose/v4" + ] }, "noImplicitAny": true, "noImplicitThis": true, @@ -25,4 +28,4 @@ "index.d.ts", "connect-mongo-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/csso/csso-tests.ts b/types/csso/csso-tests.ts new file mode 100644 index 0000000000..74e0b51dd9 --- /dev/null +++ b/types/csso/csso-tests.ts @@ -0,0 +1,40 @@ +import csso = require('csso'); + +csso.minify('.test { color: #ff0000; }').css; +csso.minify('.test { color: #ff0000; }').map; +csso.minify('.test { color: #ff0000; }', { + sourceMap: true, + filename: '', + debug: true, + beforeCompress: () => {}, + afterCompress: () => {}, + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}); + +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000').css; +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000').map; +csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000', { + sourceMap: true, + filename: '', + debug: true, + beforeCompress: () => {}, + afterCompress: () => {}, + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}); + +csso.compress({}).ast; +csso.compress({}, { + restructure: false, + forceMediaMerge: true, + clone: false, + comments: '', + logger: () => {} +}).ast; diff --git a/types/csso/index.d.ts b/types/csso/index.d.ts new file mode 100644 index 0000000000..f89f395129 --- /dev/null +++ b/types/csso/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for csso 3.5 +// Project: https://github.com/css/csso +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace csso { + interface Result { + /** + * Resulting CSS. + */ + css: string; + /** + * Instance of SourceMapGenerator or null. + */ + map: object | null; + } + + interface CompressOptions { + /** + * Disable or enable a structure optimisations. + * @default true + */ + restructure?: boolean; + /** + * Enables merging of @media rules with the same media query by splitted by other rules. + * The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk. + * @default false + */ + forceMediaMerge?: boolean; + /** + * Transform a copy of input AST if true. Useful in case of AST reuse. + * @default false + */ + clone?: boolean; + /** + * Specify what comments to leave: + * - 'exclamation' or true – leave all exclamation comments + * - 'first-exclamation' – remove every comment except first one + * - false – remove all comments + * @default true + */ + comments?: string | boolean; + /** + * Usage data for advanced optimisations. + */ + usage?: object; + /** + * Function to track every step of transformation. + */ + logger?: () => void; + } + + interface MinifyOptions { + /** + * Generate a source map when true. + * @default false + */ + sourceMap?: boolean; + /** + * Filename of input CSS, uses for source map generation. + * @default '' + */ + filename?: string; + /** + * Output debug information to stderr. + * @default false + */ + debug?: boolean; + /** + * Called right after parse is run. + */ + beforeCompress?: BeforeCompressFn | BeforeCompressFn[]; + /** + * Called right after compress() is run. + */ + afterCompress?: AfterCompressFn | AfterCompressFn[]; + restructure?: boolean; + } + + type BeforeCompressFn = (ast: object, options: CompressOptions) => void; + type AfterCompressFn = (compressResult: string, options: CompressOptions) => void; +} + +interface Csso { + /** + * Minify source CSS passed as String + * @param source + * @param options + */ + minify(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result; + + /** + * The same as minify() but for list of declarations. Usually it's a style attribute value. + * @param source + * @param options + */ + minifyBlock(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result; + + /** + * Does the main task – compress an AST. + */ + compress(ast: object, options?: csso.CompressOptions): { ast: object }; +} + +declare const csso: Csso; +export = csso; diff --git a/types/csso/tsconfig.json b/types/csso/tsconfig.json new file mode 100644 index 0000000000..9ed6695bc9 --- /dev/null +++ b/types/csso/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", + "csso-tests.ts" + ] +} diff --git a/types/csso/tslint.json b/types/csso/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/csso/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 39be1cd0e7..10a38145de 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -2,14 +2,8 @@ // TODO: document all aliases as aliases, not as duplicates! -const assert = (tag: boolean) => { if (!tag) throw new Error(); }; -const aliases = (...obj: Array<{}>) => { if (obj.slice(1).some((alias) => alias !== obj[0])) throw new Error(); }; -const events = (obj: any) => { - aliases(obj.on, obj.bind, obj.listen, obj.addListener); - aliases(obj.promiseOn, obj.pon); - aliases(obj.off, obj.unbind, obj.unlisten, obj.removeListener); - aliases(obj.emit, obj.trigger); -}; +const assert = (tag: boolean) => {}; +const aliases = (...obj: Array<{}>) => {}; // definitions function oneOf(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E; @@ -129,7 +123,7 @@ cy.on('zoom', (event) => { } }); cy.off('zoom'); -events(cy); +// events(cy); - TODO cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); cy.add([ @@ -383,11 +377,18 @@ assert(eles.removed()); assert(!eles.inside()); eles.restore(); -([ele, eles, node, nodes, edge, edges] as cytoscape.CollectionReturnValue[]).forEach((elem) => { - aliases(elem.clone, elem.copy); - events(elem); - aliases(elem.data, elem.attr); - aliases(elem.removeData, elem.removeAttr); +([ele, eles, node, nodes, edge, edges] as [ + cytoscape.SingularElementReturnValue, + cytoscape.CollectionReturnValue, + cytoscape.NodeSingular, + cytoscape.NodeCollection, + cytoscape.EdgeSingular, + cytoscape.EdgeCollection +]).forEach((elemType) => { + aliases(elemType.clone, elemType.copy); + // events(elemType); - TODO + aliases(elemType.data, elemType.attr); + aliases(elemType.removeData, elemType.removeAttr); }); // TODO: tests for data flow @@ -490,6 +491,6 @@ eles.reduce((prev, ele, i, eles) => [...prev, [ele, i]], []).concat(['fin const min = eles.min((ele, i, eles) => ele.id.length + i); min.ele.scratch('min', min.value); const max = eles.max((ele, i, eles) => ele.id.length + i); max.ele.scratch('max', max.value); -// TODO: traversing (need to actively check the nodes/edeges distinction) +// TODO: traversing (need to actively check the nodes/edges distinction) // TODO: algorithms // TODO: compound nodes (there aren't any in current test case) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index a3226defd2..1fcdcb0f08 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1118,7 +1118,7 @@ declare namespace cytoscape { * http://js.cytoscape.org/#collection */ interface Collection - extends Singular, + extends CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, @@ -1129,8 +1129,10 @@ declare namespace cytoscape { /** * ele --> Cy.Singular * a collection of a single element (node or edge) + * NB: every singular collection is a general collection too (but not vice versa)! */ - interface Singular extends + interface Singular + extends Collection, SingularGraphManipulation, SingularData, SingularPosition, SingularSelection, SingularStyle, SingularAnimation { } @@ -1154,7 +1156,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1162,7 +1164,7 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends NodeSingular, NodeCollectionMetadata, NodeCollectionPosition, NodeCollectionTraversing, NodeCollectionCompound { } @@ -1172,14 +1174,14 @@ declare namespace cytoscape { * edge --> Cy.EdgeSingular * a collection of a single edge */ - interface EdgeSingular extends Singular, + interface EdgeSingular extends Singular, EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular * a collection of a single node */ - interface NodeSingular extends Singular, + interface NodeSingular extends Singular, NodeSingularMetadata, NodeSingularPosition, NodeSingularCompound { } /** @@ -1251,6 +1253,15 @@ declare namespace cytoscape { on(events: EventNames, selector: string, data: any, handler: EventHandler): void; on(events: EventNames, selector: string, handler: EventHandler): void; on(events: EventNames, handler: EventHandler): void; + bind(events: EventNames, selector: string, data: any, handler: EventHandler): void; + bind(events: EventNames, selector: string, handler: EventHandler): void; + bind(events: EventNames, handler: EventHandler): void; + listen(events: EventNames, selector: string, data: any, handler: EventHandler): void; + listen(events: EventNames, selector: string, handler: EventHandler): void; + listen(events: EventNames, handler: EventHandler): void; + addListener(events: EventNames, selector: string, data: any, handler: EventHandler): void; + addListener(events: EventNames, selector: string, handler: EventHandler): void; + addListener(events: EventNames, handler: EventHandler): void; /** * http://js.cytoscape.org/#eles.promiseOn * alias: pon @@ -1280,11 +1291,15 @@ declare namespace cytoscape { * alias unbind, unlisten, removeListener */ off(events: EventNames, selector?: string, handler?: EventHandler): void; + unbind(events: EventNames, selector?: string, handler?: EventHandler): void; + unlisten(events: EventNames, selector?: string, handler?: EventHandler): void; + removeListener(events: EventNames, selector?: string, handler?: EventHandler): void; /** * http://js.cytoscape.org/#eles.trigger * alias: emit */ trigger(events: EventNames, extra?: string[]): void; + emit(events: EventNames, extra?: string[]): void; } /** @@ -2747,28 +2762,28 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - outgoers(selector?: Selector): EdgeCollection; + outgoers(selector?: Selector): CollectionReturnValue; /** * Recursively get edges (and their targets) coming out of the nodes in the collection (i.e. the outgoers, the outgoers' outgoers, ...). * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - successors(selector?: Selector): EdgeCollection; + successors(selector?: Selector): CollectionReturnValue; /** * Get edges (and their sources) coming into the nodes in the collection. * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - incomers(selector?: Selector): EdgeCollection; + incomers(selector?: Selector): CollectionReturnValue; /** * Recursively get edges (and their sources) coming into the nodes in the collection (i.e. the incomers, the incomers' incomers, ...). * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - predecessors(selector?: Selector): EdgeCollection; + predecessors(selector?: Selector): CollectionReturnValue; } /** diff --git a/types/dat.gui/index.d.ts b/types/dat.gui/index.d.ts index 967b5ae13b..5c20fd51fe 100644 --- a/types/dat.gui/index.d.ts +++ b/types/dat.gui/index.d.ts @@ -51,8 +51,7 @@ export class GUI { __folders: GUI[]; domElement: HTMLElement; - add(target: Object, propName:string): GUIController; - add(target: Object, propName:string, min: number, max: number): GUIController; + add(target: Object, propName:string, min?: number, max?: number, step?: number): GUIController; add(target: Object, propName:string, status: boolean): GUIController; add(target: Object, propName:string, items:string[]): GUIController; add(target: Object, propName:string, items:number[]): GUIController; @@ -64,6 +63,7 @@ export class GUI { destroy(): void; addFolder(propName:string): GUI; + removeFolder(subFolder:GUI):void; open(): void; close(): void; diff --git a/types/datatables.net-scroller/datatables.net-scroller-tests.ts b/types/datatables.net-scroller/datatables.net-scroller-tests.ts new file mode 100644 index 0000000000..cb93306ba0 --- /dev/null +++ b/types/datatables.net-scroller/datatables.net-scroller-tests.ts @@ -0,0 +1,13 @@ +$(document).ready(() => { + const config: DataTables.Settings = { + // Scroller extension options + scroller: { + trace: true, + rowHeight: 30, + serverWait: 1000, + displayBuffer: 10, + boundaryScale: 0.6, + loadingIndicator: true + } + }; +}); diff --git a/types/datatables.net-scroller/index.d.ts b/types/datatables.net-scroller/index.d.ts new file mode 100644 index 0000000000..fe97507712 --- /dev/null +++ b/types/datatables.net-scroller/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for datatables.net-scroller 1.4 +// Project: https://datatables.net +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// + +declare namespace DataTables { + interface Settings { + /* + * Select extension options + */ + scroller?: boolean | ScrollerSettings; + } + + interface ScrollerSettings { + /* + * Indicate if Scroller show show trace information on the console or not. + */ + trace?: boolean; + + /* + * Scroller will attempt to automatically calculate the height of rows for it's internal + * calculations. However the height that is used can be overridden using this parameter. + */ + rowHeight?: number | string; + + /* + * When using server-side processing, Scroller will wait a small amount of time to allow + * the scrolling to finish before requesting more data from the server. + */ + serverWait?: number; + + /* + * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch + * for scrolling. + */ + displayBuffer?: number; + + /* + * Scroller uses the boundary scaling factor to decide when to redraw the table - which it + * typically does before you reach the end of the currently loaded data set (in order to + * allow the data to look continuous to a user scrolling through the data). + */ + boundaryScale?: number; + + /* + * Show (or not) the loading element in the background of the table. Note that you should + * include the dataTables.scroller.css file for this to be displayed correctly. + */ + loadingIndicator?: boolean; + } + + interface Api { + scroller: ScrollerMethodsModel; + } + + interface ScrollerMethodsModel { + /* + * Calculate and store information about how many rows are to be displayed + * in the scrolling viewport, based on current dimensions in the browser's + * rendering. + */ + measure(redraw?: boolean): Api; + /* + * Get information about current displayed record range. + */ + page(): PageInfo; + /* + * Get Scroller Api + */ + scroller(): ScrollerMethods; + } + + interface ScrollerMethods extends Api { + /* + * Calculate the pixel position from the top of the scrolling container for + * a given row + */ + rowToPixels(rowIdx: number, intParse?: boolean, virtual?: boolean): number; + /* + * Calculate the row number that will be found at the given pixel position + * (y-scroll). + */ + pixelsToRow(pixels: number, intParse?: boolean, virtual?: boolean): number; + scrollToRow(rowIdx: number, animate?: boolean): Api; + } + + /* + * start: {int}, // the 0-indexed record at the top of the viewport + * end: {int}, // the 0-indexed record at the bottom of the viewport + */ + interface PageInfo { + start: number; + end: number; + } + + interface RowMethods { + /** + * Scroll to a row + */ + scrollTo(animate?: boolean): Api; + } +} diff --git a/types/datatables.net-scroller/tsconfig.json b/types/datatables.net-scroller/tsconfig.json new file mode 100644 index 0000000000..29e1854557 --- /dev/null +++ b/types/datatables.net-scroller/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "datatables.net-scroller-tests.ts" + ] +} diff --git a/types/datatables.net-scroller/tslint.json b/types/datatables.net-scroller/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/datatables.net-scroller/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/emoji-regex/emoji-regex-tests.ts b/types/emoji-regex/emoji-regex-tests.ts new file mode 100644 index 0000000000..6d6b0d25d9 --- /dev/null +++ b/types/emoji-regex/emoji-regex-tests.ts @@ -0,0 +1,3 @@ +import emojiRegex from "emoji-regex"; + +emojiRegex(); // $ExpectType RegExp diff --git a/types/emoji-regex/index.d.ts b/types/emoji-regex/index.d.ts new file mode 100644 index 0000000000..edff690dc7 --- /dev/null +++ b/types/emoji-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for emoji-regex 7.0 +// Project: https://github.com/mathiasbynens/emoji-regex +// Definitions by: iKBAHT +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function createRegExp(): RegExp; +export = createRegExp; diff --git a/types/emoji-regex/tsconfig.json b/types/emoji-regex/tsconfig.json new file mode 100644 index 0000000000..1dfdf53dac --- /dev/null +++ b/types/emoji-regex/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "emoji-regex-tests.ts" + ] +} diff --git a/types/emoji-regex/tslint.json b/types/emoji-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/emoji-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ethereum-protocol/ethereum-protocol-tests.ts b/types/ethereum-protocol/ethereum-protocol-tests.ts new file mode 100644 index 0000000000..a30a691e87 --- /dev/null +++ b/types/ethereum-protocol/ethereum-protocol-tests.ts @@ -0,0 +1,4 @@ +import { CallData, BlockParamLiteral } from 'ethereum-protocol'; +BlockParamLiteral.Earliest; +BlockParamLiteral.Latest; +BlockParamLiteral.Pending; diff --git a/types/ethereum-protocol/index.d.ts b/types/ethereum-protocol/index.d.ts new file mode 100644 index 0000000000..9b967cfc83 --- /dev/null +++ b/types/ethereum-protocol/index.d.ts @@ -0,0 +1,293 @@ +// Type definitions for ethereum-protocol 1.0 +// Project: https://www.npmjs.com/package/ethereum-protocol +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import BigNumber from 'bignumber.js'; + +export type JSONRPCErrorCallback = (err: Error | null, result?: JSONRPCResponsePayload) => void; + +/** + * Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library + * Read more about Providers in the 0x wiki. + */ +export interface Provider { + sendAsync(payload: JSONRPCRequestPayload, callback: JSONRPCErrorCallback): void; +} + +export type ContractAbi = AbiDefinition[]; + +export type AbiDefinition = FunctionAbi | EventAbi; + +export type FunctionAbi = MethodAbi | ConstructorAbi | FallbackAbi; + +export type ConstructorStateMutability = 'nonpayable' | 'payable'; +export type StateMutability = 'pure' | 'view' | ConstructorStateMutability; + +export enum AbiType { + Function = 'function', + Constructor = 'constructor', + Event = 'event', + Fallback = 'fallback', +} + +export interface MethodAbi { + type: AbiType.Function; + name: string; + inputs: DataItem[]; + outputs: DataItem[]; + constant: boolean; + stateMutability: StateMutability; + payable: boolean; +} + +export interface ConstructorAbi { + type: AbiType.Constructor; + inputs: DataItem[]; + payable: boolean; + stateMutability: ConstructorStateMutability; +} + +export interface FallbackAbi { + type: AbiType.Fallback; + payable: boolean; +} + +export interface EventParameter extends DataItem { + indexed: boolean; +} + +export interface EventAbi { + type: AbiType.Event; + name: string; + inputs: EventParameter[]; + anonymous: boolean; +} + +export interface DataItem { + name: string; + type: string; + components?: DataItem[]; +} + +export enum OpCode { + DelegateCall = 'DELEGATECALL', + Revert = 'REVERT', + Create = 'CREATE', + Stop = 'STOP', + Invalid = 'INVALID', + CallCode = 'CALLCODE', + StaticCall = 'STATICCALL', + Return = 'RETURN', + Call = 'CALL', + SelfDestruct = 'SELFDESTRUCT', +} + +export interface StructLog { + depth: number; + error: string; + gas: number; + gasCost: number; + memory: string[]; + op: OpCode; + pc: number; + stack: string[]; + storage: { [location: string]: string }; +} + +export interface TransactionTrace { + gas: number; + returnValue: any; + structLogs: StructLog[]; +} + +export type Unit = + | 'kwei' + | 'ada' + | 'mwei' + | 'babbage' + | 'gwei' + | 'shannon' + | 'szabo' + | 'finney' + | 'ether' + | 'kether' + | 'grand' + | 'einstein' + | 'mether' + | 'gether' + | 'tether'; + +export interface JSONRPCRequestPayload { + params: any[]; + method: string; + id: number; + jsonrpc: string; +} + +export interface JSONRPCResponsePayload { + result: any; + id: number; + jsonrpc: string; +} + +export interface AbstractBlock { + number: number | null; + hash: string | null; + parentHash: string; + nonce: string | null; + sha3Uncles: string; + logsBloom: string | null; + transactionsRoot: string; + stateRoot: string; + miner: string; + difficulty: BigNumber; + totalDifficulty: BigNumber; + extraData: string; + size: number; + gasLimit: number; + gasUsed: number; + timestamp: number; + uncles: string[]; +} + +export interface BlockWithoutTransactionData extends AbstractBlock { + transactions: string[]; +} + +export interface BlockWithTransactionData extends AbstractBlock { + transactions: Transaction[]; +} + +export interface Transaction { + hash: string; + nonce: number; + blockHash: string | null; + blockNumber: number | null; + transactionIndex: number | null; + from: string; + to: string | null; + value: BigNumber; + gasPrice: BigNumber; + gas: number; + input: string; +} + +export interface CallTxDataBase { + to?: string; + value?: number | string | BigNumber; + gas?: number | string | BigNumber; + gasPrice?: number | string | BigNumber; + data?: string; + nonce?: number; +} + +export interface TxData extends CallTxDataBase { + from: string; +} + +export interface CallData extends CallTxDataBase { + from?: string; +} + +export interface FilterObject { + fromBlock?: number | string; + toBlock?: number | string; + address?: string; + topics?: LogTopic[]; +} + +export type LogTopic = null | string | string[]; + +export interface DecodedLogEntry extends LogEntry { + event: string; + args: A; +} + +export interface DecodedLogEntryEvent extends DecodedLogEntry { + removed: boolean; +} + +export interface LogEntryEvent extends LogEntry { + removed: boolean; +} + +export interface LogEntry { + logIndex: number | null; + transactionIndex: number | null; + transactionHash: string; + blockHash: string | null; + blockNumber: number | null; + address: string; + data: string; + topics: string[]; +} + +export interface TxDataPayable extends TxData { + value?: BigNumber; +} + +export interface TransactionReceipt { + blockHash: string; + blockNumber: number; + transactionHash: string; + transactionIndex: number; + from: string; + to: string; + status: null | string | 0 | 1; + cumulativeGasUsed: number; + gasUsed: number; + contractAddress: string | null; + logs: LogEntry[]; +} + +export type ContractEventArg = string | BigNumber | number | boolean; + +export interface DecodedLogArgs { + [argName: string]: ContractEventArg; +} + +export interface LogWithDecodedArgs extends DecodedLogEntry {} +export type RawLog = LogEntry; + +export enum BlockParamLiteral { + Earliest = 'earliest', + Latest = 'latest', + Pending = 'pending', +} + +export type BlockParam = BlockParamLiteral | number; + +export interface RawLogEntry { + logIndex: string | null; + transactionIndex: string | null; + transactionHash: string; + blockHash: string | null; + blockNumber: string | null; + address: string; + data: string; + topics: string[]; +} + +export enum SolidityTypes { + Address = 'address', + Uint256 = 'uint256', + Uint8 = 'uint8', + Uint = 'uint', +} + +/** + * Contains the logs returned by a TransactionReceipt. We attempt to decode the + * logs using AbiDecoder. If we have the logs corresponding ABI, we decode it, + * otherwise we don't. + */ +export interface TransactionReceiptWithDecodedLogs extends TransactionReceipt { + logs: Array | LogEntry>; +} + +export interface TraceParams { + disableMemory?: boolean; + disableStack?: boolean; + disableStorage?: boolean; +} diff --git a/types/ethereum-protocol/package.json b/types/ethereum-protocol/package.json new file mode 100644 index 0000000000..4eeb6b18c8 --- /dev/null +++ b/types/ethereum-protocol/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "dependencies": { "bignumber.js": "7.2.1" } +} diff --git a/types/ethereum-protocol/tsconfig.json b/types/ethereum-protocol/tsconfig.json new file mode 100644 index 0000000000..5f358a8dec --- /dev/null +++ b/types/ethereum-protocol/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", "ethereum-protocol-tests.ts"] +} diff --git a/types/ethereum-protocol/tslint.json b/types/ethereum-protocol/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ethereum-protocol/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ffi/index.d.ts b/types/ffi/index.d.ts index 76e197e841..cf562cea06 100644 --- a/types/ffi/index.d.ts +++ b/types/ffi/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for node-ffi 0.1 +// Type definitions for node-ffi 0.2 // Project: https://github.com/rbranson/node-ffi -// Definitions by: Paul Loyd +// Definitions by: Paul Loyd , Waiting Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -135,12 +135,13 @@ export const DynamicLibrary: { * The function pointer may be used in other C functions that * accept C callback functions. */ -export const Callback: { +export interface Callback { new (retType: any, argTypes: any[], abi: number, fn: any): Buffer; new (retType: any, argTypes: any[], fn: any): Buffer; (retType: any, argTypes: any[], abi: number, fn: any): Buffer; (retType: any, argTypes: any[], fn: any): Buffer; -}; +} +export const Callback: Callback; export const ffiType: { /** Get a `ffi_type *` Buffer appropriate for the given type. */ diff --git a/types/fibjs/declare/dgram.d.ts b/types/fibjs/declare/dgram.d.ts index 1f87090814..a8004536e2 100644 --- a/types/fibjs/declare/dgram.d.ts +++ b/types/fibjs/declare/dgram.d.ts @@ -214,7 +214,7 @@ declare module "dgram" { * * */ - export class DgramSocket extends Class_DgramSocket {} + export class Socket extends Class_DgramSocket {} diff --git a/types/fibjs/declare/http.d.ts b/types/fibjs/declare/http.d.ts index d5080f12bb..f558303870 100644 --- a/types/fibjs/declare/http.d.ts +++ b/types/fibjs/declare/http.d.ts @@ -196,7 +196,7 @@ /** module Or Internal Object */ /** - * @brief 超文本传输协议模块,用以支持 http 协议处理 + * @brief 超文本传输协议模块,用以支持 http 协议处理,模块别名:https * @detail */ declare module "http" { @@ -212,7 +212,7 @@ declare module "http" { * * */ - export class HttpRequest extends Class_HttpRequest {} + export class Request extends Class_HttpRequest {} /** @@ -221,7 +221,7 @@ declare module "http" { * * */ - export class HttpResponse extends Class_HttpResponse {} + export class Response extends Class_HttpResponse {} /** @@ -230,7 +230,7 @@ declare module "http" { * * */ - export class HttpCookie extends Class_HttpCookie {} + export class Cookie extends Class_HttpCookie {} /** @@ -239,7 +239,7 @@ declare module "http" { * * */ - export class HttpServer extends Class_HttpServer {} + export class Server extends Class_HttpServer {} /** @@ -248,7 +248,7 @@ declare module "http" { * * */ - export class HttpClient extends Class_HttpClient {} + export class Client extends Class_HttpClient {} /** @@ -266,7 +266,7 @@ declare module "http" { * * */ - export class HttpHandler extends Class_HttpHandler {} + export class Handler extends Class_HttpHandler {} diff --git a/types/fibjs/declare/net.d.ts b/types/fibjs/declare/net.d.ts index dcf90e72eb..f9d9c222c9 100644 --- a/types/fibjs/declare/net.d.ts +++ b/types/fibjs/declare/net.d.ts @@ -271,7 +271,7 @@ declare module "net" { * * */ - export class UrlObject extends Class_UrlObject {} + export class Url extends Class_UrlObject {} diff --git a/types/fibjs/declare/ssl.d.ts b/types/fibjs/declare/ssl.d.ts index befed4f19a..6fbdabd87c 100644 --- a/types/fibjs/declare/ssl.d.ts +++ b/types/fibjs/declare/ssl.d.ts @@ -196,7 +196,7 @@ /** module Or Internal Object */ /** - * @brief ssl/tls 模块 + * @brief ssl/tls 模块,模块别名:tls * @detail */ declare module "ssl" { @@ -300,7 +300,7 @@ declare module "ssl" { * * */ - export class SslSocket extends Class_SslSocket {} + export class Socket extends Class_SslSocket {} /** @@ -309,7 +309,7 @@ declare module "ssl" { * * */ - export class SslHandler extends Class_SslHandler {} + export class Handler extends Class_SslHandler {} /** @@ -318,7 +318,7 @@ declare module "ssl" { * * */ - export class SslServer extends Class_SslServer {} + export class Server extends Class_SslServer {} diff --git a/types/fibjs/declare/ws.d.ts b/types/fibjs/declare/ws.d.ts index d5402ad972..78ab282d97 100644 --- a/types/fibjs/declare/ws.d.ts +++ b/types/fibjs/declare/ws.d.ts @@ -292,7 +292,7 @@ declare module "ws" { * * */ - export class WebSocketMessage extends Class_WebSocketMessage {} + export class Message extends Class_WebSocketMessage {} /** @@ -301,7 +301,7 @@ declare module "ws" { * * */ - export class WebSocket extends Class_WebSocket {} + export class Socket extends Class_WebSocket {} diff --git a/types/fibjs/declare/xml.d.ts b/types/fibjs/declare/xml.d.ts index 4dbb477dc1..5526a84e5c 100644 --- a/types/fibjs/declare/xml.d.ts +++ b/types/fibjs/declare/xml.d.ts @@ -284,7 +284,7 @@ declare module "xml" { * * */ - export class XmlDocument extends Class_XmlDocument {} + export class Document extends Class_XmlDocument {} diff --git a/types/fibjs/declare/zmq.d.ts b/types/fibjs/declare/zmq.d.ts index 04f7b59815..e6ef8fde76 100644 --- a/types/fibjs/declare/zmq.d.ts +++ b/types/fibjs/declare/zmq.d.ts @@ -300,7 +300,7 @@ declare module "zmq" { * * */ - export class ZmqSocket extends Class_ZmqSocket {} + export class Socket extends Class_ZmqSocket {} diff --git a/types/fibjs/index.d.ts b/types/fibjs/index.d.ts index 67bc9f3a4e..0b4ef29975 100644 --- a/types/fibjs/index.d.ts +++ b/types/fibjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for fibjs 0.25 // Project: https://github.com/fibjs/fibjs -// Definitions by: Richard +// Definitions by: richardo2016 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/gramps__rest-helpers/gramps__rest-helpers-tests.ts b/types/gramps__rest-helpers/gramps__rest-helpers-tests.ts new file mode 100644 index 0000000000..cbb74725ca --- /dev/null +++ b/types/gramps__rest-helpers/gramps__rest-helpers-tests.ts @@ -0,0 +1,16 @@ +import { GraphQLConnector, GraphQLModel } from '@gramps/rest-helpers'; + +const myConnector = new GraphQLConnector(); + +myConnector.apiBaseUri = "some uri"; +myConnector.headers = {}; +myConnector.cacheExpiry = 300; +myConnector.enableCache = true; +myConnector.redis = false; + +myConnector.get("someurl"); +myConnector.post("someendpoint", {}, {}).then(() => {}); +myConnector.put("someendpoint", {}, {}).then(() => {}); +myConnector.delete("someendpoint", {}).then(() => {}); + +const myModel = new GraphQLModel(myConnector); diff --git a/types/gramps__rest-helpers/index.d.ts b/types/gramps__rest-helpers/index.d.ts new file mode 100644 index 0000000000..4fb7e32a27 --- /dev/null +++ b/types/gramps__rest-helpers/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for @gramps/rest-helpers 1.1 +// Project: https://github.com/gramps-graphql/rest-helpers +// Definitions by: Claude Ciocan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export class GraphQLConnector { + constructor(); + + apiBaseUri: string; + headers: object; + request: any; + cacheExpiry: number; + enableCache: boolean; + redis: boolean; + get(endpoint: string): Promise; + post(endpoint: string, body: object, options: object): Promise; + put(endpoint: string, body: object, options: object): Promise; + delete(endpoint: string, options: object): Promise; +} + +export class GraphQLModel { + connector: GraphQLConnector; + + constructor({}); +} diff --git a/types/gramps__rest-helpers/tsconfig.json b/types/gramps__rest-helpers/tsconfig.json new file mode 100644 index 0000000000..03402cad31 --- /dev/null +++ b/types/gramps__rest-helpers/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@gramps/rest-helpers": [ + "gramps__rest-helpers" + ] + } + }, + "files": [ + "index.d.ts", + "gramps__rest-helpers-tests.ts" + ] +} \ No newline at end of file diff --git a/types/gramps__rest-helpers/tslint.json b/types/gramps__rest-helpers/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gramps__rest-helpers/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 1434999411..6ef4ef4e2a 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -2354,7 +2354,7 @@ declare namespace Highcharts { * can be customized by defining a new array of items and assigning null to unwanted positions. * @since 2.0 */ - menuItems?: MenuItem[]; + menuItems?: string[] | MenuItem[]; /** * A click handler callback to use on the button directly instead of the popup menu. * @since 2.0 @@ -2661,6 +2661,12 @@ declare namespace Highcharts { * @default ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] */ shortMonths?: string[]; + /** + * Short week days, starting Sunday. If not specified, Highcharts uses the first three letters of the lang.weekdays option. + * @default undefined + * @since 4.2.4 + */ + shortWeekdays?: string[]; /** * The default thousands separator used in the Highcharts.numberFormat method unless otherwise specified in the * function arguments. Since Highcharts 4.1 it defaults to a single space character, which is compatible with ISO diff --git a/types/highcharts/modules/drilldown.d.ts b/types/highcharts/modules/drilldown.d.ts new file mode 100644 index 0000000000..adf9bae6f8 --- /dev/null +++ b/types/highcharts/modules/drilldown.d.ts @@ -0,0 +1,10 @@ +// Type definitions for Highcharts Drilldown 4.2.7 +// Project: http://www.highcharts.com/ +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Static } from "highcharts"; + +declare function HighchartsDrilldown(H: Static): Static; +export = HighchartsDrilldown; +export as namespace HighchartsDrilldown; diff --git a/types/highcharts/test/drilldown.ts b/types/highcharts/test/drilldown.ts new file mode 100644 index 0000000000..f4aa33ca4a --- /dev/null +++ b/types/highcharts/test/drilldown.ts @@ -0,0 +1 @@ +HighchartsDrilldown(Highcharts); diff --git a/types/highcharts/tsconfig.json b/types/highcharts/tsconfig.json index 24b0cf2dd7..e69f0eeb57 100644 --- a/types/highcharts/tsconfig.json +++ b/types/highcharts/tsconfig.json @@ -21,6 +21,7 @@ "index.d.ts", "modules/map/index.d.ts", "modules/boost.d.ts", + "modules/drilldown.d.ts", "modules/exporting.d.ts", "modules/no-data-to-display.d.ts", "modules/offline-exporting.d.ts", @@ -28,6 +29,7 @@ "highstock.d.ts", "js/highcharts/index.d.ts", "test/boost.ts", + "test/drilldown.ts", "test/exporting.ts", "test/highstock.ts", "test/index.ts", diff --git a/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts b/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts new file mode 100644 index 0000000000..17bc81ce1d --- /dev/null +++ b/types/http-graceful-shutdown/http-graceful-shutdown-tests.ts @@ -0,0 +1,21 @@ +import GracefulShutdown = require('http-graceful-shutdown'); +import * as http from "http"; + +const opts: GracefulShutdown.Options = { + signals: "SIGINT SIGTERM", + timeout: 1337, + development: false, + onShutdown: () => { + console.log('fake shutdown handler'); + return Promise.resolve(); + }, + finally: () => { + console.log('fake finally handler'); + } +}; + +const server = http.createServer((req, res) => { + res.end(); +}); + +GracefulShutdown(server, opts); diff --git a/types/http-graceful-shutdown/index.d.ts b/types/http-graceful-shutdown/index.d.ts new file mode 100644 index 0000000000..f8269adea7 --- /dev/null +++ b/types/http-graceful-shutdown/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for http-graceful-shutdown 2.1 +// Project: https://github.com/sebhildebrandt/http-graceful-shutdown +// Definitions by: Dave Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Server } from "http"; + +declare function GracefulShutdown(server: Server, options?: GracefulShutdown.Options): void; + +declare namespace GracefulShutdown { + interface Options { + signals?: string; + timeout?: number; + development?: boolean; + onShutdown?: () => Promise; + finally?: () => void; + } +} + +export = GracefulShutdown; diff --git a/types/http-graceful-shutdown/tsconfig.json b/types/http-graceful-shutdown/tsconfig.json new file mode 100644 index 0000000000..a738609778 --- /dev/null +++ b/types/http-graceful-shutdown/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", + "http-graceful-shutdown-tests.ts" + ] +} diff --git a/types/http-graceful-shutdown/tslint.json b/types/http-graceful-shutdown/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-graceful-shutdown/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next-ko/i18next-ko-tests.ts b/types/i18next-ko/i18next-ko-tests.ts new file mode 100644 index 0000000000..1b8cd90904 --- /dev/null +++ b/types/i18next-ko/i18next-ko-tests.ts @@ -0,0 +1,24 @@ +import * as i18next from 'i18next'; +import * as i18nextko from 'i18next-ko'; +import * as ko from 'knockout'; + +const resourceStore = { + en: { + translation: { + testTranslation: 'Test translation' + } + }, + + de: { + translation: { + testTranslation: 'Test-Übersetzung' + } + } +}; +i18nextko.init(resourceStore, 'en', ko); + +i18nextko.setLanguage('de'); + +i18nextko.i18n; + +i18nextko.t('testTranslation'); diff --git a/types/i18next-ko/index.d.ts b/types/i18next-ko/index.d.ts new file mode 100644 index 0000000000..e9d3c2c639 --- /dev/null +++ b/types/i18next-ko/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for i18next-ko 3.0 +// Project: https://github.com/leMaik/i18next-ko +// Definitions by: Daniel Waxweiler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as i18next from 'i18next'; + +export const i18n: i18next.i18n; + +export function init(resourceStore: i18nextkoResourceStore, language: string, ko: KnockoutStatic): void; + +export function setLanguage(language: string): void; + +export function t(key: string): KnockoutComputed; + +export interface i18nextkoResourceStore { + [language: string]: { + translation: { + [key: string]: string + } + }; +} diff --git a/types/i18next-ko/tsconfig.json b/types/i18next-ko/tsconfig.json new file mode 100644 index 0000000000..9509fa509e --- /dev/null +++ b/types/i18next-ko/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", + "i18next-ko-tests.ts" + ] +} diff --git a/types/i18next-ko/tslint.json b/types/i18next-ko/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/i18next-ko/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jquery.fancytree/index.d.ts b/types/jquery.fancytree/index.d.ts index c13cd7f26f..d370b06f4d 100644 --- a/types/jquery.fancytree/index.d.ts +++ b/types/jquery.fancytree/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for jquery.fancytree 2.7.0 +// Type definitions for jquery.fancytree 2.28.2-0 // Project: https://github.com/mar10/fancytree // Definitions by: Peter Palotas // Mahdi Abedi +// Nikolai Ommundsen // Nitecube // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// @@ -95,10 +96,10 @@ declare namespace Fancytree { findNextNode(match: (node: FancytreeNode) => boolean, startNode?: FancytreeNode): FancytreeNode; /** Find all nodes that matches condition. - * + * * @returns array of nodes (may be empty) */ - findAll(match: string|((node: FancytreeNode) => boolean|undefined)): FancytreeNode[]; + findAll(match: string | ((node: FancytreeNode) => boolean | undefined)): FancytreeNode[]; /** Generate INPUT elements that can be submitted with html forms. In selectMode 3 only the topmost selected nodes are considered. */ generateFormElements(selected?: boolean, active?: boolean): void; @@ -315,7 +316,7 @@ declare namespace Fancytree { * @param map callback function(NodeData) that could modify the new node * @returns new node. */ - copyTo(node: FancytreeNode, mode?: string, map?: (node: NodeData) => void) : FancytreeNode; + copyTo(node: FancytreeNode, mode?: string, map?: (node: NodeData) => void): FancytreeNode; /** Count direct and indirect children. * @@ -545,7 +546,7 @@ declare namespace Fancytree { resetLazy(): void; /** Schedule activity for delayed execution (cancel any pending request). scheduleAction('cancel') will only cancel a pending request (if any). */ - scheduleAction(mode: string, ms: number) : void; + scheduleAction(mode: string, ms: number): void; /** * @param effects animation options. @@ -761,7 +762,20 @@ declare namespace Fancytree { /** Make sure that the active node is always visible, i.e. its parents are expanded (default: true). */ activeVisible?: boolean; /** Default options for ajax requests. */ - ajax?: Object; + ajax?: { + /** + * HTTP Method (default: 'GET') + */ + type: string; + /** + * false: Append random '_' argument to the request url to prevent caching. + */ + cache: boolean; + /** + * Default 'json' -> Expect json format and pass json object to callbacks. + */ + dataType: string; + }; /** (default: false) Add WAI-ARIA attributes to markup */ aria?: boolean; /** Activate a node when focused with the keyboard (default: true) */ @@ -771,24 +785,26 @@ declare namespace Fancytree { /** Scroll node into visible area, when focused by keyboard (default: false). */ autoScroll?: boolean; /** Display checkboxes to allow selection (default: false) */ - checkbox?: boolean|string|((event: JQueryEventObject, data: EventData) => boolean); + checkbox?: boolean | string | ((event: JQueryEventObject, data: EventData) => boolean); /** Defines what happens, when the user click a folder node. (default: activate_dblclick_expands) */ clickFolderMode?: FancytreeClickFolderMode; - /** 0..2 (null: use global setting $.ui.fancytree.debugInfo) */ - debugLevel?: number; + /** 0..4 (null: use global setting $.ui.fancytree.debugInfo) */ + debugLevel?: 0 | 1 | 2 | 3 | 4; /** callback(node) is called for new nodes without a key. Must return a new unique key. (default null: generates default keys like that: "_" + counter) */ defaultKey?: (node: FancytreeNode) => string; /** Accept passing ajax data in a property named `d` (default: true). */ enableAspx?: boolean; + /** Enable titles (default: false) */ + enableTitles?: boolean; /** List of active extensions (default: []) */ - extensions?: string[]; + extensions?: Array; /** Set focus when node is checked by a mouse click (default: false) */ focusOnSelect?: boolean; /** Add `id="..."` to node markup (default: true). */ generateIds?: boolean; - /** Display node icons (default: true) */ - icons?: boolean; - /** (default: "ft_") */ + /** Node icon url, if only filename, please use imagePath to set the path */ + icon?: boolean | string; + /** Prefix (default: "ft_") */ idPrefix?: string; /** Path to a folder containing icons (default: null, using 'skin/' subdirectory). */ imagePath?: string; @@ -800,36 +816,227 @@ declare namespace Fancytree { minExpandLevel?: number; /** navigate to next node by typing the first letters (default: false) */ quicksearch?: boolean; + /** Right to left mode (default: false) */ + rtl?: false; /** optional margins for node.scrollIntoView() (default: {top: 0, bottom: 0}) */ - scrollOfs?: Object; + scrollOfs?: { top: number, bottom: number }; /** scrollable container for node.scrollIntoView() (default: $container) */ - scrollParent?: JQuery; + scrollParent?: JQuery | null; /** default: multi_hier */ selectMode?: FancytreeSelectMode; /** Used to Initialize the tree. */ - source?: any; + source?: any[] | any; /** Translation table */ - strings?: Object; + strings?: TranslationTable; /** Add tabindex='0' to container, so tree can be reached using TAB */ tabbable?: boolean; /** Add tabindex='0' to node title span, so it can receive keyboard focus */ titlesTabbable?: boolean; /** Animation options, false:off (default: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }) */ toggleEffect?: JQueryUI.EffectOptions; + /** Tooltips */ + tooltip?: boolean; /** (dynamic Option)Prevent (de-)selection using mouse or keyboard. */ - unselectable?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectable?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); /** (dynamic Option)Ignore this node when calculating the partsel status of parent nodes in selectMode 3 propagation. */ - unselectableIgnore?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectableIgnore?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); /** (dynamic Option)Use this as constant selected value (overriding selectMode 3 propagation). */ - unselectableStatus?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + unselectableStatus?: boolean | ((event: JQueryEventObject, data: Fancytree.EventData) => boolean | undefined); + + //////////////// + // EXTENSIONS // + //////////////// + dnd5?: Extensions.DragAndDrop5; + filter?: Extensions.Filter; + table?: Extensions.Table; + + /** Options for misc extensions - see docs for typings */ + [extension: string]: any; } + interface TranslationTable { + /** + * "Loading..." // … would be escaped when escapeTitles is true + */ + loading: string; + /** + * "Load error!" + */ + loadError: string; + /** + * "More..." + */ + moreData: string; + /** + * "No data." + */ + noData: string; + } + + namespace Extensions { + interface List { + dnd5?: DragAndDrop5; + filter?: Filter; + table?: Table; + [extension: string]: any; + } + + interface DragAndDrop5 { + /** + * Expand nodes after n milliseconds of hovering. + */ + autoExpandMS?: number; + /** + * Absolute position offset for .fancytree-drop-marker + */ + dropMarkerOffsetX?: number; + /** + * Additional offset for drop-marker with hitMode = "before"/"after" + */ + dropMarkerInsertOffsetX?: number; + /** + * true: Drag multiple (i.e. selected) nodes. + */ + multiSource?: boolean; + /** + * Prevent dropping nodes from different Fancytrees + */ + preventForeignNodes?: boolean; + /** + * Prevent dropping items other than Fancytree nodes + */ + preventNonNodes?: boolean; + /** + * Prevent dropping nodes on own descendants + */ + preventRecursiveMoves?: boolean; + /** + * Prevent dropping nodes 'before self', etc. + */ + preventVoidMoves?: boolean; + /** + * Enable auto-scrolling while dragging + */ + scroll?: boolean; + /** + * Active top/bottom margin in pixel + */ + scrollSensitivity?: number; + /** + * Pixel per event + */ + scrollSpeed?: number; + /** + * Allow dragging of nodes to different IE windows, default: false + */ + setTextTypeJson?: boolean; + /** + * Callback(sourceNode, data), return true, to enable dnd drag + */ + dragStart?: (sourceNode: FancytreeNode, data: any) => void; + dragDrag?: (sourceNode: FancytreeNode, data: any) => void; + dragEnd?: (sourceNode: FancytreeNode, data: any) => void; + /** + * Callback(targetNode, data), return true, to enable dnd drop + */ + dragEnter?: (targetNode: FancytreeNode, data: any) => void; + /** + * Events (drag over) + */ + dragOver?: (targetNode: FancytreeNode, data: any) => void; + /** + * Callback(targetNode, data), return false to prevent autoExpand + */ + dragExpand?: (targetNode: FancytreeNode, data: any) => void; + /** + * Events (drag drop) + */ + dragDrop?: (node: FancytreeNode, data: any) => void; + dragLeave?: (targetNode: FancytreeNode, data: any) => void; + /** + * Support misc options + */ + [key: string]: any; + } + /** + * Define filter-extension options + */ + interface Filter { + /** + * Re-apply last filter if lazy data is loaded + */ + autoApply: boolean; + /** + * Expand all branches that contain matches while filtered + */ + autoExpand: boolean; + /** + * Show a badge with number of matching child nodes near parent icons + */ + counter: boolean; + /** + * Match single characters in order, e.g. 'fb' will match 'FooBar' + */ + fuzzy: boolean; + /** + * Hide counter badge if parent is expanded + */ + hideExpandedCounter: boolean; + /** + * Hide expanders if all child nodes are hidden by filter + */ + hideExpanders: boolean; + /** + * Highlight matches by wrapping inside tags + */ + highlight: boolean; + /** + * Match end nodes only + */ + leavesOnly: boolean; + /** + * Display a 'no data' status node if result is empty + */ + nodata: boolean; + /** + * Grayout unmatched nodes (pass "hide" to remove unmatched node instead); default 'dimm' + */ + mode: 'dimm' | 'string'; + /** + * Support misc options + */ + [key: string]: any; + } + /** + * Define table-extension options + */ + interface Table { + /** + * Render the checkboxes into the this column index (default: nodeColumnIdx) + */ + checkboxColumnIdx: any; + /** + * Indent every node level by 16px; default: 16 + */ + indentation: number; + /** + * Render node expander, icon, and title to this column (default: 0) + */ + nodeColumnIdx: number; + /** + * Support misc options + */ + [key: string]: any; + } + } + + /** Data object passed to FancytreeNode() constructor. Note: typically these attributes are accessed by meber methods, e.g. `node.isExpanded()` and `node.setSelected(false)`. */ interface NodeData { /** node text (may contain HTML tags) */ title: string; - icon?: boolean|string; + icon?: boolean | string; /** unique key for this node (auto-generated if omitted) */ key?: string; /** (reserved) */ diff --git a/types/jquery.fancytree/jquery.fancytree-tests.ts b/types/jquery.fancytree/jquery.fancytree-tests.ts index de1489de42..8f9707597e 100644 --- a/types/jquery.fancytree/jquery.fancytree-tests.ts +++ b/types/jquery.fancytree/jquery.fancytree-tests.ts @@ -1,4 +1,4 @@ -$("#tree").fancytree({ +$("#tree").fancytree({ source: [ { title: "Node 1", key: "1" }, { @@ -12,16 +12,20 @@ $("#tree").fancytree({ { title: "Node 1", key: "1" }, { title: "Folder 2", key: "2", folder: true, children: [ - { title: "Node 2.1", key: "3" }, - { title: "Node 2.2", key: "4" }, - { title: "NOde 2.3", key: "5", icon: "./icon.svg", checkbox: "radio"} - ] + { title: "Node 2.1", key: "3" }, + { title: "Node 2.2", key: "4" }, + { title: "NOde 2.3", key: "5", icon: "./icon.svg", checkbox: "radio" } + ] } ] } ] } ], + extensions: ['dnd5'], + dnd5: { + dragDrag: (node, data) => { } + }, click: (ev: JQueryEventObject, node: Fancytree.EventData) => { return true; }, @@ -51,9 +55,9 @@ $("#tree").fancytree({ //$("#tree").fancytree(); -var tree : Fancytree.Fancytree = $("#tree").fancytree("getTree"); +var tree: Fancytree.Fancytree = $("#tree").fancytree("getTree"); -var activeNode : Fancytree.FancytreeNode = tree.getRootNode(); +var activeNode: Fancytree.FancytreeNode = tree.getRootNode(); // Sort children of active node: activeNode.sortChildren(); @@ -72,15 +76,15 @@ activeNode.addChildren({ tree.loadKeyPath("/1/2", function (node, status) { if (status === "loaded") { console.log("loaded intermiediate node " + node); - } else if (status === "ok") { + } else if (status === "ok") { node.setActive(); } }); -var node = $.ui.fancytree.getNode($("#tree")); +var node = $.ui.fancytree.getNode($("#tree")); alert($.ui.fancytree.version); -var f = $.ui.fancytree.debounce(50, (a : number) => { console.log(a); }, true); -f(2); +var f = $.ui.fancytree.debounce(50, (a: number) => { console.log(a); }, true); +f(2); node = tree.getFirstChild(); node.setExpanded().done(function () { @@ -120,4 +124,4 @@ node.addChildren({ statusNodeType: "loading", unselectableIgnore: true, unselectableStatus: false, -}, 0); \ No newline at end of file +}, 0); diff --git a/types/json-patch-gen/index.d.ts b/types/json-patch-gen/index.d.ts new file mode 100644 index 0000000000..46b9a7c029 --- /dev/null +++ b/types/json-patch-gen/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for json-patch-gen 1.0 +// Project: https://github.com/gregsexton/json-patch-gen +// Definitions by: Konstantin Rohde +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare function diff(obj1: object | null, obj2: object | null): diff.JsonPatch[]; + +declare namespace diff { + type PatchOperation = "replace" | "add" | "remove"; + + interface JsonPatch { + op: PatchOperation; + path: string; + value: any; + } +} + +export = diff; +export as namespace diff; diff --git a/types/json-patch-gen/json-patch-gen-tests.ts b/types/json-patch-gen/json-patch-gen-tests.ts new file mode 100644 index 0000000000..6f45195f22 --- /dev/null +++ b/types/json-patch-gen/json-patch-gen-tests.ts @@ -0,0 +1,24 @@ +import diff = require("json-patch-gen"); + +const assertEqual = (a: object, b: object) => JSON.stringify(a) === JSON.stringify(b); +const assertLength = (a: any[], b: number) => a.length === b; + +assertLength(diff({a: "a"}, {a: "a", b: "b"}), 1); +assertEqual(diff({a: "a"}, {a: "a", b: "b"})[0], { + op: "add", + path: "/b", + value: "b" +}); + +assertLength(diff({a: "a", b: "b"}, {a: "a"}), 1); +assertEqual(diff({a: "a", b: "b"}, {a: "a"})[0], { + op: "remove", + path: "/b" +}); + +assertLength(diff({a: "a"}, {a: "b"}), 1); +assertEqual(diff({a: "a"}, {a: "b"})[0], { + op: "replace", + path: "/a", + value: "b" +}); diff --git a/types/json-patch-gen/tsconfig.json b/types/json-patch-gen/tsconfig.json new file mode 100644 index 0000000000..266cb4acae --- /dev/null +++ b/types/json-patch-gen/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", + "json-patch-gen-tests.ts" + ] +} diff --git a/types/json-patch-gen/tslint.json b/types/json-patch-gen/tslint.json new file mode 100644 index 0000000000..ece4c342d1 --- /dev/null +++ b/types/json-patch-gen/tslint.json @@ -0,0 +1,80 @@ +{ + "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-eval": 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 + } +} diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 1813b29413..1340e22d8f 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -9,22 +9,18 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface KnockoutExtensionFunctions { - [key: string]: any; -} - -interface KnockoutSubscribableFunctions extends KnockoutExtensionFunctions { +interface KnockoutSubscribableFunctions { notifySubscribers(valueToWrite?: T, event?: string): void; } -interface KnockoutComputedFunctions extends KnockoutExtensionFunctions { +interface KnockoutComputedFunctions { } -interface KnockoutObservableFunctions extends KnockoutExtensionFunctions { +interface KnockoutObservableFunctions { equalityComparer(a: T, b: T): boolean; } -interface KnockoutObservableArrayFunctions extends KnockoutExtensionFunctions { +interface KnockoutObservableArrayFunctions { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; slice(start: number, end?: number): T[]; diff --git a/types/koa-bodyparser/index.d.ts b/types/koa-bodyparser/index.d.ts index 256a2fad0a..1664e86cac 100644 --- a/types/koa-bodyparser/index.d.ts +++ b/types/koa-bodyparser/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for koa-bodyparser 4.2 +// Type definitions for koa-bodyparser 5.0 // Project: https://github.com/koajs/bodyparser -// Definitions by: Jerry Chin +// Definitions by: Jerry Chin , Anup Kishore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -18,8 +18,8 @@ import * as Koa from "koa"; declare module "koa" { interface Request { - body: any; - rawBody: any; + body: {} | null | undefined; + rawBody: {} | null | undefined; } } diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts index e7a6c39a7d..ebbfeee8f2 100644 --- a/types/koa-websocket/index.d.ts +++ b/types/koa-websocket/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for koa-websocket 2.1 +// Type definitions for koa-websocket 5.0 // Project: https://github.com/kudos/koa-websocket -// Definitions by: My Self +// Definitions by: Maël Lavault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -21,7 +21,7 @@ declare class KoaWebsocketServer { middleware: Koa.Middleware[]; constructor(app: Koa); - listen(server: http.Server | https.Server): ws.Server; + listen(options: ws.ServerOptions): ws.Server; onConnection(handler: KoaWebsocketConnectionHandler): void; use(middleware: KoaWebsocketMiddleware): this; } diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 94623c5abb..75491e24f6 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 0.5 +// Type definitions for luxon 1.2 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang @@ -180,14 +180,14 @@ declare module 'luxon' { zoneName: string; diff( other: DateTime, - unit?: string | string[], + unit?: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; - diffNow(unit?: string | string[], options?: DiffOptions): Duration; - endOf(unit: string): DateTime; + diffNow(unit?: DurationUnit | DurationUnit[], options?: DiffOptions): Duration; + endOf(unit: DurationUnit): DateTime; equals(other: DateTime): boolean; - get(unit: string): number; - hasSame(other: DateTime, unit: string): boolean; + get(unit: keyof DateTime): number; + hasSame(other: DateTime, unit: DurationUnit): boolean; minus(duration: Duration | number | DurationObject): DateTime; plus(duration: Duration | number | DurationObject): DateTime; reconfigure(properties: LocaleOptions): DateTime; @@ -195,7 +195,8 @@ declare module 'luxon' { set(values: DateObjectUnits): DateTime; setLocale(locale: any): DateTime; setZone(zone: string | Zone, options?: ZoneOptions): DateTime; - startOf(unit: string): DateTime; + startOf(unit: DurationUnit): DateTime; + toBSON(): Date; toFormat(format: string, options?: ToFormatOptions): string; toHTTP(): string; toISO(options?: ISOTimeOptions): string; @@ -207,6 +208,7 @@ declare module 'luxon' { toLocal(): DateTime; toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; + toMillis(): number; toObject(options?: { includeConfig?: boolean }): DateObject; toMillis(): number; toRFC2822(): string; @@ -238,6 +240,9 @@ declare module 'luxon' { type DurationObject = DurationObjectUnits & DurationOptions; + type DurationUnit = 'year' | 'years' | 'quarter' | 'quarters' | 'month' | 'months' | 'week' | 'weeks' | 'day' | 'days' + | 'hour' | 'hours' | 'minute' | 'minutes' | 'second' | 'seconds' | 'millisecond' | 'milliseconds'; + class Duration { static fromISO(text: string, options?: DurationOptions): Duration; static fromMillis( @@ -261,16 +266,16 @@ declare module 'luxon' { seconds: number; weeks: number; years: number; - as(unit: string): number; + as(unit: DurationUnit): number; equals(other: Duration): boolean; - get(unit: string): number; + get(unit: DurationUnit): number; minus(duration: Duration | number | DurationObject): Duration; negate(): Duration; normalize(): Duration; plus(duration: Duration | number | DurationObject): Duration; reconfigure(objectPattern: DurationOptions): Duration; set(values: DurationObjectUnits): Duration; - shiftTo(...units: string[]): Duration; + shiftTo(...units: DurationUnit[]): Duration; toFormat(format: string, options?: ToFormatOptions): string; toISO(): string; toJSON(): string; @@ -278,6 +283,7 @@ declare module 'luxon' { includeConfig?: boolean; }): DurationObject; toString(): string; + valueOf(): number; } type EraLength = 'short' | 'long'; @@ -341,23 +347,23 @@ declare module 'luxon' { abutsEnd(other: Interval): boolean; abutsStart(other: Interval): boolean; contains(dateTime: DateTime): boolean; - count(unit?: string): number; + count(unit?: DurationUnit): number; difference(...intervals: Interval[]): Interval[]; divideEqually(numberOfParts?: number): Interval[]; engulfs(other: Interval): boolean; equals(other: Interval): boolean; - hasSame(unit: string): boolean; + hasSame(unit: DurationUnit): boolean; intersection(other: Interval): Interval; isAfter(dateTime: DateTime): boolean; isBefore(dateTime: DateTime): boolean; isEmpty(): boolean; - length(unit?: string): number; + length(unit?: DurationUnit): number; overlaps(other: Interval): boolean; set(values: IntervalObject): Interval; splitAt(...dateTimes: DateTime[]): Interval[]; splitBy(duration: Duration | DurationObject | number): Interval[]; toDuration( - unit: string | string[], + unit: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; toFormat( diff --git a/types/merge-stream/index.d.ts b/types/merge-stream/index.d.ts index 5a5493b06e..6c6426b902 100644 --- a/types/merge-stream/index.d.ts +++ b/types/merge-stream/index.d.ts @@ -12,6 +12,5 @@ interface IMergedStream extends NodeJS.ReadWriteStream { isEmpty(): boolean; } -declare function merge(streams: T[]): IMergedStream; -declare function merge(...streams: T[]): IMergedStream; +declare function merge(...streams: (T | T[])[]): IMergedStream; export = merge; diff --git a/types/mocha/index.d.ts b/types/mocha/index.d.ts index 1ada77c0a4..5f0aa3baf6 100644 --- a/types/mocha/index.d.ts +++ b/types/mocha/index.d.ts @@ -2846,7 +2846,7 @@ declare global { // #region Deprecations - /** @deprecated use `Mocha.DoneCallback` instead. */ + /** @deprecated use `Mocha.Done` instead. */ type MochaDone = Mocha.Done; /** @deprecated use `Mocha.ReporterConstructor` instead. */ diff --git a/types/mosca/index.d.ts b/types/mosca/index.d.ts new file mode 100644 index 0000000000..178f150d05 --- /dev/null +++ b/types/mosca/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for mosca 2.8 +// Project: https://github.com/mcollina/mosca +// Definitions by: Joao Gabriel Gouveia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class Server { + opts: any; + modernOpts: any; + clients: any; + closed: boolean; + + constructor(opts: any, callback?: () => void); + + on(when: string, callback: (() => void) | ((client: Client) => void) | ((packet: Packet, client: Client) => void)): void; + once(when: string, callback: () => void): void; + toString(): string; + subscribe(topic: string, callback: () => void, done: () => void): void; + publish(message: Message, callback: (obj: any, packet: Packet) => void): void; + authenticate(client: Client, username: string, password: string, + callback: (obj: any, authenticated: boolean) => void): void; + published(packet: Packet, client: Client, callback: (obj: any) => void): void; + authorizePublish(client: Client, topic: string, payload: string, + callback: (obj: any, authorized: boolean) => void): void; + authorizeSubscribe(client: Client, topic: string, callback: (obj: any, authorized: boolean) => void): void; + authorizeForward(client: Client, packet: Packet, callback: (obj: any, authorized: boolean) => void): void; + storePacket(packet: Packet, callback: () => void): void; + deleteOfflinePacket(client: Client, messageId: number, callback: () => void): void; + forwardRetained(pattern: string, client: Client, callback: () => void): void; + restoreClientSubscriptions(client: Client, callback: () => void): void; + forwardOfflinePackets(client: Client, callback: () => void): void; + updateOfflinePacket(client: Client, originMessageId: number, packet: Packet, + callback: (obj: any, packet: Packet) => void): void; + persistClient(client: Client, callback: () => void): void; + close(callback?: () => void): void; + attachHttpServer(server: any, path?: any): void; +} + +export class Client { + id: string; + connection: any; + server: Server; + logger: any; + subscriptions: any; + nextId: number; + inflight: any; + inflightCounter: number; + + constructor(connection: any, server: Server); + + close(callback?: () => void, reason?: string): void; +} + +export class Stats { + maxConnectedClients: number; + connectedClients: number; + lastIntervalConnectedClients: number; + publishedMessages: number; + lastIntervalPublishedMessages: number; + started: Date; + load: any; + + wire(server: Server): void; +} + +export class Authorizer { + users: any; + + addUser(username: string, password: string, authorizePublish: string, + authorizeSubscribe: string, callback: (func: any) => void): void; +} + +export interface Packet { + topic: string; + payload: any; + messageId: string; + qos: number; + retain: boolean; +} + +export interface Message { + topic: string; + payload: any; + qos: number; + retain: boolean; +} diff --git a/types/mosca/mosca-tests.ts b/types/mosca/mosca-tests.ts new file mode 100644 index 0000000000..e03b664b1b --- /dev/null +++ b/types/mosca/mosca-tests.ts @@ -0,0 +1,16 @@ +import { Server, Client, Packet } from 'mosca'; + +const settings = { + port: 1883, + host: '0.0.0.0' +}; + +const server = new Server(settings); + +server.on('ready', () => {}); + +server.on('clientConnected', (client: Client) => {}); + +server.on('clientDisconnected', (client: Client) => {}); + +server.on('published', (packet: Packet, client: Client) => {}); diff --git a/types/mosca/tsconfig.json b/types/mosca/tsconfig.json new file mode 100644 index 0000000000..58b3dcaaf8 --- /dev/null +++ b/types/mosca/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mosca-tests.ts" + ] +} diff --git a/types/mosca/tslint.json b/types/mosca/tslint.json new file mode 100644 index 0000000000..6746359dda --- /dev/null +++ b/types/mosca/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/mustache/index.d.ts b/types/mustache/index.d.ts index 26a00fc796..2b0ab91cd0 100644 --- a/types/mustache/index.d.ts +++ b/types/mustache/index.d.ts @@ -1,53 +1,247 @@ -// Type definitions for Mustache 0.8.2 +// Type definitions for Mustache 0.8.3 // Project: https://github.com/janl/mustache.js -// Definitions by: Mark Ashley Bell +// Definitions by: Mark Ashley Bell , Manuel Thalmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Provides the functionality to render templates with `{{mustaches}}`. + */ +interface MustacheStatic { + /** + * The name of the module. + */ + name: string; -interface MustacheScanner { + /** + * The version of the module. + */ + version: string; + + /** + * The opening and closing tags to parse. + */ + tags: string; + + /** + * A simple string scanner that is used by the template parser to find tokens in template strings. + */ + Scanner: typeof MustacheScanner + + /** + * Represents a rendering context by wrapping a view object and maintaining a reference to the parent context. + */ + Context: typeof MustacheContext; + + /** + * A Writer knows how to take a stream of tokens and render them to a `string`, given a context. + * + * It also maintains a cache of templates to avoid the need to parse the same template twice. + */ + Writer: typeof MustacheWriter; + + /** + * Escapes HTML-characters. + * + * @param value + * The string to escape. + */ + escape: (value: string) => string; + + /** + * Clears all cached templates in this writer. + */ + clearCache(): void; + + /** + * Parses and caches the given template in the default writer and returns the array of tokens it contains. + * + * Doing this ahead of time avoids the need to parse templates on the fly as they are rendered. + * + * @param template + * The template to parse. + * + * @param tags + * The tags to use. + */ + parse(template: string, tags?: string[]): any; + + /** + * Renders the `template` with the given `view` and `partials` using the default writer. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + render(template: string, view: any | MustacheContext, partials?: any): string; + + /** + * Renders the `template` with the given `view` and `partials` using the default writer. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + to_html(template: string, view: any | MustacheContext, partials?: any, send?: any): any; +} + +/** + * A simple string scanner that is used by the template parser to find tokens in template strings. + */ +declare class MustacheScanner { string: string; tail: string; pos: number; + /** + * Initializes a new instance of the `MustacheScanner` class. + */ + constructor(string: string); + + /** + * Returns `true` if the tail is empty (end of string). + */ eos(): boolean; + + /** + * Tries to match the given regular expression at the current position. + * + * @param re + * The regex-pattern to match. + * + * @returns + * The matched text if it can match, the empty string otherwise. + */ scan(re: RegExp): string; + + /** + * Skips all text until the given regular expression can be matched. + * + * @param re + * The regex-pattern to match. + * + * @returns + * Returns the skipped string, which is the entire tail if no match can be made. + */ scanUntil(re: RegExp): string; } -interface MustacheContext { +/** + * Represents a rendering context by wrapping a view object and maintaining a reference to the parent context. + */ +declare class MustacheContext { view: any; parentContext: MustacheContext; + /** + * Initializes a new instance of the `MustacheContenxt` class. + */ + constructor(view: any, parentContext: MustacheContext); + + /** + * Initializes a new instance of the `MustacheContenxt` class. + */ + constructor(view: any); + + /** + * Creates a new context using the given view with this context as the parent. + * + * @param view + * The view to create the new context with. + */ push(view: any): MustacheContext; + + /** + * Returns the value of the given name in this context, traversing up the context hierarchy if the value is absent in this context's view. + * + * @param name + * The name to look up. + */ lookup(name: string): any; } -interface MustacheWriter { - (view: any): string; +/** + * A Writer knows how to take a stream of tokens and render them to a `string`, given a context. + * + * It also maintains a cache of templates to avoid the need to parse the same template twice. + */ +declare class MustacheWriter { + /** + * Initializes a new instance of the `MustacheWriter` class. + */ + constructor(); + /** + * Clears all cached templates in this writer. + */ clearCache(): void; + + /** + * Parses and caches the given `template` and returns the array of tokens that is generated from the parse. + * + * @param template + * The template to parse. + */ parse(template: string, tags?: any): any; - render(template: string, view: any, partials: any): string; + + /** + * High-level method that is used to render the given `template` with the given `view`. + * + * @param template + * The template to render. + * + * @param view + * The view to render the template with. + * + * @param partials + * Either an object that contains the names and templates of partials that are used in a template + * + * -- or -- + * + * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + */ + render(template: string, view: any | MustacheContext, partials: any): string; + + /** + * Low-level method that renders the given array of `tokens` using the given `context` and `partials`. + * + * @param tokens + * The tokens to render. + * + * @param context + * The context to use for rendering the tokens. + * + * @param partials + * The partials to use for rendering the tokens. + * + * @param originalTemplate + * An object used to extract the portion of the original template that was contained in a higher-order section. + * + * If the template doesn't use higher-order sections, this argument may be omitted. + */ renderTokens(tokens: string[], context: MustacheContext, partials: any, originalTemplate: any): string; } -interface MustacheStatic { - name: string; - version: string; - tags: string; - Scanner: MustacheScanner; - Context: MustacheContext; - Writer: MustacheWriter; - escape: any; - - clearCache(): MustacheWriter; - parse(template: string, tags?: any): any; - render(template: string, view: any, partials?: any): string; - to_html(template: string, view: any, partials?: any, send?: any): any; -} - +/** + * Provides the functionality to render templates with `{{mustaches}}`. + */ declare var Mustache: MustacheStatic; - -declare module 'mustache' { - export = Mustache; -} +export = Mustache; +export as namespace Mustache; diff --git a/types/mustache/mustache-tests.ts b/types/mustache/mustache-tests.ts index ad9c410d76..30c920a30a 100644 --- a/types/mustache/mustache-tests.ts +++ b/types/mustache/mustache-tests.ts @@ -12,3 +12,18 @@ var output2 = Mustache.render(template2, view2); var view3 = { firstName: "John", lastName: "Smith", blogURL: "http://testblog.com" }; var template3 = "

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; var html = Mustache.to_html(template3, view3); + +var view4 = new class extends Mustache.Context +{ + constructor() + { + super({}); + } + + public lookup(name: string) + { + return name.toUpperCase(); + } +}; +var template4 = "Hello, {{firstName}} {{lastName}}"; +var html4 = Mustache.render(template4, view4); \ No newline at end of file diff --git a/types/new-relic-browser/index.d.ts b/types/new-relic-browser/index.d.ts index 6d9fc22fdc..581d6efb52 100644 --- a/types/new-relic-browser/index.d.ts +++ b/types/new-relic-browser/index.d.ts @@ -13,7 +13,7 @@ declare namespace NewRelic { * @param releaseId The ID or version of this release; for example, a version number, build number * from your CI environment, GitHub SHA, GUID, or a hash of the contents. Since New Relic converts this * value into a string, you can also use null or undefined if necessary - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addRelease + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/add-release */ addRelease(releaseName: string, releaseId: string): void; @@ -23,9 +23,9 @@ declare namespace NewRelic { * @param name Name or category of the action. Reports to Insights as the actionName attribute. * @param attributes JSON object with one or more key/value pairs. * The key will report to Insights as its own PageAction attribute with the specified values. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/addPageAction + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/add-page-action */ - addPageAction(name: string, attributes: { [key: string]: string }): void; + addPageAction(name: string, attributes: { [key: string]: string | number }): void; /** * Adds a JavaScript object with a custom name, start time, etc. to an in-progress session trace. @@ -51,7 +51,7 @@ declare namespace NewRelic { * * @param Provide a meaningful error message that you can use when analyzing data on * New Relic Browser's JavaScript errors page. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/noticeError + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/notice-error */ noticeError(error: any): void; @@ -63,7 +63,7 @@ declare namespace NewRelic { * @param value Value of the attribute. Appears as the value in the named attribute column in the * PageView event. It will appear as a column in the PageAction event if you are using it. Custom attribute * values cannot be complex objects, only simple types such as strings and numbers. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setCustomAttribute + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-custom-attribute */ setCustomAttribute(name: string, value: string): void; @@ -72,7 +72,7 @@ declare namespace NewRelic { * * @param filterCallback The callback will be called with each error, so it is not * specific to one error. `err` will usually be an error object, but it can be other data types. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setErrorHandler + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-error-handler */ setErrorHandler(filterCallback: (err: any) => boolean): void; @@ -84,7 +84,7 @@ declare namespace NewRelic { * To further group these custom transactions, provide a custom host. Otherwise, the page views will be * assigned the default domain custom.transaction. Segments within the name must be explicitly added to * the Whitelist segments in your URL whitelist settings if they do not already appear. - * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/setPageViewName + * @see https://docs.newrelic.com/docs/browser/new-relic-browser/browser-agent-spa-api/set-pageview-name */ setPageViewName(name: string, host?: string): void; diff --git a/types/new-relic-browser/new-relic-browser-tests.ts b/types/new-relic-browser/new-relic-browser-tests.ts index 86ce781e18..b593f335e1 100644 --- a/types/new-relic-browser/new-relic-browser-tests.ts +++ b/types/new-relic-browser/new-relic-browser-tests.ts @@ -9,6 +9,7 @@ newrelic.addRelease('checkout page', 'a818994'); // addPageAction() newrelic.addPageAction('copy-text-button', { result: 'success' }); +newrelic.addPageAction('async-action', { duration: 3000 }); // addToTrace() newrelic.addToTrace({ diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 38e20e00c0..0955877d61 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,10 +1,43 @@ import * as React from "react"; + import { NextContext } from "."; +export interface RenderPageResponse { + buildManifest: { [key: string]: any }; + chunks: { + names: string[]; + filenames: string[]; + }; + html?: string; + head: Array>; + errorHtml: string; +} + +export interface PageProps { + url: string; +} + +export interface AnyPageProps extends PageProps { + [key: string]: any; +} + +export type Enhancer = (page: React.ComponentType

) => React.ComponentType; + +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage(enhancer?: Enhancer): RenderPageResponse; // tslint:disable-line:no-unnecessary-generics +} + export interface DocumentProps { __NEXT_DATA__?: any; dev?: boolean; - chunks?: string[]; + chunks?: { + names: string[]; + filenames: string[]; + }; html?: string; head?: Array>; errorHtml?: string; @@ -13,21 +46,9 @@ export interface DocumentProps { [key: string]: any; } -/** - * Context object used inside `Document` - */ -export interface NextDocumentContext extends NextContext { - /** A callback that executes the actual React rendering logic (synchronously) */ - renderPage( - cb?: (enhancer: () => JSX.Element) => React.ComponentType - ): { - [key: string]: any - }; -} - export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} export default class extends React.Component { - static getInitialProps(ctx: NextContext): DocumentProps; + static getInitialProps(ctx: NextDocumentContext): Promise | DocumentProps; } diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 2b3257cd25..f727262b0e 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,7 +1,7 @@ -import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; +import Document, { DocumentProps, Enhancer, Head, Main, NextScript, NextDocumentContext, PageProps } from 'next/document'; import * as React from "react"; -const results = ( +const basicResults = ( @@ -11,16 +11,18 @@ const results = ( ); -const Wrapper: React.SFC = ({ children }) => {children}; - -export default class MyDocument extends Document { +class MyDoc extends Document { static async getInitialProps({ renderPage }: NextDocumentContext) { - // Without callback - const page = renderPage(); - // With callback - const differentPage = renderPage(App => props => ); + // without callback + const _page = renderPage(); + + // with callback + const enhancer: Enhancer = (App) => (props) => (); + const { html, head, errorHtml, chunks, buildManifest } = renderPage(enhancer); + const style = {}; - return { ...page, style }; + + return { html, head, errorHtml, chunks, buildManifest, style }; } render() { @@ -33,8 +35,45 @@ export default class MyDocument extends Document {

+ {this.props.children} ); } } + +const extendedResults = ( + + + + +

Hey there

+
+); + +const renderPage: NextDocumentContext['renderPage'] = (enhancer) => ({ + buildManifest: {}, + chunks: { names: [], filenames: [] }, + html: '', + head: [], + errorHtml: '', +}); + +interface PageInitialProps extends PageProps { + foo: string; + bar: number; +} + +interface ProcessedInitialProps { + fooLength: number; + bar: boolean; +} + +const enhancerExplicit: Enhancer = (App) => (props) => (); +const enhancerInferred = (App: React.ComponentType) => ({ foo, bar }: PageInitialProps) => (); +const explicitEnhancerRenderResponse = renderPage(enhancerExplicit); +const inferredEnhancerRenderResponse = renderPage(enhancerInferred); +const defaultedTypesRenderResponse = renderPage((App) => (props) => ()); +const defaultedTypesExtendedRenderResponse = renderPage((App) => (props) => ()); +const explicitTypesRenderResponseOne = renderPage((App) => (props) => ()); +const explicitTypesRenderResponseTwo = renderPage((App) => ({ foo, bar }) => ()); diff --git a/types/node-vault/index.d.ts b/types/node-vault/index.d.ts index 835e364ae7..f21d625822 100644 --- a/types/node-vault/index.d.ts +++ b/types/node-vault/index.d.ts @@ -111,7 +111,7 @@ declare namespace NodeVault { debug?(...args: any[]): any; tv4?(...args: any[]): any; commands?: Array<{ method: string, path: string, scheme: any }>; - mustache?: MustacheStatic; + mustache?: typeof mustache; "request-promise"?: any; Promise?: PromiseConstructor; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index fc2bcb51b9..eea1cd2bb0 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -13559,12 +13559,46 @@ declare namespace OfficeExtension { } declare namespace OfficeExtension { + /** + * Specifies which properties of an object should be loaded. This load happens when the sync() method is executed. This synchronizes the states between Office objects and corresponding JavaScript proxy objects. + * + * @remarks + * + * For Word, the preferred method for specifying the properties and paging information is by using a string literal. The first two examples show the preferred way to request the text and font size properties for paragraphs in a paragraph collection: + * + * `context.load(paragraphs, 'text, font/size');` + * + * `paragraphs.load('text, font/size');` + * + * Here is a similar example using object notation (includes paging): + * + * `context.load(paragraphs, {select: 'text, font/size', expand: 'font', top: 50, skip: 0});` + * + * `paragraphs.load({select: 'text, font/size', expand: 'font', top: 50, skip: 0});` + * + * Note that if we don't specify the specific properties on the font object in the select statement, the expand statement by itself would indicate that all of the font properties are loaded. + */ interface LoadOption { + /** + * A comma-delimited string, or array of strings, that specifies the properties/relationships to load. + */ select?: string | string[]; + /** + * A comma-delimited string, or array of strings, that specifies the relationships to load. + */ expand?: string | string[]; + /** + * Only usable on collection types. Specifies the maximum number of collection items that can be included in the result. + */ top?: number; + /** + * Only usable on collection types. Specifies the number of items in the collection that are to be skipped and not included in the result. If top is specified, the result set will start after skipping the specified number of items. + */ skip?: number; } + /** + * Provides an option for suppressing an error when the object that is used to set multiple properties tries to set read-only properties. + */ interface UpdateOptions { /** * Throw an error if the passed-in property list includes read-only properties (default = true). @@ -13592,7 +13626,11 @@ declare namespace OfficeExtension { /** Request headers */ requestHeaders: { [name: string]: string }; - /** Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. */ + /** Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. + * + * @param object The object whose properties are loaded. + * @param option A comma-delimited string, or array of strings, that specifies the properties/relationships to load, or an {@link Office.OfficeExtension.LoadOption} object. + */ load(object: ClientObject, option?: string | string[] | LoadOption): void; /** @@ -13652,7 +13690,9 @@ declare namespace OfficeExtension { */ extendedErrorLogging: boolean; }; - + /** + * Provides information about an error. + */ interface DebugInfo { /** Error code string, such as "InvalidArgument". */ code: string; @@ -13660,24 +13700,20 @@ declare namespace OfficeExtension { message: string; /** Inner error, if applicable. */ innerError?: DebugInfo | string; - /** The object type and property or method name (or similar information), if available. */ errorLocation?: string; - /** * The statement that caused the error, if available. * * This statement will never contain any potentially-sensitive data and may not match the code exactly as written, but will be a close approximation. */ statements?: string; - /** * The statements that closely precede and follow the statement that caused the error, if available. * * These statements will never contain any potentially-sensitive data and may not match the code exactly as written, but will be a close approximation. */ surroundingStatements?: string[]; - /** * All statements in the batch request (including any potentially-sensitive information that was specified in the request), if available. * @@ -13731,11 +13767,23 @@ declare namespace OfficeExtension { declare namespace OfficeExtension { /** Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. */ class TrackedObjects { - /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ + /** + * Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. + * + * This method also has the following signature: + * + * `add(objects: ClientObject[]): void;` Where objects is an array of objects to be tracked. + */ add(object: ClientObject): void; - /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ + /** Track a set of objects for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ add(objects: ClientObject[]): void; - /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ + /** + * Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. + * + * This method also has the following signature: + * + * `remove(objects: ClientObject[]): void;` Where objects is an array of objects to be removed. + */ remove(object: ClientObject): void; /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ remove(objects: ClientObject[]): void; diff --git a/types/p-timeout/index.d.ts b/types/p-timeout/index.d.ts index 882cc7adc8..40e1dc6410 100644 --- a/types/p-timeout/index.d.ts +++ b/types/p-timeout/index.d.ts @@ -5,8 +5,8 @@ export = pTimeout; -declare function pTimeout(input: Promise, ms: number, message?: string | pTimeout.TimeoutError): Promise; -declare function pTimeout(input: Promise, ms: number, fallback: () => R | Promise): Promise; +declare function pTimeout(input: PromiseLike, ms: number, message?: string | pTimeout.TimeoutError): Promise; +declare function pTimeout(input: PromiseLike, ms: number, fallback: () => R | Promise): Promise; declare namespace pTimeout { class TimeoutError extends Error { diff --git a/types/pngjs/index.d.ts b/types/pngjs/index.d.ts index d5476e9e1f..f5ac2e6d2a 100644 --- a/types/pngjs/index.d.ts +++ b/types/pngjs/index.d.ts @@ -85,7 +85,7 @@ export interface PackerOptions { export type PNGOptions = BaseOptions & ParserOptions & PackerOptions; -export type ColorType = 0 | 1 | 2 | 4; +export type ColorType = 0 | 2 | 4 | 6; export interface Metadata { width: number; diff --git a/types/pouchdb-find/index.d.ts b/types/pouchdb-find/index.d.ts index 7f5f925f8c..1ccd3d4c14 100644 --- a/types/pouchdb-find/index.d.ts +++ b/types/pouchdb-find/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for pouchdb-find 6.3 // Project: https://pouchdb.com/ // Definitions by: Jakub Navratil +// Sebastian Ramirez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -100,7 +101,7 @@ declare namespace PouchDB { } interface FindResponse { - docs: Array>; + docs: Array>; } interface CreateIndexOptions { diff --git a/types/react-amplitude/index.d.ts b/types/react-amplitude/index.d.ts new file mode 100644 index 0000000000..c6a9ff3d2d --- /dev/null +++ b/types/react-amplitude/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for react-amplitude 0.1 +// Project: https://github.com/rorygarand/react-amplitude +// Definitions by: Raymond Ho +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface AmplitudeInstance { + init(apiKey: string, userId?: string, config?: any, cb?: () => void): void; + amplitude(): void; + clearUserProperties(): void; + getSessionId(): void; + identify(idObj: any, cb: () => void): void; + isNewSession(): void; + logEvent(eventType: string, eventProperties: {}, cb: () => void): void; + logEventWithTimestamp(eventType: string, eventProperties: {}, timestamp: number, cb: () => void): void; + resetUserId(): void; + setUserId(userId: string): void; + setUserProperties(userProps: any): void; +} + +declare const Amplitude: AmplitudeInstance; + +export default Amplitude; diff --git a/types/react-amplitude/react-amplitude-tests.ts b/types/react-amplitude/react-amplitude-tests.ts new file mode 100644 index 0000000000..f311f8491f --- /dev/null +++ b/types/react-amplitude/react-amplitude-tests.ts @@ -0,0 +1,2 @@ +import Amplitude from 'react-amplitude'; +Amplitude.init('YOUR_UNIQUE_TRACKING_CODE'); diff --git a/types/react-amplitude/tsconfig.json b/types/react-amplitude/tsconfig.json new file mode 100644 index 0000000000..6f7a8a296e --- /dev/null +++ b/types/react-amplitude/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", + "react-amplitude-tests.ts" + ] +} diff --git a/types/react-amplitude/tslint.json b/types/react-amplitude/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-amplitude/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-autocomplete/index.d.ts b/types/react-autocomplete/index.d.ts index 58339d3b31..0de7cd7eac 100644 --- a/types/react-autocomplete/index.d.ts +++ b/types/react-autocomplete/index.d.ts @@ -143,8 +143,27 @@ declare namespace Autocomplete { open?: boolean; debug?: boolean; } + + interface State { + /** + * True when the menu is visible. Provided to `onMenuVisibilityChange`. + */ + isOpen: boolean; + + /** + * Index of the highlighted item, `null` if none currently is. + */ + highlightedIndex: number | null; + + /** + * These three `menu___` values are used in CSS to layout the menu. + */ + menuLeft?: number; + menuTop?: number; + menuWidth?: number; + } } -declare class Autocomplete extends Component { +declare class Autocomplete extends Component { /** * Autocomplete exposes a subset of `HTMLInputElement` properties to the parent component. * They can be accessed through Autocomplete's `ref` prop. diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index 8d25e79407..3cb5e026f8 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for react-beautiful-dnd 6.0 +// Type definitions for react-beautiful-dnd 7.1 // Project: https://github.com/atlassian/react-beautiful-dnd // Definitions by: varHarrie // Bradley Ayers // Austin Turner +// Mark Nelissen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -84,8 +85,8 @@ export class Droppable extends React.Component {} */ export interface NotDraggingStyle { - transform: null | string; - transition: null | 'none'; + transform?: string; + transition?: 'none'; } export interface DraggingStyle { @@ -97,14 +98,14 @@ export interface DraggingStyle { top: number; left: number; margin: 0; - transform: null | string; + transform?: string; transition: 'none'; zIndex: ZIndex; } export interface DraggableProvidedDraggableProps { // inline style - style: null | DraggingStyle | NotDraggingStyle; + style?: DraggingStyle | NotDraggingStyle; // used for shared global styles 'data-react-beautiful-dnd-draggable': string; } diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index ef1b359e5d..52903e8375 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -35,6 +35,7 @@ declare module "react-jsonschema-form" { >; safeRenderCompletion?: boolean; transformErrors?: (errors: AjvError[]) => AjvError[]; + idPrefix?: string; // HTML Attributes id?: string; diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 667106d916..f05820bbce 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-places-autocomplete 6.1 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner +// Andrew Makarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 // @@ -56,6 +57,11 @@ export interface PropTypes { } export function geocodeByAddress(address: string, callback: (results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => void): void; +export function geocodeByAddress(address: string): Promise; + export function geocodeByPlaceId(placeId: string, callback: (results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => void): void; +export function geocodeByPlaceId(placeId: string): Promise; + +export function getLatLng(results: google.maps.GeocoderResult): Promise; export default class PlacesAutocomplete extends React.Component {} diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx new file mode 100644 index 0000000000..41e6ff37b4 --- /dev/null +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -0,0 +1,52 @@ +import * as React from 'react'; +import PlacesAutocomplete, { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete'; + +class Test extends React.Component { + state = { + address: 'San Francisco, CA', + placeId: '12345', + }; + + handleFormSubmit = (event: any) => { + event.preventDefault(); + + const { address, placeId } = this.state; + + // Old API + geocodeByAddress(address, (results, status) => { + const latLng = getLatLng(results[0]); + console.info(latLng, status); + }); + + geocodeByPlaceId(placeId, (results, status) => { + const latLng = getLatLng(results[0]); + console.info(latLng, status); + }); + + // New API + geocodeByAddress(address) + .then((results) => getLatLng(results[0])) + .then((latLng) => console.log('Success', latLng)) + .catch((error) => console.error('Error', error)); + + geocodeByPlaceId(placeId) + .then((results) => getLatLng(results[0])) + .then((latLng) => console.log('Success', latLng)) + .catch((error) => console.error('Error', error)); + } + + onChange = (address: string) => this.setState({ address }); + + render() { + const inputProps = { + value: this.state.address, + onChange: this.onChange, + }; + + return ( +
+ + + ); + } +} diff --git a/types/react-places-autocomplete/tsconfig.json b/types/react-places-autocomplete/tsconfig.json index 02dbd0279c..6f45bffc51 100644 --- a/types/react-places-autocomplete/tsconfig.json +++ b/types/react-places-autocomplete/tsconfig.json @@ -1,12 +1,19 @@ { - "files": ["index.d.ts"], + "files": [ + "index.d.ts", + "react-places-autocomplete-tests.tsx" + ], "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, + "jsx": "react", "baseUrl": "../", "typeRoots": ["../"], "types": [], diff --git a/types/react-rnd/index.d.ts b/types/react-rnd/index.d.ts index 31d477ca5e..ff5ac2078e 100644 --- a/types/react-rnd/index.d.ts +++ b/types/react-rnd/index.d.ts @@ -4,117 +4,118 @@ // fsubal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 -import React = require('react'); +import * as React from "react"; type CSSProperties = React.CSSProperties; -declare namespace Rnd { - type Direction = - | 'bottom' - | 'bottomLeft' - | 'bottomRight' - | 'left' - | 'right' - | 'top' - | 'topLeft' - | 'topRight'; +export type Direction = + | "bottom" + | "bottomLeft" + | "bottomRight" + | "left" + | "right" + | "top" + | "topLeft" + | "topRight"; - interface Enable { - bottom?: boolean; - bottomLeft?: boolean; - bottomRight?: boolean; - left?: boolean; - right?: boolean; - top?: boolean; - topLeft?: boolean; - topRight?: boolean; - } - - interface HandleClasses { - bottom?: string; - bottomLeft?: string; - bottomRight?: string; - left?: string; - right?: string; - top?: string; - topLeft?: string; - topRight?: string; - } - - interface HandleStyles { - bottom?: CSSProperties; - bottomLeft?: CSSProperties; - bottomRight?: CSSProperties; - left?: CSSProperties; - right?: CSSProperties; - top?: CSSProperties; - topLeft?: CSSProperties; - topRight?: CSSProperties; - } - - interface Position { - x: number; - y: number; - } - - interface Size { - width: number; - height: number; - } - - interface DraggableData { - node: HTMLElement; - x: number; - y: number; - deltaX: number; - deltaY: number; - lastX: number; - lastY: number; - } - - type DraggableEventHandler = (e: MouseEvent | TouchEvent, data: DraggableData) => void|false; - - type ResizeHandler = ( - e: MouseEvent|TouchEvent, - direction: Direction, - ref: HTMLDivElement, - delta: Size, - position: Position - ) => void; - - interface Options { - default: { - x?: number; - y?: number; - width?: number|string; - height?: number|string; - }; - className: string; - style: any; - width: number|string; - height: number|string; - minWidth: number|string; - minHeight: number|string; - maxWidth: number|string; - maxHeight: number|string; - z: number; - resizeHandleClasses: HandleClasses; - resizeHandleStyles: HandleStyles; - - lockAspectRatio: boolean; - enableResizing?: Enable; - disableDragging?: boolean; - - onResizeStart: () => void; - onResize: () => void; - onResizeStop: ResizeHandler; - - onDragStart: DraggableEventHandler; - onDrag: DraggableEventHandler; - onDragStop: DraggableEventHandler; - } +export interface Enable { + bottom?: boolean; + bottomLeft?: boolean; + bottomRight?: boolean; + left?: boolean; + right?: boolean; + top?: boolean; + topLeft?: boolean; + topRight?: boolean; } -declare class Rnd extends React.Component> {} +export interface HandleClasses { + bottom?: string; + bottomLeft?: string; + bottomRight?: string; + left?: string; + right?: string; + top?: string; + topLeft?: string; + topRight?: string; +} -export = Rnd; +export interface HandleStyles { + bottom?: CSSProperties; + bottomLeft?: CSSProperties; + bottomRight?: CSSProperties; + left?: CSSProperties; + right?: CSSProperties; + top?: CSSProperties; + topLeft?: CSSProperties; + topRight?: CSSProperties; +} + +export interface Position { + x: number; + y: number; +} + +export interface Size { + width: number; + height: number; +} + +export interface DraggableData { + node: HTMLElement; + x: number; + y: number; + deltaX: number; + deltaY: number; + lastX: number; + lastY: number; +} + +export type DraggableEventHandler = ( + e: MouseEvent | TouchEvent, + data: DraggableData +) => void | false; + +export type ResizeHandler = ( + e: MouseEvent | TouchEvent, + direction: Direction, + ref: HTMLDivElement, + delta: Size, + position: Position +) => void; + +export interface Options { + default: { + x?: number; + y?: number; + width?: number | string; + height?: number | string; + }; + className: string; + style: any; + width: number | string; + height: number | string; + minWidth: number | string; + minHeight: number | string; + maxWidth: number | string; + maxHeight: number | string; + z: number; + resizeHandleClasses: HandleClasses; + resizeHandleStyles: HandleStyles; + + lockAspectRatio: boolean; + enableResizing?: Enable; + disableDragging?: boolean; + + onResizeStart: () => void; + onResize: () => void; + onResizeStop: ResizeHandler; + + onDragStart: DraggableEventHandler; + onDrag: DraggableEventHandler; + onDragStop: DraggableEventHandler; +} + +declare class Rnd extends React.Component> {} + +export default Rnd; diff --git a/types/react-rnd/react-rnd-tests.tsx b/types/react-rnd/react-rnd-tests.tsx index 9f1cbc593c..461a0d03ba 100644 --- a/types/react-rnd/react-rnd-tests.tsx +++ b/types/react-rnd/react-rnd-tests.tsx @@ -1,7 +1,7 @@ -import React = require('react'); -import Rnd = require('react-rnd'); +import * as React from 'react'; +import { default as Rnd, ResizeHandler } from "react-rnd"; -const onResize: Rnd.ResizeHandler = (e, direction, ref, delta, position) => { +const onResize: ResizeHandler = (e, direction, ref, delta, position) => { direction === 'right'; delta.width; delta.height; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 8ee5fa9698..336ab9ade4 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 7.2 +// Type definitions for redux-form 7.3 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full // Daniel Lytkin @@ -7,6 +7,7 @@ // Alex Young // Anton Novik // Huw Martin +// Tim de Koning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 diff --git a/types/redux-form/lib/reducer.d.ts b/types/redux-form/lib/reducer.d.ts index 9e865fc6c1..6324ab92e6 100644 --- a/types/redux-form/lib/reducer.d.ts +++ b/types/redux-form/lib/reducer.d.ts @@ -18,7 +18,7 @@ export interface FormStateMap { export interface FormState { registeredFields: RegisteredFieldState[]; fields?: {[name: string]: FieldState}; - values?: { [fieldName: string]: string }; + values?: { [fieldName: string]: any }; active?: string; anyTouched?: boolean; submitting?: boolean; diff --git a/types/redux-form/v6/lib/reducer.d.ts b/types/redux-form/v6/lib/reducer.d.ts index 1800391863..9089a8802d 100644 --- a/types/redux-form/v6/lib/reducer.d.ts +++ b/types/redux-form/v6/lib/reducer.d.ts @@ -29,7 +29,7 @@ export interface FormStateMap { export interface FormState { registeredFields: RegisteredFieldState[]; fields?: {[name: string]: FieldState}; - values?: { [fieldName: string]: string }; + values?: { [fieldName: string]: any }; active?: string; anyTouched?: boolean; submitting?: boolean; diff --git a/types/sax/index.d.ts b/types/sax/index.d.ts index 4c556d8aab..40d17caa4d 100644 --- a/types/sax/index.d.ts +++ b/types/sax/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for sax-js 1.x // Project: https://github.com/isaacs/sax-js // Definitions by: Asana +// Evert Pot // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -44,7 +45,7 @@ export interface Tag extends BaseTag { export declare function parser(strict: boolean, opt: SAXOptions): SAXParser; export declare class SAXParser { - constructor(strict: boolean, opt: SAXOptions); + constructor(strict: boolean, opt?: SAXOptions); // Methods end(): void; diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index d3d2ef5b6a..b781523ef2 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -18,6 +18,10 @@ declare namespace SeamlessImmutable { merger?(a: any, b: any, config: any): any; } + interface ReplaceConfig { + deep: boolean; + } + interface Options { prototype?: any; } @@ -75,6 +79,8 @@ declare namespace SeamlessImmutable { without(property: K): ImmutableObject; without(...properties: K[]): ImmutableObject; without(filter: (value: T[K], key: K) => boolean): ImmutableObject; + + replace(valueObj: S, options?: ReplaceConfig): ImmutableObject; } interface ImmutableArrayMixin { @@ -92,6 +98,8 @@ declare namespace SeamlessImmutable { function isImmutable(target: any): boolean; function ImmutableError(message: string): Error; + + function replace(obj: ImmutableObject, valueObj: S, options?: ReplaceConfig): ImmutableObject; } declare function SeamlessImmutable(obj: T[], options?: SeamlessImmutable.Options): SeamlessImmutable.ImmutableArray; diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index ddec87e81d..cccb2d7f96 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -44,6 +44,12 @@ interface ExtendedUser extends User { { const isImmutable: boolean = Immutable.isImmutable(Immutable.from([0, 2])); + const user1: Immutable.ImmutableObject = Immutable.from({ + firstName: 'Angry', + lastName: 'Monkey' + }); + const replacedUser01 = Immutable.replace(user1, { firstName: 'Super', lastName: 'Monkey' }); + const replacedUser02 = Immutable.replace(user1, { firstName: 'Super', lastName: 'Monkey' }, { deep: true }); } // @@ -124,4 +130,8 @@ interface ExtendedUser extends User { const firstNameWithDynamicPathWithDefault = immutableUser.getIn(['first' + 'name'], ''); const line1WithoutDefault = immutableUserEx.getIn(['address', 'line1']); const line1WithDefault = immutableUserEx.getIn(['address', 'line1'], ''); + + // replace + const replacedUser01 = immutableUser.replace({ firstName: 'Super', lastName: 'Monkey' }); + const replacedUser02 = immutableUser.replace({ firstName: 'Super', lastName: 'Monkey' }, { deep: true }); } diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 0d9a96bfc4..f003b77731 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3233,9 +3233,10 @@ declare namespace sequelize { as?: string; /** - * The association you want to eagerly load. (This can be used instead of providing a model/as pair) + * The association you want to eagerly load. (This can be used instead of providing a model/as pair). + * You can also use the association alias. */ - association?: IncludeAssociation; + association?: IncludeAssociation | string; /** * Where clauses to apply to the child models. Note that this converts the eager load to an inner join, diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index eafa70b641..11b6775846 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -4339,7 +4339,7 @@ declare namespace sequelize { * * PostgreSQL only */ - deferrable?: Deferrable; + deferrable?: DeferrableInitiallyDeferred | DeferrableInitiallyImmediate | DeferrableNot | DeferrableSetDeferred | DeferrableSetImmediate; } diff --git a/types/signale/index.d.ts b/types/signale/index.d.ts new file mode 100644 index 0000000000..d14660e5a9 --- /dev/null +++ b/types/signale/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for signale 1.1 +// Project: https://github.com/klauscfhq/signale +// Definitions by: Resi Respati +// Kingdaro +// Joydip Roy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +declare namespace signale { + type DefaultMethods = + | "await" + | "complete" + | "error" + | "debug" + | "fatal" + | "fav" + | "info" + | "note" + | "pause" + | "pending" + | "star" + | "start" + | "success" + | "warn" + | "watch" + | "log"; + + interface CommandType { + /** The icon corresponding to the logger. */ + badge: string; + /** + * The color of the label, can be any of the foreground colors supported by + * [chalk](https://github.com/chalk/chalk#colors). + */ + color: string; + /** The label used to identify the type of the logger. */ + label: string; + } + + interface SignaleConfig { + /** Display the scope name of the logger. */ + displayScope?: boolean; + /** Display the badge of the logger. */ + displayBadge?: boolean; + /** Display the current local date in `YYYY-MM-DD` format. */ + displayDate?: boolean; + /** Display the name of the file that the logger is reporting from. */ + displayFilename?: boolean; + /** Display the label of the logger. */ + displayLabel?: boolean; + /** Display the current local time in `HH:MM:SS` format. */ + displayTimestamp?: boolean; + /** Underline the logger label. */ + underlineLabel?: boolean; + /** Underline the logger message. */ + underlineMessage?: boolean; + } + + interface SignaleOptions { + /** Sets the configuration of an instance overriding any existing global or local configuration. */ + config?: SignaleConfig; + /** + * Name of the scope. + */ + scope?: string; + /** + * Holds the configuration of the custom and default loggers. + */ + types?: Partial>; + interactive?: boolean; + timers?: Map; + /** + * Destination to which the data is written, can be any valid + * [Writable stream](https://nodejs.org/api/stream.html#stream_writable_streams). + */ + stream?: NodeJS.WriteStream; + } + + interface SignaleConstructor { + new ( + options?: SignaleOptions + ): Signale; + } + + interface SignaleBase { + /** + * Sets the configuration of an instance overriding any existing global or local configuration. + * + * @param configObj Can hold any of the documented options. + */ + config(configObj: SignaleConfig): Signale; + /** + * Defines the scope name of the logger. + * + * @param name Can be one or more comma delimited strings. + */ + scope(...name: string[]): Signale; + /** Clears the scope name of the logger. */ + unscope(): void; + /** + * Sets a timers and accepts an optional label. If none provided the timer will receive a unique label automatically. + * + * @param label Label corresponding to the timer. Each timer must have its own unique label. + * @returns a string corresponding to the timer label. + */ + time(label?: string): string; + /** + * Deactivates the timer to which the given label corresponds. If no label + * is provided the most recent timer, that was created without providing a + * label, will be deactivated. + * + * @param label Label corresponding to the timer, each timer has its own unique label. + * @param span Total running time. + */ + timeEnd( + label?: string, + span?: number + ): { label: string; span?: number }; + } + + type LoggerFunc = (message?: any, ...optionalArgs: any[]) => void; + type Signale = SignaleBase & + Record & + Record; +} + +declare const signale: signale.Signale & { + Signale: signale.SignaleConstructor; + SignaleConfig: signale.SignaleConfig; + SignaleOptions: signale.SignaleOptions; + DefaultMethods: signale.DefaultMethods; +}; + +export = signale; diff --git a/types/signale/signale-tests.ts b/types/signale/signale-tests.ts new file mode 100644 index 0000000000..7fd96638a8 --- /dev/null +++ b/types/signale/signale-tests.ts @@ -0,0 +1,129 @@ +import { Signale, SignaleOptions } from "signale"; + +// --- Test 1: Basic Usage --- // + +const signale = new Signale(); + +signale.success("Operation successful"); +signale.debug("Hello", "from", "L59"); +signale.pending("Write release notes for 1.2.0"); +signale.fatal(new Error("Unable to acquire lock")); +signale.watch("Recursively watching build directory..."); +signale.complete({ + prefix: "[task]", + message: "Fix issue #59", + suffix: "(@klauscfhq)" +}); + +// --- Test 2: Custom Loggers --- // + +type CustomLogger = "remind" | "santa"; + +const optionsCustom: SignaleOptions = { + stream: process.stdout, + scope: "custom", + types: { + remind: { + badge: "**", + color: "yellow", + label: "reminder" + }, + santa: { + badge: "🎅", + color: "red", + label: "santa" + } + } +}; + +const custom = new Signale(optionsCustom); +custom.remind("Improve documentation."); +custom.santa("Hoho! You have an unused variable on L45."); +custom.debug("This should still work"); + +// --- Test 3: Overriding Default Loggers --- // + +const optionsOverride: SignaleOptions = { + types: { + error: { + badge: "!!", + color: "red", + label: "fatal error" + }, + success: { + badge: "++", + color: "green", + label: "huge success" + } + } +}; + +signale.error("Default Error Log"); +signale.success("Default Success Log"); + +const customOverride = new Signale(optionsOverride); +customOverride.error("Custom Error Log"); +customOverride.success("Custom Success Log"); + +// --- Test 4: Scoped Loggers --- // + +const optionsScope: SignaleOptions = { + scope: "global scope" +}; + +const global = new Signale(optionsScope); +global.success("Successful Operation"); + +const global2 = signale.scope("global scope"); +global2.success("Hello from the global scope"); + +function scopedTest() { + const outer = global2.scope("outer", "scope"); + outer.success("Hello from the outer scope"); + + setTimeout(() => { + const inner = outer.scope("inner", "scope"); + inner.success("Hello from the inner scope"); + }, 500); +} + +scopedTest(); + +// --- Test 5: Timers --- // + +signale.time("test"); +signale.time(); +signale.time(); + +setTimeout(() => { + signale.timeEnd(); + signale.timeEnd(); + signale.timeEnd("test"); +}, 500); + +// --- Test 6: Configuration --- // + +// Overrides any existing `package.json` config +signale.config({ + displayFilename: true, + displayTimestamp: true, + displayDate: false +}); + +signale.success("Hello from the Global scope"); + +function scopedConfigTest() { + // `fooLogger` inherits the config of `signale` + const fooLogger = signale.scope("foo scope"); + + // Overrides both `signale` and `package.json` configs + fooLogger.config({ + displayFilename: true, + displayTimestamp: false, + displayDate: true + }); + + fooLogger.success("Hello from the Local scope"); +} + +scopedConfigTest(); diff --git a/types/signale/tsconfig.json b/types/signale/tsconfig.json new file mode 100644 index 0000000000..ef5b67d941 --- /dev/null +++ b/types/signale/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "signale-tests.ts" + ] +} diff --git a/types/signale/tslint.json b/types/signale/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/signale/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts new file mode 100644 index 0000000000..ea6fdc03db --- /dev/null +++ b/types/styled-system/index.d.ts @@ -0,0 +1,603 @@ +// Type definitions for styled-system 2.3 +// Project: https://github.com/jxnblk/styled-system#readme +// Definitions by: Marshall Bowers +// Ben McCormick +// Justin Bennett +// Christopher Pappas +// Eloy Durán +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * Core + */ + +export type GlobalStyleValues = "inherit" | "initial" | "unset"; + +export interface BaseTheme { + breakpoints?: number[]; + space?: number[]; + fontSizes?: number[]; + colors?: { + [name: string]: string; + }; +} + +/** + * Space + */ + +export type ResponsiveValue = T | Array; + +export type SpaceValue = number | string; +export type ResponsiveSpaceValue = ResponsiveValue; + +export interface SpaceProps { + m?: ResponsiveSpaceValue; + mt?: ResponsiveSpaceValue; + mr?: ResponsiveSpaceValue; + mb?: ResponsiveSpaceValue; + ml?: ResponsiveSpaceValue; + mx?: ResponsiveSpaceValue; + my?: ResponsiveSpaceValue; + p?: ResponsiveSpaceValue; + pt?: ResponsiveSpaceValue; + pr?: ResponsiveSpaceValue; + pb?: ResponsiveSpaceValue; + pl?: ResponsiveSpaceValue; + px?: ResponsiveSpaceValue; + py?: ResponsiveSpaceValue; +} + +export function space(...args: any[]): any; + +/** + * Width + */ + +export type WidthValue = number | string; +export type ResponsiveWidthValue = ResponsiveValue; + +export interface WidthProps { + width?: ResponsiveWidthValue; +} + +export interface MinWidthProps { + minWidth?: ResponsiveWidthValue; +} + +export interface MaxWidthProps { + maxWidth?: ResponsiveWidthValue; +} + +export function width(...args: any[]): any; +export function minWidth(...args: any[]): any; +export function maxWidth(...args: any[]): any; + +/** + * Height + */ + +export type HeightValue = number | string; +export type ResponsiveHeightValue = ResponsiveValue; + +export interface HeightProps { + height?: ResponsiveHeightValue; +} + +export interface MinHeightProps { + minHeight?: ResponsiveHeightValue; +} + +export interface MaxHeightProps { + maxHeight?: ResponsiveHeightValue; +} + +export function height(...args: any[]): any; +export function minHeight(...args: any[]): any; +export function maxHeight(...args: any[]): any; + +/** + * Font Size + */ + +export type FontSizeValue = number | string; +export type ResponsiveFontSizeValue = ResponsiveValue; + +export interface FontSizeProps { + fontSize?: ResponsiveFontSizeValue; +} + +export function fontSize(...args: any[]): any; + +/** + * Color + */ +export type ColorValue = string; +export type ResponsiveColorValue = ResponsiveValue; + +export interface ColorProps { + color?: ResponsiveColorValue; +} + +export function color(...args: any[]): any; + +/** + * Typography + */ +export interface FontFamilyProps { + fontFamily?: string; +} +export function fontFamily(...args: any[]): any; + +export type TextAlignValue = + | "left" + | "right" + | "center" + | "justify" + | "justify-all" + | "start" + | "end" + | "match-parent"; +export type ResponsiveTextAlignValue = ResponsiveValue; + +export interface TextAlignProps { + textAlign?: ResponsiveTextAlignValue; +} + +export function textAlign(...args: any[]): any; + +export type LineHeightValue = number | string; +export type ResponsiveLineHeightValue = ResponsiveValue; +export interface LineHeightProps { + lineHeight?: ResponsiveLineHeightValue; +} +export function lineHeight(...args: any[]): any; + +export type FontWeightValue = + | GlobalStyleValues + | "normal" + | "bold" + | "lighter" + | "bolder" + | number; + +export interface FontWeightProps { + fontWeight?: FontWeightValue; +} + +export function fontWeight(...args: any[]): any; + +export type LetterSpacingValue = number | string; +export type ResponsiveLetterSpacingValue = ResponsiveValue; +export interface LetterSpacingProps { + letterSpacing?: ResponsiveLetterSpacingValue; +} +export function letterSpacing(...args: any[]): any; + +/** + * Layout + */ + +export type DisplayValue = + | "inline" + | "block" + | "contents" + | "flex" + | "grid" + | "inline-block"; +export type ResponsiveDisplayValue = ResponsiveValue; +export interface DisplayProps { + display?: ResponsiveDisplayValue; +} + +export function display(...args: any[]): any; + +export interface SizeProps { + size?: ResponsiveWidthValue | ResponsiveHeightValue; +} + +export function size(...args: any[]): any; + +export type RatioValue = SpaceValue; + +export interface RatioProps { + ratio?: RatioValue; +} + +export function ratio(...args: any[]): any; + +/** + * Flexbox + */ + +export type AlignItemsValue = + | "normal" + | "stretch" + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "self-start" + | "self-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignItemsValue = ResponsiveValue; + +export interface AlignItemsProps { + align?: ResponsiveAlignItemsValue; + alignItems?: ResponsiveAlignItemsValue; +} + +export function alignItems(...args: any[]): any; + +export type JustifyContentValue = + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "space-between" + | "space-around" + | "space-evenly" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveJustifyContentValue = ResponsiveValue< + JustifyContentValue +>; + +export interface JustifyContentProps { + justify?: ResponsiveJustifyContentValue; + justifyContent?: ResponsiveJustifyContentValue; +} + +export function justifyContent(...args: any[]): any; + +export type FlexWrapValue = true | "nowrap" | "wrap" | "wrap-reverse"; + +export interface FlexWrapProps { + flexWrap?: FlexWrapValue; +} + +export function flexWrap(...args: any[]): any; + +export type FlexDirectionValue = + | GlobalStyleValues + | "row" + | "row-reverse" + | "column" + | "column-reverse"; + +export type ResponsiveFlexDirectionValue = ResponsiveValue; + +export interface FlexDirectionProps { + flexDirection?: ResponsiveFlexDirectionValue; +} + +export function flexDirection(...args: any[]): any; + +export type FlexValue = number | string; +export type ResponsiveFlexValue = ResponsiveValue; + +export interface FlexProps { + flex?: ResponsiveFlexValue; +} + +export function flex(...args: any[]): any; + +export type AlignContentValue = + | GlobalStyleValues + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "normal" + | "baseline" + | "first baseline" + | "last baseline" + | "space-between" + | "space-around" + | "space-evenly" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignContentValue = ResponsiveValue; + +export interface AlignContentProps { + alignContent?: ResponsiveAlignItemsValue; +} + +export function alignContent(...args: any[]): any; + +export type JustifySelfValue = + | GlobalStyleValues + | "auto" + | "normal" + | "stretch" + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "self-start" + | "self-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "safe center" + | "unsafe center"; + +export type ResponsiveJustifySelfValue = ResponsiveValue; + +export interface JustifySelfProps { + justifySelf?: ResponsiveJustifySelfValue; +} + +export function justifySelf(...args: any[]): any; + +export type AlignSelfValue = + | "auto" + | "normal" + | "center" + | "start" + | "end" + | "self-start" + | "self-end" + | "flex-start" + | "flex-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignSelfValue = ResponsiveValue; + +export interface AlignSelfProps { + alignSelf?: ResponsiveAlignSelfValue; +} + +export function alignSelf(...args: any[]): any; + +export type OrderValue = GlobalStyleValues | number; +export type ResponsiveOrderValue = ResponsiveValue; + +export interface OrderProps { + order?: ResponsiveOrderValue; +} + +export function order(...args: any[]): any; + +export type FlexBasisValue = + | GlobalStyleValues + | "auto" + | "fill" + | "max-content" + | "min-content" + | "fit-content" + | "content"; + +export interface FlexBasisProps { + // TODO: The FlexBasisValue currently really only exists for documentation + // purposes, because flex-basis also accepts `Nem` and `Npx` strings. + // Not sure there’s a way to still have the union values show up as + // auto-completion results. + flexBasis?: FlexBasisValue | string; +} + +export function flexBasis(...args: any[]): any; + +/** + * Grid Layout + */ + +// TODO: Add grid values + +/** + * Background + */ + +export type BackgroundValue = string; +export interface BackgroundProps { + background?: BackgroundValue; + bg?: BackgroundValue; +} + +export function background(...args: any[]): any; + +export type BackgroundImageValue = string; +export interface BackgroundImageProps { + /** + * Value will be wrapped in url() + */ + backgroundImage?: BackgroundImageValue; +} + +export function backgroundImage(...args: any[]): any; + +export type BackgroundSizeValue = string; +export interface BackgroundSizeProps { + backgroundSize?: BackgroundSizeValue; +} + +export function backgroundSize(...args: any[]): any; + +export type BackgroundPositionValue = string; +export interface BackgroundPositionProps { + backgroundPosition?: BackgroundPositionValue; +} + +export function backgroundPosition(...args: any[]): any; + +export type BackgroundRepeatValue = string; +export interface BackgroundRepeatProps { + backgroundRepeat?: BackgroundRepeatValue; +} + +export function backgroundRepeat(...args: any[]): any; + +/** + * Misc + */ + +export type BorderRadiusValue = string | number; +export interface BorderRadiusProps { + borderRadius?: BorderRadiusValue; +} +export function borderRadius(...args: any[]): any; + +export type BorderColorValue = string; +export interface BorderColorProps { + borderColor?: BorderColorValue; +} +export function borderColor(...args: any[]): any; + +export type BorderValue = string | number; +export type ResponsiveBorderValue = ResponsiveValue; +export interface BorderProps { + border?: ResponsiveBorderValue; + borderTop?: ResponsiveBorderValue; + borderRight?: ResponsiveBorderValue; + borderBottom?: ResponsiveBorderValue; + borderLeft?: ResponsiveBorderValue; +} +export function borders(...args: any[]): any; + +export type BoxShadowValue = string | number; +export interface BoxShadowProps { + boxShadow?: BoxShadowValue; +} +export function boxShadow(...arg: any[]): any; + +/** + * Position + */ + +export type PositionValue = + | "static" + | "relative" + | "absolute" + | "sticky" + | "fixed"; +export type ResponsivePositionValue = ResponsiveValue; +export interface PositionProps { + position?: ResponsivePositionValue; +} +export function position(...args: any[]): any; + +export type ZIndexValue = GlobalStyleValues | "auto" | number; + +export interface ZIndexProps { + zIndex?: ZIndexValue; +} +export function zIndex(...args: any[]): any; + +export type TopValue = string | number; +export type ResponsiveTopValue = ResponsiveValue; +export interface TopProps { + top?: ResponsiveTopValue; +} +export function top(...args: any[]): any; + +export type RightValue = string | number; +export type ResponsiveRightValue = ResponsiveValue; +export interface RightProps { + right?: ResponsiveRightValue; +} +export function right(...args: any[]): any; + +export type BottomValue = string | number; +export type ResponsiveBottomValue = ResponsiveValue; +export interface BottomProps { + bottom?: ResponsiveBottomValue; +} +export function bottom(...args: any[]): any; + +export type LeftValue = string | number; +export type ResponsiveLeftValue = ResponsiveValue; +export interface LeftProps { + left?: ResponsiveLeftValue; +} +export function left(...args: any[]): any; + +/** + * Pseudo-classes + */ + +export interface PseudoStyleValue { + color?: ColorValue; + backgroundColor?: ColorValue; + borderColor?: BorderColorValue; + boxShadow?: BoxShadowValue; + textDecoration?: string; +} +export type HoverValue = PseudoStyleValue; +export interface HoverProps { + hover?: HoverValue; +} +export function hover(...args: any[]): any; + +export type FocusValue = PseudoStyleValue; +export interface FocusProps { + focus?: FocusValue; +} +export function focus(...args: any[]): any; + +export type ActiveValue = PseudoStyleValue; +export interface ActiveProps { + active?: ActiveValue; +} +export function active(...args: any[]): any; + +export type DisabledValue = PseudoStyleValue; +export interface DisabledProps { + disabledStyle?: DisabledValue; +} +export function disabled(...args: any[]): any; + +/** + * Utilities + */ + +export function theme(keys: string): any; +export function themeGet(keys: string, fallback?: string): any; + +export function cleanElement(component: any): any; + +export function removeProps(props: any): any; + +/** + * Low-level style export functions + */ + +export interface LowLevelStylefunctionArguments { + prop: string; + cssProperty?: string; + key?: string; + numberToPx?: boolean; + alias?: string; + getter?: () => any; +} + +export function style(args: LowLevelStylefunctionArguments): any; + +export function responsiveStyle(args: LowLevelStylefunctionArguments): any; + +export function pseudoStyle(args: LowLevelStylefunctionArguments): any; diff --git a/types/styled-system/package.json b/types/styled-system/package.json new file mode 100644 index 0000000000..da1a3181d0 --- /dev/null +++ b/types/styled-system/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "styled-components": "^3.3.2" + } +} diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx new file mode 100644 index 0000000000..78340eb3d8 --- /dev/null +++ b/types/styled-system/styled-system-tests.tsx @@ -0,0 +1,351 @@ +// Example uses styled-components, but styled-system works with most other css-in-js libraries as well +import * as React from "react"; +import styled from "styled-components"; +import { + themeGet, + space, + width, + fontSize, + color, + fontFamily, + display, + SpaceProps, + WidthProps, + ColorProps, + DisplayProps, + FontSizeProps, + FontFamilyProps, + textAlign, + TextAlignProps, + background, + BackgroundProps, + maxWidth, + MaxWidthProps, + lineHeight, + LineHeightProps, + FontWeightProps, + fontWeight, + letterSpacing, + LetterSpacingProps, + minWidth, + MinWidthProps, + HeightProps, + height, + MaxHeightProps, + maxHeight, + minHeight, + MinHeightProps, + size, + SizeProps, + RatioProps, + ratio, + alignItems, + AlignItemsProps, + AlignContentProps, + alignContent, + justifyContent, + JustifyContentProps, + FlexWrapProps, + flexWrap, + flexBasis, + FlexBasisProps, + borderColor, + BorderColorProps, + flexDirection, + FlexDirectionProps, + flex, + FlexProps, + justifySelf, + JustifySelfProps, + alignSelf, + AlignSelfProps, + borders, + BorderProps, + borderRadius, + BorderRadiusProps, + position, + PositionProps, + zIndex, + ZIndexProps, + top, + bottom, + left, + right, + TopProps, + BottomProps, + LeftProps, + RightProps, + boxShadow, + BoxShadowProps, + backgroundImage, + backgroundPosition, + backgroundRepeat, + backgroundSize, + BackgroundImageProps, + BackgroundPositionProps, + BackgroundRepeatProps, + BackgroundSizeProps, + hover, + HoverProps, + focus, + FocusProps, + active, + ActiveProps, + disabled, + DisabledProps +} from "styled-system"; + +interface BoxProps + extends SpaceProps, + WidthProps, + FontSizeProps, + ColorProps, + DisplayProps, + BackgroundProps, + MaxWidthProps, + MinWidthProps, + HeightProps, + MaxHeightProps, + MinHeightProps, + SizeProps, + RatioProps, + BorderColorProps, + FlexProps, + JustifySelfProps, + AlignSelfProps, + BorderProps, + BorderRadiusProps, + PositionProps, + ZIndexProps, + TopProps, + BottomProps, + LeftProps, + RightProps, + BoxShadowProps, + BackgroundImageProps, + BackgroundPositionProps, + BackgroundRepeatProps, + BackgroundSizeProps, + HoverProps, + FocusProps, + ActiveProps, + DisabledProps {} +const Box = styled.div.attrs({})` + +border-radius: ${themeGet("radii.small", "4px")}; + ${space} + ${width} + ${fontSize} + ${color} + ${display} + ${background} + ${maxWidth} + ${minWidth} + ${height} + ${maxHeight} + ${minHeight} + ${size} + ${ratio} + ${borderColor} + ${flex} + ${justifySelf} + ${alignSelf} + ${borders} + ${borderRadius} + ${position} + ${zIndex} + ${top} + ${bottom} + ${left} + ${right} + ${boxShadow} + ${backgroundImage} + ${backgroundPosition} + ${backgroundRepeat} + ${backgroundSize} + ${hover} + ${focus} + ${active} + ${disabled} +`; + +interface TextProps + extends FontSizeProps, + FontFamilyProps, + TextAlignProps, + LineHeightProps, + FontWeightProps, + LetterSpacingProps {} +const Text = styled.div.attrs({})` + ${fontSize}; + ${fontFamily}; + ${textAlign}; + ${lineHeight}; + ${fontWeight}; + ${letterSpacing}; +`; + +interface FlexComponentProps + extends AlignItemsProps, + AlignContentProps, + JustifyContentProps, + FlexWrapProps, + FlexBasisProps, + FlexDirectionProps {} +const Flex = styled.div.attrs({})` + ${alignItems}; + ${alignContent}; + ${justifyContent}; + ${flexWrap}; + ${flexBasis}; + ${flexDirection}; +`; + +const test = () => ( +
+ // width: 50% + + // font-size: 20px (theme.fontSizes[4]) + + // margin: 16px (theme.space[2]) + + // padding: 32px (theme.space[3]) + + // color + + // color: #333 (theme.colors.gray[0]) + + // background color + + // responsive width + + // responsive font-size + + // responsive margin + + // responsive padding + + // examples (margin prop) // sets margin value of `theme.space[2]` + + // sets margin value of `-1 * theme.space[2]` + + // sets a margin value of `16px` since it's greater than + `theme.space.length` + + // sets margin `'auto'` + + // sets margin `8px` on all viewports and `16px` from the smallest + breakpoint and up + + // examples // width `50%` + + // width `256px` + + // width `'2em'` + + // width `100%` on all viewports and `50%` from the smallest breakpoint + and up + + // examples // font-size of `theme.fontSizes[3]` + + // font-size `32px` + + // font-size `'2em'` + + // font-size `10px` on all viewports and `12px` from the smallest + breakpoint and up + + // examples // picks the value defined in `theme.colors['blue']` + + // picks up a nested color value using dot notation // + `theme.colors['gray'][0]` + + // raw CSS color value + + // fontFamily + + // textAlign (responsive) + + + // lineHeight + + // fontWeight + + // letterSpacing + + // display (responsive) + + + // maxWidth (responsive) + + + // minWidth (responsive) + + + // height (responsive) + + + // maxHeight (responsive) + + + // minHeight (responsive) + + + // size (responsive, width & height) + + + // ratio (height: 0 & paddingBottom) + + // alignItems (responsive) + + // alignContent (responsive) + + // justifyContent (responsive) + + // flexWrap (responsive) + + // flexBasis (responsive) + + // flexDirection (responsive) + + // flex (responsive) + + // justifySelf (responsive) + + // alignSelf (responsive) + + + + + + + // borderColor + + // borderRadius + + // position (responsive) + + // zIndex + + // top, right, bottom, left (responsive) + + // boxShadow + + // backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat + + + + + +
+); diff --git a/types/styled-system/tsconfig.json b/types/styled-system/tsconfig.json new file mode 100644 index 0000000000..2cc754217f --- /dev/null +++ b/types/styled-system/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "styled-system-tests.tsx"] +} diff --git a/types/styled-system/tslint.json b/types/styled-system/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/styled-system/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/index.d.ts b/types/three/index.d.ts index cc26a82225..88cd09c70a 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -33,6 +33,7 @@ export * from "./three-effectcomposer"; export * from "./three-examples"; export * from "./three-fbxloader"; export * from "./three-FirstPersonControls"; +export * from "./three-gltfexporter"; export * from "./three-maskpass"; export * from "./three-mtlloader"; export * from "./three-objloader"; diff --git a/types/three/test/webvr/webvr.ts b/types/three/test/webvr/webvr.ts index e831e493ee..dfc8576f59 100644 --- a/types/three/test/webvr/webvr.ts +++ b/types/three/test/webvr/webvr.ts @@ -10,4 +10,10 @@ const obj = new THREE.Object3D(); renderer.vr.setPoseTarget(obj); renderer.vr.dispose(); + + const scene = new THREE.Scene(); + const render = function() { + renderer.render(scene, camera); + } + renderer.animate(render); } diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index b0798a61d9..7736b46fa4 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -5519,6 +5519,12 @@ export class WebGLRenderer implements Renderer { renderBufferDirect(camera: Camera, fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + /** + * A build in function that can be used instead of requestAnimationFrame. For WebVR projects this function must be used. + * @param callback The function will be called every available frame. If `null` is passed it will stop any already ongoing animation. + */ + animate(callback: Function): void; + /** * Render a scene using a camera. * The render is done to the renderTarget (if specified) or to the canvas as usual. diff --git a/types/three/three-gltfexporter.d.ts b/types/three/three-gltfexporter.d.ts new file mode 100644 index 0000000000..2bdba480a7 --- /dev/null +++ b/types/three/three-gltfexporter.d.ts @@ -0,0 +1,9 @@ +import { Object3D } from "three"; + +export class GLTFExporter { + constructor(); + + parse(input: Object3D, onCompleted: (gltf: object) => void, options: object): null; + +} + diff --git a/types/tinycon/index.d.ts b/types/tinycon/index.d.ts new file mode 100644 index 0000000000..3f385603cc --- /dev/null +++ b/types/tinycon/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for tinycon 0.6 +// Project: https://github.com/tommoor/tinycon +// Definitions by: Daniel Waxweiler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function setBubble(count: number): void; + +export function setOptions(options: TinyconOptions): void; + +export interface TinyconOptions { + abbreviate?: boolean; + background?: string; + color?: string; + fallback?: boolean; + font?: string; + height?: number; + width?: number; +} diff --git a/types/tinycon/tinycon-tests.ts b/types/tinycon/tinycon-tests.ts new file mode 100644 index 0000000000..b4bcc304ac --- /dev/null +++ b/types/tinycon/tinycon-tests.ts @@ -0,0 +1,13 @@ +import * as Tinycon from 'tinycon'; + +Tinycon.setOptions({ + abbreviate: false, + background: '#549A2F', + color: '#ffffff', + fallback: true, + font: '10px arial', + height: 9, + width: 7 +}); + +Tinycon.setBubble(7); diff --git a/types/tinycon/tsconfig.json b/types/tinycon/tsconfig.json new file mode 100644 index 0000000000..2410f4bd8a --- /dev/null +++ b/types/tinycon/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", + "tinycon-tests.ts" + ] +} diff --git a/types/tinycon/tslint.json b/types/tinycon/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinycon/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index 89d28766b3..f4a7be74b4 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -24,7 +24,7 @@ declare module 'twit' { */ export interface Contributors { id: number, - id_str: number, + id_str: string, screen_name: string, } @@ -169,7 +169,7 @@ declare module 'twit' { created_at: string, current_user_retweet?: { id: number, - id_str: number, + id_str: string, }, entities: Entities, favorite_count?: number, @@ -257,7 +257,7 @@ declare module 'twit' { id?: string, slug?: string, status?: string, - user_id?: number, + user_id?: number | string, lat?: number, long?: number, follow?: boolean, diff --git a/types/w3c-web-usb/index.d.ts b/types/w3c-web-usb/index.d.ts index d481245e14..d596351a5b 100644 --- a/types/w3c-web-usb/index.d.ts +++ b/types/w3c-web-usb/index.d.ts @@ -62,7 +62,7 @@ declare class USBAlternateInterface { readonly interfaceClass: number; readonly interfaceSubclass: number; readonly interfaceProtocol: number; - readonly alternatinterfaceName?: string; + readonly interfaceName?: string; readonly endpoints: USBEndpoint[]; } @@ -146,6 +146,7 @@ declare class USBDevice { transferOut(endpointNumber: number, data: BufferSource): Promise; isochronousTransferIn(endpointNumber: number, packetLengths: number[]): Promise; isochronousTransferOut(endpointNumber: number, data: BufferSource, packetLengths: number[]): Promise; + reset(): Promise; } interface Navigator { diff --git a/types/w3c-web-usb/w3c-web-usb-tests.ts b/types/w3c-web-usb/w3c-web-usb-tests.ts index fe29480479..49efebcdbc 100644 --- a/types/w3c-web-usb/w3c-web-usb-tests.ts +++ b/types/w3c-web-usb/w3c-web-usb-tests.ts @@ -43,6 +43,7 @@ navigator.usb.addEventListener('disconnect', evt => { }); async function handleConnectedDevice(device: USBDevice) { + await device.reset(); connectedDevices.push(device); await device.open(); diff --git a/types/webpack-serve/index.d.ts b/types/webpack-serve/index.d.ts index 5a1a302af0..f0426c5ad7 100644 --- a/types/webpack-serve/index.d.ts +++ b/types/webpack-serve/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for webpack-serve 1.0 // Project: https://github.com/webpack-contrib/webpack-serve // Definitions by: Ryan Clark +// Jokcy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -21,7 +22,7 @@ declare module 'webpack' { } declare function WebpackServe( - { config }: { config: webpack.Configuration } + options: WebpackServe.Options ): Promise; declare namespace WebpackServe { diff --git a/types/webpack-serve/webpack-serve-tests.ts b/types/webpack-serve/webpack-serve-tests.ts index 2a29cec317..d22c1adfea 100644 --- a/types/webpack-serve/webpack-serve-tests.ts +++ b/types/webpack-serve/webpack-serve-tests.ts @@ -1,19 +1,25 @@ import webpack = require('webpack'); import serve = require('webpack-serve'); -const compiler = webpack(); +const config: webpack.Configuration = { + mode: 'development', + entry: ['index.js'], // when use compiler entry must be array or object +}; + +const serveConfig = { + http2: true, + dev: { + publicPath: '/', + logLevel: 'info' + }, + host: 'localhost' +}; + +const compiler = webpack(config); const server = serve({ - config: { - serve: { - http2: true, - dev: { - publicPath: '/', - logLevel: 'info' - }, - host: 'localhost' - }, - }, + compiler, + ...serveConfig }); server @@ -22,3 +28,25 @@ server server.close(); }); }); + +const config2: webpack.Configuration = { + ...config, + serve: { + ...serveConfig, + port: 8888, + hot: { + port: 8889 + } + }, +}; + +const server2 = serve({ + config: config2 +}); + +server2 + .then((server) => { + server.on('listening', () => { + server.close(); + }); + }); diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 55d7dbd801..d482955d2c 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -61,24 +61,22 @@ declare namespace webpack { /** Like resolve but for loaders. */ resolveLoader?: ResolveLoader; /** - * Specify dependencies that shouldn’t be resolved by webpack, but should become dependencies of the resulting bundle. - * The kind of the dependency depends on output.libraryTarget. + * Specify dependencies that shouldn’t be resolved by webpack, but should become dependencies of the resulting bundle. + * The kind of the dependency depends on output.libraryTarget. */ externals?: ExternalsElement | ExternalsElement[]; /** - *
    - *
  • "web" Compile for usage in a browser-like environment (default)
  • - *
  • "webworker" Compile as WebWorker
  • - *
  • "node" Compile for usage in a node.js-like environment (use require to load chunks)
  • - *
  • "async-node" Compile for usage in a node.js-like environment (use fs and vm to load chunks async)
  • - *
  • "node-webkit" Compile for usage in webkit, uses jsonp chunk loading but also supports builtin node.js modules plus require(“nw.gui”) (experimental)
  • - *
  • "atom" Compile for usage in electron (formerly known as atom-shell), supports require for modules necessary to run Electron.
  • - *
  • "electron-renderer" Compile for Electron for renderer process, providing a target using JsonpTemplatePlugin, FunctionModulePlugin - * for browser environments and NodeTargetPlugin and ExternalsPlugin for CommonJS and Electron built-in modules.
  • - *
  • "electron-main" Compile for Electron for main process.
  • - *
  • "atom" Alias for electron-main
  • - *
  • "electron" Alias for electron-main
  • - *
      + * - "web" Compile for usage in a browser-like environment (default). + * - "webworker" Compile as WebWorker. + * - "node" Compile for usage in a node.js-like environment (use require to load chunks). + * - "async-node" Compile for usage in a node.js-like environment (use fs and vm to load chunks async). + * - "node-webkit" Compile for usage in webkit, uses jsonp chunk loading but also supports builtin node.js modules plus require(“nw.gui”) (experimental) + * - "atom" Compile for usage in electron (formerly known as atom-shell), supports require for modules necessary to run Electron. + * - "electron-renderer" Compile for Electron for renderer process, providing a target using JsonpTemplatePlugin, FunctionModulePlugin for browser + * environments and NodeTargetPlugin and ExternalsPlugin for CommonJS and Electron built-in modules. + * - "electron-main" Compile for Electron for main process. + * - "atom" Alias for electron-main. + * - "electron" Alias for electron-main. */ target?: 'web' | 'webworker' | 'node' | 'async-node' | 'node-webkit' | 'atom' | 'electron' | 'electron-renderer' | 'electron-main' | ((compiler?: any) => void); /** Report the first error as a hard error instead of tolerating it. */ @@ -171,17 +169,15 @@ declare namespace webpack { library?: string | string[]; /** * Which format to export the library: - *
        - *
      • "var" - Export by setting a variable: var Library = xxx (default)
      • - *
      • "this" - Export by setting a property of this: this["Library"] = xxx
      • - *
      • "commonjs" - Export by setting a property of exports: exports["Library"] = xxx
      • - *
      • "commonjs2" - Export by setting module.exports: module.exports = xxx
      • - *
      • "amd" - Export to AMD (optionally named)
      • - *
      • "umd" - Export to AMD, CommonJS2 or as property in root
      • - *
      • "window" - Assign to window
      • - *
      • "assign" - Assign to a global variable
      • - *
      • "jsonp" - Generate Webpack JSONP module
      • - *
      + * - "var" - Export by setting a variable: var Library = xxx (default) + * - "this" - Export by setting a property of this: this["Library"] = xxx + * - "commonjs" - Export by setting a property of exports: exports["Library"] = xxx + * - "commonjs2" - Export by setting module.exports: module.exports = xxx + * - "amd" - Export to AMD (optionally named) + * - "umd" - Export to AMD, CommonJS2 or as property in root + * - "window" - Assign to window + * - "assign" - Assign to a global variable + * - "jsonp" - Generate Webpack JSONP module */ libraryTarget?: 'var' | 'this' | 'commonjs' | 'commonjs2' | 'amd' | 'umd' | 'window' | 'assign' | 'jsonp'; /** Configure which module or modules will be exposed via the `libraryTarget` */ @@ -955,42 +951,9 @@ declare namespace webpack { usedModuleIds: any; getStats(): Stats; addModule(module: CompilationModule, cacheGroup: any): any; - // getModule(module) - // findModule(identifier) - // waitForBuildingFinished(module, callback) - // buildModule(module, optional, origin, dependencies, thisCallback) - // processModuleDependencies(module, callback) - // addModuleDependencies(module, dependencies, bail, cacheGroup, recursive, callback) // tslint:disable-next-line:ban-types addEntry(context: any, entry: any, name: any, callback: Function): void; - // prefetch(context, dependency, callback) - // rebuildModule(module, thisCallback) - // finish() - // unseal() - // seal(callback) - // sortModules(modules) - // reportDependencyErrorsAndWarnings(module, blocks) - // addChunkInGroup(name, module, loc, request) - // addChunk(name) - // assignIndex(module) - // assignDepth(module) - // processDependenciesBlocksForChunkGroups(inputChunkGroups) - // removeReasonsOfDependencyBlock(module, block) - // patchChunksAfterReasonRemoval(module, chunk) - // removeChunkFromDependencies(block, chunk) - // applyModuleIds() - // applyChunkIds() - // sortItemsWithModuleIds() - // sortItemsWithChunkIds() - // summarizeDependencies() - // createHash() - // modifyHash(update) - // createModuleAssets() - // createChunkAssets() getPath(filename: string, data: {hash?: any, chunk?: any, filename?: string, basename?: string, query?: any}): string; - // createChildCompiler(name, outputOptions, plugins) - // checkConstraints() - /** * @deprecated Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead */ @@ -1131,10 +1094,14 @@ declare namespace webpack { | 'verbose'; interface ToJsonOptionsObject { + /** fallback value for stats options when an option is not defined (has precedence over local webpack defaults) */ + all?: boolean; /** Add asset Information */ assets?: boolean; /** Sort assets by a field */ assetsSort?: string; + /** Add built at time information */ + builtAt?: boolean; /** Add information about cached (not built) modules */ cached?: boolean; /** Show cached assets (setting this to `false` only shows emitted files) */ diff --git a/types/webpack/webpack-tests.ts b/types/webpack/webpack-tests.ts index b7b9ca8913..913eea0b19 100644 --- a/types/webpack/webpack-tests.ts +++ b/types/webpack/webpack-tests.ts @@ -383,6 +383,7 @@ webpack({ const jsonStatsWithAllOptions = stats.toJson({ assets: true, assetsSort: "field", + builtAt: true, cached: true, children: true, chunks: true, diff --git a/types/wepy/app.d.ts b/types/wepy/app.d.ts new file mode 100644 index 0000000000..cc2636ed92 --- /dev/null +++ b/types/wepy/app.d.ts @@ -0,0 +1,13 @@ +export interface AppConfig { + appEvents?: string[]; + pageEvents?: string[]; + noPromiseAPI?: string[] | { [name: string]: boolean }; +} + +export interface AppConstructor { + new (): app; +} + +export default class app { + $init(wepy: any, config: AppConfig): any; +} diff --git a/types/wepy/base.d.ts b/types/wepy/base.d.ts new file mode 100644 index 0000000000..91c934b8b1 --- /dev/null +++ b/types/wepy/base.d.ts @@ -0,0 +1,12 @@ +import page, { PageConstructor } from "./page"; +import app, { AppConstructor, AppConfig } from "./app"; + +declare const defaultExport: { + $createApp?: (appClass: AppConstructor, appConfig: AppConfig) => app; + $createPage?: ( + pageClass: PageConstructor, + pagePath: string | boolean + ) => page; +}; + +export default defaultExport; diff --git a/types/wepy/component.d.ts b/types/wepy/component.d.ts new file mode 100644 index 0000000000..ddcea63ed6 --- /dev/null +++ b/types/wepy/component.d.ts @@ -0,0 +1,20 @@ +import event from "./event"; + +export default class component { + $isComponent: boolean; + $prefix: string; + data: { [name: string]: any }; + + computed?: { [name: string]: (self?: component) => any }; + methods?: { [name: string]: (evt?: event) => any }; + + $init($wxpage: any, $root: any, $parent: any): void; + $initMixins(): void; + onLoad(): void; + setData(k: string | string[], v: any): void; + getWxPage(): any; + $setIndex(index: number): void; + $getComponent(com: any): any; + $apply(fn: () => void): void; + $nextTick(fn: () => void): void; +} diff --git a/types/wepy/event.d.ts b/types/wepy/event.d.ts new file mode 100644 index 0000000000..f3a0d6c5a8 --- /dev/null +++ b/types/wepy/event.d.ts @@ -0,0 +1,6 @@ +export default class event { + active: boolean; + constructor(name: string, source: any, type: any); + $destroy(): void; + $transfor(wxevent: any[]): void; +} diff --git a/types/wepy/index.d.ts b/types/wepy/index.d.ts new file mode 100644 index 0000000000..bff673ee8c --- /dev/null +++ b/types/wepy/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for wepy 1.7 +// Project: https://github.com/Tencent/wepy#readme +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import component from "./component"; +import mixin from "./mixin"; +import event from "./event"; +import page from "./page"; +import app from "./app"; +import util from "./util"; +import base from "./base"; +import { WxEnhances } from "./wx_enhanced"; + +interface DefaultExport extends WxEnhances { + event: typeof event; + app: typeof app; + component: typeof component; + page: typeof page; + mixin: typeof mixin; + $createApp: typeof base.$createApp; + $createPage: typeof base.$createPage; + $isEmpty: typeof util.$isEmpty; + $isEqual: typeof util.$isEqual; + $isDeepEqual: typeof util.$isDeepEqual; + $has: typeof util.$has; + $extend: typeof util.$extend; + $isPlainObject: typeof util.$isPlainObject; + $copy: typeof util.$copy; +} + +declare const defaultExport: DefaultExport; + +export default defaultExport; diff --git a/types/wepy/mixin.d.ts b/types/wepy/mixin.d.ts new file mode 100644 index 0000000000..c70aedd7b1 --- /dev/null +++ b/types/wepy/mixin.d.ts @@ -0,0 +1 @@ +export default class mixin {} diff --git a/types/wepy/page.d.ts b/types/wepy/page.d.ts new file mode 100644 index 0000000000..7655621106 --- /dev/null +++ b/types/wepy/page.d.ts @@ -0,0 +1,23 @@ +import component from "./component"; + +export interface UrlParam { + url: string; +} + +export interface PageConstructor { + new (): page; +} + +export default class page extends component { + $preloadData: { [key: string]: any }; + $init(wxpage: any, $parent: any): any; + $route( + type: "redirectTo" | "navigateTo", + url: string | UrlParam, + params?: { [name: string]: any } + ): any; + $preload(key: string | { [key: string]: any }, data: any): any; + $switch(url: string | UrlParam): any; + $redirect(url: string, params?: object): any; + $back(delta: number | { delta: number }): any; +} diff --git a/types/wepy/tsconfig.json b/types/wepy/tsconfig.json new file mode 100644 index 0000000000..f363a749a1 --- /dev/null +++ b/types/wepy/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "app.d.ts", + "base.d.ts", + "component.d.ts", + "event.d.ts", + "index.d.ts", + "mixin.d.ts", + "page.d.ts", + "util.d.ts", + "wx_enhanced.d.ts", + "wepy-tests.ts" + ] +} diff --git a/types/wepy/tslint.json b/types/wepy/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/wepy/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/wepy/util.d.ts b/types/wepy/util.d.ts new file mode 100644 index 0000000000..cff1be1ce5 --- /dev/null +++ b/types/wepy/util.d.ts @@ -0,0 +1,15 @@ +declare const defaultExport: { + $isEmpty: (obj: object) => boolean; + $isEqual: (a: any, b: any, aStack?: any[], bStack?: any[]) => boolean; + $isDeepEqual: (a: any, b: any, aStack?: any[], bStack?: any[]) => boolean; + $has: (obj: object, path: string) => boolean; + $extend: () => any; + $copy: (obj: T, deep?: boolean) => T; + $isPlainObject: (obj: any) => boolean; + $resolvePath: (route: string, url: string) => string; + $getParams: (url: string) => object; + hyphenate: (str: string) => string; + camelize: (str: string) => string; +}; + +export default defaultExport; diff --git a/types/wepy/wepy-tests.ts b/types/wepy/wepy-tests.ts new file mode 100644 index 0000000000..9ed5462fb9 --- /dev/null +++ b/types/wepy/wepy-tests.ts @@ -0,0 +1,41 @@ +import wepy from "wepy"; + +export class MyComponent extends wepy.component { + data = { + reveal: false, + img: "", + animationData: "", + imgClassName: "", + imgMode: "scaleToFill", + title: "loading", + titleClassName: "" + }; + + methods = {}; + + onLoad() { + super.onLoad(); + } +} + +export class BindJwc extends wepy.page { + config = { + navigationBarTitleText: "校历", + enablePullDownRefresh: true + }; + mixins = []; + data = {}; + computed = { + termName(): number { + return 1; + } + }; + methods = { + returnToday(): number { + return 123; + } + }; + + init() {} + async onLoad() {} +} diff --git a/types/wepy/wx_enhanced.d.ts b/types/wepy/wx_enhanced.d.ts new file mode 100644 index 0000000000..d5e66dea34 --- /dev/null +++ b/types/wepy/wx_enhanced.d.ts @@ -0,0 +1,391 @@ +export interface WechatProfileDetails { + photoFilePath?: string; + nickName?: string; + lastName?: string; + middleName?: string; + firstName?: string; + remark?: string; + mobilePhoneNumber?: string; + email?: string; + url?: string; + workAddressCountry?: string; + workAddressState?: string; + workAddressCity?: string; + workAddressStreet?: string; + workAddressPostalCode?: string; + homeFaxNumber?: string; + homePhoneNumber?: string; + homeAddressCountry?: string; + homeAddressState?: string; + homeAddressCity?: string; + homeAddressStreet?: string; + homeAddressPostalCode?: string; +} + +export interface RotateAnimation { + rotate(deg: number): Animation; + rotateX(deg: number): Animation; + rotateY(deg: number): Animation; + rotateZ(deg: number): Animation; + rotate3d(): Animation; +} + +export interface ScaleAnimation { + scale(sx: number): Animation; + scaleX(sx: number): Animation; + scaleY(sy: number): Animation; + scaleZ(sz: number): Animation; + scale3d(): Animation; +} + +export interface TranslateAnimation { + translate(tx: number): Animation; + translateX(tx: number): Animation; + translateY(ty: number): Animation; + translateZ(tz: number): Animation; + translate3d(): Animation; +} + +export interface SkewAnimation { + skew(ax: number): Animation; + skewX(ax: number): Animation; + skewY(ay: number): Animation; +} + +export interface Animation + extends RotateAnimation, + ScaleAnimation, + SkewAnimation, + TranslateAnimation { + opacity(x: number): Animation; + backgroundColor(x: string): Animation; + width(x: number): Animation; + height(x: number): Animation; + top(x: number): Animation; + left(x: number): Animation; + bottom(x: number): Animation; + right(x: number): Animation; +} + +export interface LagLng { + latitude: number; + longitude: number; +} + +export type CallbackFunction = ( + callbacks: { + success: (res: T) => void; + fail: () => void; + complete: () => void; + } +) => void; + +export interface MapContext { + getCenterLocation: CallbackFunction; + + moveToLocation(): void; + + translateMarker(params: { + markerId: number; + autoRotate: boolean; + duration: number; + destination: LagLng; + animationEnd: () => void; + }): void; + + includePoints(params: { padding: number[]; points: LagLng[] }): void; + + getRegion: CallbackFunction<{ southwest: LagLng; northeast: LagLng }>; + + getScale: CallbackFunction<{ scale: number }>; +} + +export interface UserInfo { + nickName: string; + avatarUrl: string; + gender: string; + city: string; + province: string; + country: string; + language: string; +} + +export interface UrlParam { + url: string; +} + +export interface FilePathParam { + filePath: string; +} + +// WePY enhanced Wx interfaces and methods below are all accessible +export interface WxEnhances { + addPhoneContact(param: WechatProfileDetails): Promise; + + authorize(param: { scope: string }): Promise; + + canIUse(name: string): Promise; + + canvasGetImageData( + params: { + canvasId: string; + x: number; + y: number; + width: number; + height: number; + }, + context: any + ): Promise<{ + width: number; + height: number; + data: Uint8ClampedArray; + }>; + + canvasPutImageData( + params: { + canvasId: string; + data: Uint8ClampedArray; + x: number; + y: number; + height?: number; + wdith: number; + }, + context: any + ): Promise; + + canvasToTempFilePath( + params: { + x: number; + y: number; + width: number; + height: number; + destWidth: number; + destHeight: number; + canvasId: string; + }, + context: any + ): Promise<{ tempFilePath: string }>; + + checkIsSoterEnrolledInDevice(params: { + checkAuthMode: "fingerPrint" | "facial" | "speech"; + }): Promise<{ + isEnrolled: boolean; + errMsg: string; + }>; + + checkIsSupportSoterAuthentication(): Promise<{ + supportMode: string[]; + }>; + + checkSession(): Promise; + + chooseInvoiceTitle(): Promise<{ + type: "0" | "1"; + title: string; + taxNumber: string; + companyAddress: string; + telephone: string; + bankName: string; + bankAccount: string; + errMsg: string; + }>; + + chooseLocation(): Promise<{ + name: string; + address: string; + latitude: number; + longitude: number; + }>; + + chooseVideo(params: { + sourceType: string[]; + compressed: boolean; + maxDuration: number; + }): Promise<{ + tempFilePath: string; + duration: number; + size: number; + height: number; + width: number; + }>; + + clearStorage(): Promise; + + createAnimation(params: { + duration: number; + timingFunction: string; + delay: number; + transformOrigin: string; + }): Promise; + + createCanvasContext(canvasId: string, context: any): Promise; + + createMapContext(mapId: string, context: any): MapContext; + + createSelectorQuery(): Promise<{}>; + + getLocation(params: { + type: string; + altitude: boolean; + }): Promise<{ + latitude: number; + longitude: number; + speed: number; + accuracy: number; + altitude: number; + verticalAccuracy: number; + horizontalAccuracy: number; + }>; + + getNetworkType(): Promise<{ networkType: string }>; + + getSavedFileInfo( + params: FilePathParam + ): Promise<{ + errMsg: string; + size: number; + createTime: number; + }>; + + getSavedFileList(): Promise<{ + errMsg: string; + fileList: object[]; + }>; + + getSetting(): Promise<{ + authSetting: { + "scope.userInfo": boolean; + "scope.userLocation": boolean; + "scope.address": boolean; + "scope.invoiceTitle": boolean; + "scope.werun": boolean; + "scope.record": boolean; + "scope.writePhotosAlbum": boolean; + "scope.camera": boolean; + }; + }>; + + getShareInfo(params: { + shareTicket: string; + timeout: number; + }): Promise<{ + errMsg: string; + encryptedData: string; + iv: string; + }>; + + getSystemInfo(): Promise<{ + brand: string; + model: string; + pixelRatio: number; + screenWidth: number; + screenHeight: number; + windowWidth: number; + windowHeight: number; + statusBarHeight: number; + language: string; + version: string; + system: string; + platform: string; + fontSizeSetting: string; + SDKVersion: string; + }>; + + getUserInfo(params: { + withCredentials: boolean; + lang: string; + timeout: number; + }): Promise<{ + userInfo: object; + rawData: string; + signature: string; + encryptedData: string; + iv: string; + }>; + + hideLoading(): Promise; + + hideNavigationBarLoading(): Promise; + + makePhoneCall(params: { phoneNumber: string }): Promise; + + navigateTo(params: UrlParam): Promise; + + onUserCaptureScreen(): Promise; + + openLocation(params: { + latitude: number; + longitude: number; + scale?: number; + name?: string; + address?: string; + }): Promise; + + pageScrollTo(params: { + scrollTop: number; + duration: number; + }): Promise; + + redirectTo(params: UrlParam): Promise; + + removeSavedFile(params: FilePathParam): Promise; + + removeStorage(params: { key: string }): Promise; + + request(params: UrlParam): Promise; + + requestPayment(params: { + timeStamp: string; + nonceStr: string; + package: string; + signType: string; + paySign: string; + }): Promise; + + scanCode(params: { + onlyFromCamera?: boolean; + scanType?: string[]; + }): Promise<{ + result: string; + scanType: string; + charSet: string; + path: string; + }>; + + setNavigationBarAlpha(params: { alpha: number }): Promise; + + setNavigationBarColor(params: { color: number }): Promise; + + setNavigationBarTitle(params: { title: string }): Promise; + + setStorage(params: { key: string; data: string | object }): Promise; + + showActionSheet(params: { + itemList: string[]; + itemColor: string; + }): Promise; + + showLoading(params: { title: string }): Promise; + + showModal(params: { + title: string; + content: string; + showCancel?: boolean; + cancelText?: string; + cancelColor?: string; + confirmText?: string; + confirmColor?: string; + }): Promise<{ confirm: boolean; cancel: boolean }>; + + showNavigationBarLoading(): Promise; + + showToast(params: { + title: string; + icon?: "success" | "loading" | "none"; + image?: string; + duration?: number; + mask?: boolean; + }): Promise; + + switchTab(params: UrlParam): Promise; +} diff --git a/types/workbox-sw/index.d.ts b/types/workbox-sw/index.d.ts new file mode 100644 index 0000000000..a169714094 --- /dev/null +++ b/types/workbox-sw/index.d.ts @@ -0,0 +1,1424 @@ +// Type definitions for workbox-sw 3.2 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Frederik Wessberg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * ===== BroadcastCacheUpdate ===== + */ + +interface IBroadcastCacheUpdateOptions { + /** + * A list of headers that will be used to determine whether the responses differ. + */ + headersToCheck: string[]; + + /** + * An attribution value that indicates where the update originated. + */ + source: string; +} + +/** + * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. + * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked + */ +declare class BroadcastCacheUpdate { + /** + * Compare two Responses and send a message via the Broadcast Channel API if they differ. + * Neither of the Responses can be opaque. + * @param {Response} firstResponse - First response to compare. + * @param {Response} secondResponse - Second response to compare. + * @param {string} url - The URL of the updated request. + * @param {string} cacheName - Name of the cache the responses belong to. This is included in the message posted on the broadcast channel. + */ + notifyIfUpdated (firstResponse: Response, secondResponse: Response, url: string, cacheName: string): void; +} + +/** + * Construct a BroadcastCacheUpdate instance with a specific channelName to broadcast messages on + */ +interface IBroadcastCacheUpdateConstructor { + new (channelName: string, options: Partial): BroadcastCacheUpdate; +} + +/** + * ===== CacheableResponse ===== + */ + +interface ICacheableResponseOptions { + statuses: number[]; + headers: { [key: string]: string }; +} + +/** + * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + */ +declare class CacheableResponse { + /** + * Checks a response to see whether it's cacheable or not, based on this object's configuration. + * @param {Response} response - The response whose cacheability is being checked. + * @returns {boolean} + */ + isResponseCacheable (response: Response): boolean; +} + +/** + * To construct a new CacheableResponse instance you must provide at least one of the config properties. + * If both statuses and headers are specified, then both conditions must be met for the Response to be considered cacheable. + */ +interface ICacheableResponseConstructor { + new (options: Partial): CacheableResponse; +} + +/** + * ===== CacheExpiration ===== + */ + +interface ICacheExpirationOptions { + /** + * The maximum number of entries to store in a cache. + */ + maxEntries: number; + + /** + * The maximum lifetime of a request to stay in the cache before it's removed. + */ + maxAgeSeconds: number; +} + +/** + * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + */ +declare class CacheExpiration { + /** + * Expires entries for the given cache and given criteria. + * @returns {Promise} + */ + expireEntries (): Promise; + + /** + * Can be used to check if a URL has expired or not before it's used. + * This requires a look up from IndexedDB, so can be slow. + * Note: This method will not remove the cached entry, call expireEntries() to remove indexedDB and Cache entries. + * @param {string} url + * @returns {Promise} + */ + isURLExpired (url: string): Promise; + + /** + * Update the timestamp for the given URL. + * This ensures the when removing entries based on maximum entries, most recently used is accurate or when expiring, the timestamp is up-to-date. + * @param {string} url + * @returns {Promise} + */ + updateTimestamp (url: string): Promise; +} + +/** + * To construct a new CacheExpiration instance you must provide at least one of the config properties. + */ +interface ICacheExpirationConstructor { + new (cacheName: string, config: Partial): CacheExpiration; +} + +/** + * ===== Strategies ===== + */ + +interface ICacheStrategyHandleOptions { + event: FetchEvent; +} + +interface ICacheStrategyMakeRequestOptions { + request: Request|string; + event?: FetchEvent; +} + +declare class CacheStrategy { + /** + * This method will perform a request strategy and follows an API that will work with the Workbox Router. + * @param {ICacheStrategyHandleOptions} input + * @returns {Promise} + */ + handle (input: ICacheStrategyHandleOptions): Promise; + + /** + * This method can be used to perform a make a standalone request outside the context of the Workbox Router. + * @param {ICacheStrategyMakeRequestOptions} input + * @returns {Promise} + */ + makeRequest (input: ICacheStrategyMakeRequestOptions): Promise; +} + +/** + * ===== CacheOnly strategy ===== + */ + +interface ICacheOnlyOptions { + /** + * Cache name to store and retrieve requests. Defaults to cache names provided by workbox-core. + */ + cacheName: string; + /** + * Plugins to use in conjunction with this caching strategy. + */ + plugins: Plugin[]; +} + +/** + * An implementation of a cache-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ +declare class CacheOnly extends CacheStrategy { +} + +/** + * Instantiates a new CacheOnly strategy + */ +interface ICacheOnlyConstructor { + new (options?: Partial): CacheOnly; +} + +/** + * ===== CacheFirst strategy ===== + */ + +interface ICacheFirstOptions extends ICacheOnlyOptions { + /** + * Values passed along to the init of all fetch() requests made by this strategy. + */ + fetchOptions: RequestInit; +} + +/** + * An implementation of a cache-first request strategy. + * A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time. + */ +declare class CacheFirst extends CacheStrategy { +} + +/** + * Instantiates a new CacheFirst strategy + */ +interface ICacheFirstConstructor { + new (options?: Partial): CacheFirst; +} + +/** + * ===== NetworkOnly strategy ===== + */ + +interface INetworkOnlyOptions extends ICacheFirstOptions { +} + +/** + * An implementation of a network-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ +declare class NetworkOnly extends CacheStrategy { +} + +/** + * Instantiates a new NetworkOnly strategy + */ +interface INetworkOnlyConstructor { + new (options?: Partial): NetworkOnly; +} + +/** + * ===== NetworkFirst strategy ===== + */ + +interface INetworkFirstOptions extends ICacheFirstOptions { + networkTimeoutSeconds: number; +} + +/** + * An implementation of a network first request strategy. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ +declare class NetworkFirst extends CacheStrategy { +} + +/** + * Instantiates a new NetworkFirst strategy + */ +interface INetworkFirstConstructor { + new (options?: Partial): NetworkFirst; +} + +/** + * ===== StaleWhileRevalidate strategy ===== + */ + +interface IStaleWhileRevalidateOptions extends ICacheFirstOptions { +} + +/** + * An implementation of a stale-while-revalidate request strategy. + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise wait for the network response. + * The cache is updated with the network response with each successful request. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ +declare class StaleWhileRevalidate extends CacheStrategy { +} + +/** + * Instantiates a new StaleWhileRevalidate strategy + */ +interface IStaleWhileRevalidateConstructor { + new (options?: Partial): StaleWhileRevalidate; +} + +/** + * ===== MatchCallback ===== + */ + +interface IMatchContext extends IURLContext { + /** + * The service workers' fetch event. + */ + event: FetchEvent; +} + +/** + * To signify a match, return anything other than null. Return null if the route shouldn't match. + */ +type MatchCallback = (context: IMatchContext) => {}|null; + +/** + * ===== HandlerCallback ===== + */ + +interface IHandlerContext extends IMatchContext { + /** + * Parameters returned by the Route's match callback function. This will be undefined if nothing was returned. + */ + params?: {}; +} + +/** + * The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response. + * If a value is returned by the match callback it will be passed in as the context.params argument. + */ +type HandlerCallback = (context: IHandlerContext) => Promise; + +/** + * ===== NavigationRoute ===== + */ + +interface IHandlerOptions { + url: string; + event: FetchEvent; + params: URLSearchParams; +} + +interface INavigationRouteOptions { + /** + * If any of these patterns match, the route will not handle the request (even if a whitelist RegExp matches). + */ + blacklist: RegExp[]; + + /** + * If any of these patterns match the URL's pathname and search parameter, + * the route will handle the request (assuming the blacklist doesn't match). + */ + whitelist: RegExp[]; +} + +/** + * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. + * It will only match incoming Requests whose mode is set to navigate. + * You can optionally only apply this route to a subset of navigation requests by using one or both of the blacklist and whitelist parameters. + */ +declare class NavigationRoute { +} + +/** + * If both blacklist and whitelist are provided, the blacklist will take precedence and the request will not match this route. + * The regular expressions in whitelist and blacklist are matched against the concatenated pathname and search portions of the requested URL. + */ +interface INavigationRouteConstructor { + new (handler: HandlerCallback, options: Partial): NavigationRoute; +} + +/** + * ===== BroadcastUpdatePlugin ===== + */ + +/** + * This plugin will automatically broadcast a message whenever a cached response is updated. + */ +declare class BroadcastUpdatePlugin { +} + +/** + * Construct a new instance with a specific channelName to broadcast messages on + */ +interface IBroadcastUpdatePluginConstructor { + new (channelName: string, options?: Partial): BroadcastUpdatePlugin; +} + +/** + * ===== BroadcastUpdatePlugin ===== + */ + +/** + * The range request plugin makes it easy for a request with a 'Range' header to be fulfilled by a cached response. + * It does this by intercepting the cachedResponseWillBeUsed plugin callback and returning the appropriate subset of the cached response body. + */ +declare class RangeRequestsPlugin { +} + +/** + * Instantiates a new RangeRequestsPlugin + */ +interface IRangeRequestsPluginConstructor { + new (): RangeRequestsPlugin; +} + +/** + * ===== CacheableResponsePlugin ===== + */ + +/** + * A class implementing the cacheWillUpdate lifecycle callback. + * This makes it easier to add in cacheability checks to requests made via Workbox's built-in strategies. + */ +declare class CacheableResponsePlugin { +} + +/** + * To construct a new cacheable response Plugin instance you must provide at least one of the config properties. + * If both statuses and headers are specified, then both conditions must be met for the Response to be considered cacheable. + */ +interface ICacheableResponsePluginConstructor { + new (config: Partial): CacheableResponsePlugin; +} + +/** + * ===== BackgroundSyncPlugin ===== + */ + +/** + * A class implementing the fetchDidFail lifecycle callback. + * This makes it easier to add failed requests to a background sync Queue. + */ +declare class BackgroundSyncPlugin { +} + +/** + * Instantiates a new BackgroundSyncPlugin + */ +interface IBackgroundSyncPluginConstructor { + new (...queueArgs: any[]): BackgroundSyncPlugin; +} + +/** + * ===== ExpirationPlugin ===== + */ + +/** + * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. + * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. + * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not have occurred + * until after the cached request has been used. If the request has a "Date" header, then a light weight expiration check is + * performed and the request will not be used immediately. + * When using maxEntries, the last request to be used will be the request that is removed from the Cache. + */ +declare class ExpirationPlugin { +} + +/** + * Instantiates a new ExpirationPlugin + */ +interface IExpirationPluginConstructor { + new (config: Partial): ExpirationPlugin; +} + +/** + * ===== ExpirationPlugin ===== + */ + +type Plugin = BroadcastUpdatePlugin|RangeRequestsPlugin|CacheableResponsePlugin|BackgroundSyncPlugin|ExpirationPlugin|WorkboxPlugin; + +/** + * ===== BackgroundSync ===== + */ + +interface IStorableRequestOptions { + url: string; + + /** + * See: https://fetch.spec.whatwg.org/#requestinit + */ + requestInit: RequestInit; + + /** + * The time the request was created, defaulting to the current time if not specified. + */ + timestamp: number; +} + +/** + * A class to make it easier to serialize and de-serialize requests so they can be stored in IndexedDB. + */ +declare class StorableRequest { + readonly timestamp: number; + + toObject (): IStorableRequestOptions; + + toRequest (): Request; + + clone (): StorableRequest; +} + +/** + * Accepts a URL and RequestInit dictionary that can be used to create a + * new Request object. A timestamp is also generated so consumers can + * reference when the object was created. + */ +interface IStorableRequestConstructor { + new (options: IStorableRequestOptions): StorableRequest; + fromRequest (request: Request): StorableRequest; +} + +/** + * ===== PrecacheController ===== + */ + +interface ICleanupResult { + /** + * List of URLs that were deleted from the precache cache. + */ + deletedCacheRequests: string[]; + /** + * List of URLs that were deleted from the precache cache. + */ + deletedRevisionDetails: string[]; +} + +interface IActivateOptions { + /** + * Plugins to be used for fetching and caching during install. + */ + plugins: Plugin[]; +} + +interface IInstallOptions { + /** + * Suppress warning messages. + */ + suppressWarnings: boolean; + + /** + * Plugins to be used for fetching and caching during install. + */ + plugins: Plugin[]; +} + +interface IPrecacheEntry { + url: string; + revision: string; +} + +interface IInstallResult { + /** + * List of entries supplied for precaching that were precached. + */ + updatedEntries: (string|IPrecacheEntry)[]; + + /** + * List of entries supplied for precaching that were already precached. + */ + notUpdatedEntries: (string|IPrecacheEntry)[]; +} + +/** + * Performs efficient precaching of assets. + */ +declare class PrecacheController { + /** + * Takes the current set of temporary files and moves them to the final cache, deleting the temporary cache once copying is complete. + * @param {IActivateOptions} options + * @returns {Promise} Resolves with an object containing details of the deleted cache requests and precache revision details. + */ + activate (options: Partial): Promise; + + /** + * This method will add items to the precache list, removing duplicates and ensuring the information is valid. + * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. + */ + addToCacheList (entries: (string|IPrecacheEntry)[]): void; + + /** + * Returns an array of fully qualified URL's that will be precached. + * @returns {string[]} An array of URLs. + */ + getCachedUrls (): string[]; + + /** + * Call this method from a service work install event to start precaching assets. + * @param {Partial} options + * @returns {Promise} + */ + install (options?: Partial): Promise; +} + +/** + * Create a new PrecacheController. + */ +interface IPrecacheControllerConstructor { + new (cacheName?: string): PrecacheController; +} + +/** + * ===== Queue ===== + */ + +interface IQueueCallback { + /** + * Invoked immediately before the request is stored to IndexedDB. Use this callback to modify request data at store time. + * @param {StorableRequest} request + */ + requestWillEnqueue (request: StorableRequest): void; + /** + * Invoked immediately before the request is re-fetched. Use this callback to modify request data at fetch time. + * @param {StorableRequest} request + */ + requestWillReplay (request: StorableRequest): void; + + /** + * Invoked after all requests in the queue have successfully replayed. + * @param {StorableRequest[]} requests + */ + queueDidReplay (requests: StorableRequest[]): void; +} + +interface IQueueOptions { + /** + * The amount of time (in minutes) a request may be retried. After this amount of time has passed, the request will be deleted from the queue. + */ + maxRetentionTime: number; + /** + * Callbacks to observe the lifecycle of queued requests. Use these to respond to or modify the requests during the replay process. + */ + callbacks: Partial; +} + +/** + * A class to manage storing failed requests in IndexedDB and retrying them later. + * All parts of the storing and replaying process are observable via callbacks. + */ +declare class Queue { + readonly name: string; + + /** + * Stores the passed request into IndexedDB. The database used is workbox-background-sync and the object store name is the same as the name this instance was created with (to guarantee it's unique). + * @param {Request} request - The request object to store. + * @returns {Promise} + */ + addRequest (request: Request): Promise; + + /** + * Retrieves all stored requests in IndexedDB and retries them. If the queue contained requests that + * were successfully replayed, the queueDidReplay callback is invoked (which implies the queue is now empty). + * If any of the requests fail, a new sync registration is created to retry again later. + * @returns {Promise} + */ + replayRequests (): Promise; +} + +/** + * Creates an instance of Queue with the given options + */ +interface IQueueConstructor { + /** + * @param {string} name - The unique name for this queue. This name must be unique as it's used to register + * sync events and store requests in IndexedDB specific to this instance. An error will be thrown if a + * duplicate name is detected. + * @param {Partial} options + * @returns {Queue} + */ + new (name: string, options?: Partial): Queue; +} + +/** + * ===== Route ===== + */ + +/** + * A Route consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a request by + * returning a non-falsy value if it can. The "handler" callback is called when there is a match + * and should return a Promise that resolves to a Response. + */ +declare class Route { +} + +/** + * Constructor for Route class. + */ +interface IRouteConstructor { + /** + * + * @param {MatchCallback} match - A callback function that determines whether the route matches a given fetch event by returning a non-falsy value. + * @param {HandlerCallback} handler - A callback function that returns a Promise resolving to a Response. + * @param {string} [method] - The HTTP method to match the Route against. + * @returns {Route} + */ + new (match: MatchCallback, handler: HandlerCallback, method?: string): Route; +} + +/** + * ===== RegExpRoute ===== + */ + +/** + * RegExpRoute makes it easy to create a regular expression based Route. + * For same-origin requests the RegExp only needs to match part of the URL. For requests against third-party servers, you must define a RegExp that matches the start of the URL. + */ +declare class RegExpRoute extends Route { +} + +/** + * If the regular expression contains capture groups, the captured values will be passed to the handler's params argument. + */ +interface IRegExpRouteConstructor { + /** + * + * @param {RegExp} regExp - The regular expression to match against URLs. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + * @param {string} [method] - The HTTP method to match the Route against. + * @returns {RegExpRoute} + */ + new (regExp: RegExp, handler: HandlerCallback, method?: string): RegExpRoute; +} + +/** + * ===== Router ===== + */ + +/** + * The Router can be used to process a FetchEvent through one or more Routes responding with a Request if a matching route exists. + * If no route matches a given a request, the Router will use a "default" handler if one is defined. + * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to gracefully deal with issues and respond with a Request. + * If a request matches multiple routes, the earliest registered route will be used to respond to the request. + */ +declare class Router { + /** + * Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler. + * @param {FetchEvent} event - The event from a service worker's 'fetch' event listener. + * @returns {Promise?} A promise is returned if a registered route can handle the FetchEvent's request. If there is no matching route and there's no defaultHandler, undefined is returned. + */ + handleRequest (event: FetchEvent): Promise|undefined; + + /** + * Registers a route with the router. + * @param {Route} route + */ + registerRoute (route: Route): void; + + /** + * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + */ + setCatchHandler (handler: HandlerCallback): void; + + /** + * Define a default handler that's called when no routes explicitly match the incoming request. + * Without a default handler, unmatched requests will go against the network as if there were no service worker present. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + */ + setDefaultHandler (handler: HandlerCallback): void; + + /** + * Unregisters a route with the router. + * @param {Route} route - The route to unregister. + */ + unregisterRoute (route: Route): void; +} + +/** + * Initializes a new Router. + */ +interface IRouterConstructor { + new (): Router; +} + +/** + * ===== CoreNamespace ===== + */ + +interface ICacheNames { + precache: string; + runtime: string; + googleAnalytics: string; +} + +interface ILogLevel { + /** + * Prints all logs from Workbox. Useful for debugging. + */ + debug: 0; + + /** + * Prints console log, warn, error and groups. Default for debug builds. + */ + log: 1; + + /** + * Prints console warn, error and groups. Default for non-debug builds. + */ + warn: 2; + + /** + * Print console error and groups. + */ + error: 3; + + /** + * Force no logging from Workbox. + */ + silent: 4; +} + +interface ICacheNameDetails { + prefix: string; + suffix: string; + precache: string; + runtime: string; + googleAnalytics: string; +} + +/** + * All of the Workbox service worker libraries use workbox-core for shared code as well as setting default values that need to be shared (like cache names). + */ +declare class CoreNamespace { + /** + * cacheNames.precache is used for precached assets, cacheNames.googleAnalytics is used by workbox-google-analytics to store analytics.js, and cacheNames.runtime is used for everything else. + */ + static readonly cacheNames: ICacheNames; + + /** + * The available log levels in Workbox: debug, log, warn, error and silent. + */ + static readonly LOG_LEVELS: ILogLevel; + + /** + * Get the current log level. + */ + static readonly logLevel: ILogLevel[keyof ILogLevel]; + + /** + * You can alter the default cache names used by the Workbox modules by changing the cache name details. + * Cache names are generated as --. + * @param {Partial} details + */ + static setCacheNameDetails (details: Partial): void; + + /** + * Set the current log level passing in one of the values from LOG_LEVELS. + * @param {number} logLevel - The new log level to use. + */ + static setLogLevel (logLevel: ILogLevel[keyof ILogLevel]): void; +} + +/** + * ===== PrecachingNamespace ===== + */ + +interface IURLContext { + /** + * The request's URL. + */ + url: URL; +} + +/** + * The "urlManipulation" callback can be used to determine if there are any additional permutations of a URL that should be used to check against the available precached files. + * For example, Workbox supports checking for '/index.html' when the URL '/' is provided. This callback allows additional, custom checks. + * @param {IURLContext} context + * @returns {URL[]} To add additional urls to test, return an Array of URL's. Please note that these should not be Strings, but URL objects. + */ +type UrlManipulation = (context: IURLContext) => URL[]; + +interface IRouteOptions { + /** + * The directoryIndex will check cache entries for a URLs ending with '/' to see if there is a hit when appending the directoryIndex value. + */ + directoryIndex: string|null; + + /** + * An array of regex's to remove search params when looking for a cache match. + */ + ignoreUrlParametersMatching: RegExp[]; + + /** + * The cleanUrls option will check the cache for the URL with a .html added to the end of the end. + */ + cleanUrls: boolean; + + /** + * This is a function that should take a URL and return an array of alternative URL's that should be checked for precache matches. + */ + urlManipulation: UrlManipulation; +} + +/** + * Most consumers of this module will want to use the precacheAndRoute() method to add assets to the Cache and respond to network requests with these cached assets. + * If you require finer grained control, you can use the PrecacheController to determine when performed. + */ +declare class PrecachingNamespace { + /** + * Performs efficient precaching of assets. + */ + static readonly PrecacheController: IPrecacheControllerConstructor; + + /** + * Add plugins to precaching. + * @param {Plugin[]} newPlugins + */ + static addPlugins (newPlugins: Plugin[]): void; + + /** + * Add a fetch listener to the service worker that will respond to network requests with precached assets. + * Requests for assets that aren't precached, the FetchEvent will not be responded to, allowing the event to fall through to other fetch event listeners. + * @param {Partial} route + */ + static addRoute (route: Partial): void; + + /** + * Add items to the precache list, removing any duplicates and store the files in the "precache cache" when the service worker installs. + * This method can be called multiple times. + * Please note: This method will not serve any of the cached files for you, it only precaches files. To respond to a network request you call addRoute(). + * If you have a single array of files to precache, you can just call precacheAndRoute(). + * @param {(string | IPrecacheEntry)[]} entries + */ + static precache (entries: (string|IPrecacheEntry)[]): void; + + /** + * This method will add entries to the precache list and add a route to respond to fetch events. + * This is a convenience method that will call precache() and addRoute() in a single call. + * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. + * @param {Partial} [route] - see addRoute() options + */ + static precacheAndRoute (entries: (string|IPrecacheEntry)[], route?: Partial): void; + + /** + * Warnings will be logged if any of the precached assets are entered without a revision property. + * This is extremely dangerous if the URL's aren't revisioned. + * However, the warnings can be supressed with this method. + * @param {boolean} suppress + */ + static suppressWarnings (suppress: boolean): void; +} + +/** + * ===== RoutingNamespace ===== + */ + +interface IRegisterNavigationRouteOptions extends INavigationRouteOptions { + cacheName: string; +} + +declare class RoutingNamespace { + /** + * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. + * It will only match incoming Requests whose mode is set to navigate. + * You can optionally only apply this route to a subset of navigation requests by using one or + * both of the blacklist and whitelist parameters. + */ + static readonly NavigationRoute: INavigationRouteConstructor; + + /** + * RegExpRoute makes it easy to create a regular expression based Route. + * For same-origin requests the RegExp only needs to match part of the URL. For requests against third-party servers, you must define a RegExp that matches the start of the URL. + */ + static readonly RegExpRoute: IRegExpRouteConstructor; + + /** + * A Route consists of a pair of callback functions, "match" and "handler". The "match" callback determine if a + * route should be used to "handle" a request by returning a non-falsy value if it can. + * The "handler" callback is called when there is a match and should return a Promise that resolves to a Response. + */ + static readonly Route: IRouteConstructor; + + /** + * The Router can be used to process a FetchEvent through one or more Routes responding with a Request if a matching route exists. + * If no route matches a given a request, the Router will use a "default" handler if one is defined. + * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to gracefully deal with issues and respond with a Request. + * If a request matches multiple routes, the earliest registered route will be used to respond to the request. + */ + static readonly Router: IRouterConstructor; + + /** + * Register a route that will return a precached file for a navigation request. This is useful for the application shell pattern. + * This method will generate a NavigationRoute and call Router.registerRoute(). + * @param {string} cachedAssetUrl + * @param {Partial} [options] + * @returns {NavigationRoute} Returns the generated Route. + */ + static registerNavigationRoute (cachedAssetUrl: string, options?: Partial): NavigationRoute; + + /** + * Easily register a RegExp, string, or function with a caching strategy to the Router. + * This method will generate a Route for you if needed and call Router.registerRoute(). + * @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a Route, all other arguments will be ignored. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + * @param {string} method - The HTTP method to match the Route against. + * @returns {Route} The generated Route(Useful for unregistering). + */ + static registerRoute (capture: string|RegExp|MatchCallback|Route, handler: HandlerCallback, method?: string): Route; + + /** + * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. + * @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. + * @returns {Promise} + */ + static setCatchHandler (handler: IHandlerOptions): Promise; + + /** + * Define a default handler that's called when no routes explicitly match the incoming request. + * Without a default handler, unmatched requests will go against the network as if there were no service worker present. + * @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. + * @returns {Promise} + */ + static setDefaultHandler (handler: IHandlerOptions): Promise; + + /** + * Unregisters a route with the router. + * @param {Route} route - The route to unregister + */ + static unregisterRoute (route: Route): void; +} + +/** + * ===== StrategiesNamespace ===== + */ + +interface IStrategyOptions { + /** + * Name of cache to use for caching (both lookup and updating). + */ + cacheName: string; + + /** + * Defining this object will add a cache expiration plugins to this strategy. + */ + cacheExpiration: Partial; + + /** + * The Plugins to use along with the Strategy + */ + plugins: Plugin[]; +} + +/** + * There are common caching strategies that most service workers will need and use. This module provides simple implementations of these strategies. + */ +declare class StrategiesNamespace { + /** + * An implementation of a cache-first request strategy. + * A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time. + */ + static readonly CacheFirst: ICacheFirstConstructor; + + /** + * An implementation of a cache-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ + static readonly CacheOnly: ICacheOnlyConstructor; + + /** + * An implementation of a network first request strategy. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ + static readonly NetworkFirst: INetworkFirstConstructor; + + /** + * An implementation of a network-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ + static readonly NetworkOnly: INetworkOnlyConstructor; + + /** + * An implementation of a stale-while-revalidate request strategy. + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise wait for the network response. + * The cache is updated with the network response with each successful request. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ + static readonly StaleWhileRevalidate: IStaleWhileRevalidateConstructor; + + /** + * Instantiates a new CacheFirst strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static cacheFirst (options?: Partial): HandlerCallback; + + /** + * Instantiates a new CacheOnly strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static cacheOnly (options?: Partial): HandlerCallback; + + /** + * Instantiates a new NetworkFirst strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static networkFirst (options?: Partial): HandlerCallback; + + /** + * Instantiates a new NetworkOnly strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static networkOnly (options?: Partial): HandlerCallback; + + /** + * Instantiates a new StaleWhileRevalidate strategy + * @param {Partial} [options] + * @returns {StaleWhileRevalidate} + */ + static staleWhileRevalidate (options?: Partial): HandlerCallback; +} + +/** + * ===== StreamsNamespace ===== + */ + +type StreamSource = Response|ReadableStream|BodyInit; + +interface IConcatenateResult { + done: Promise; + stream: ReadableStream; +} + +interface IConcatenateToResponseResult { + done: Promise; + response: Response; +} + +declare class StreamsNamespace { + /** + * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit. + * Returns an object exposing a ReadableStream with each individual stream's data returned in sequence, + * along with a Promise which signals when the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * @param {Promise[]} sourcePromises - Array of Promise containing StreamSource + * @returns {IConcatenateResult} + */ + static concatenate (sourcePromises: Promise[]): IConcatenateResult; + + /** + * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit,along with a HeadersInit. + * Returns an object exposing a Response whose body consists of each individual stream's data returned in sequence, + * along with a Promise which signals when the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * @param {Promise[]} sourcePromises - Array of Promise containing StreamSource + * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. + * @returns {IConcatenateToResponseResult} + */ + static concatenateToResponse (sourcePromises: Promise[], headersInit?: HeadersInit): IConcatenateToResponseResult; + + /** + * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. + * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. + * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. + */ + static createHeaders (headersInit?: HeadersInit): boolean; + + /** + * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. + * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. + */ + static isSupported (): boolean; + + /** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * On browsers that do not support constructing new ReadableStreams, this strategy will automatically wait for + * all the sourceFunctions to complete, and create a final response that concatenates their values together. + * @param {HandlerCallback[]} sourceFunctions - Each function should return a workbox.streams.StreamSource (or a Promise which resolves to one). + * @param {HeadersInit} headersInit . If there's no Content-Type specified, 'text/html' will be used by default. + * @returns {HandlerCallback} + */ + static strategy (sourceFunctions: HandlerCallback[], headersInit?: HeadersInit): HandlerCallback; +} + +/** + * ===== ExpirationNamespace ===== + */ + +declare class ExpirationNamespace { + /** + * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + */ + static readonly CacheExpiration: ICacheExpirationConstructor; + + /** + * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. + * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. + * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not + * have occurred until after the cached request has been used. If the request has a "Date" header, then a light weight + * expiration check is performed and the request will not be used immediately. + * When using maxEntries, the last request to be used will be the request that is removed from the Cache. + */ + static readonly Plugin: IExpirationPluginConstructor; +} + +/** + * ===== BackgroundSyncNamespace ===== + */ + +declare class BackgroundSyncNamespace { + /** + * A class implementing the fetchDidFail lifecycle callback. This makes it easier to add failed requests to a background sync Queue. + */ + static readonly Plugin: IBackgroundSyncPluginConstructor; + + /** + * A class to manage storing failed requests in IndexedDB and retrying them later. All parts of the storing and replaying process are observable via callbacks. + */ + static readonly Queue: IQueueConstructor; +} + +/** + * ===== GoogleAnalyticsNamespace ===== + */ + +interface IGoogleAnalyticsInitializeOptions { + /** + * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by workbox-core. + */ + cacheName: string; + + /** + * Measurement Protocol parameters, expressed as key/value pairs, to be added to replayed Google Analytics requests. + * This can be used to, e.g., set a custom dimension indicating that the request was replayed. + */ + parameterOverrides: { [key: string]: string }; + + /** + * A function that allows you to modify the hit parameters prior to replaying the hit. The function is invoked with the original hit's URLSearchParams object as its only argument. + * @param {URLSearchParams} params + */ + hitFilter (params: URLSearchParams): void; +} + +declare class GoogleAnalyticsNamespace { + static initialize (options: Partial): void; +} + +/** + * ===== CacheableResponseNamespace ===== + */ + +declare class CacheableResponseNamespace { + /** + * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + */ + static readonly CacheableResponse: ICacheableResponseConstructor; + + /** + * A class implementing the cacheWillUpdate lifecycle callback. This makes it easier to add in cacheability checks to requests made via Workbox's built-in strategies. + */ + static readonly Plugin: ICacheableResponsePluginConstructor; +} + +/** + * ===== BroadcastUpdateNamespace ===== + */ + +declare class BroadcastUpdateNamespace { + /** + * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. + * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked. + */ + static readonly BroadcastCacheUpdate: IBroadcastCacheUpdateConstructor; + + /** + * This plugin will automatically broadcast a message whenever a cached response is updated. + */ + static readonly Plugin: IBroadcastUpdatePluginConstructor; + + /** + * You would not normally call this method directly; + * it's called automatically by an instance of the BroadcastCacheUpdate class. + * It's exposed here for the benefit of developers who would rather not use the full BroadcastCacheUpdate implementation. + * Calling this will dispatch a message on the provided Broadcast Channel to notify interested subscribers about a + * change to a cached resource. + * The message that's posted has a formation inspired by the Flux standard action format like so: + * @param {BroadcastChannel} channel - The BroadcastChannel to use. + * @param {string} cacheName - The name of the cache in which the updated Response was stored. + * @param {string} url - The URL associated with the updated Response. + * @param {string} source - A string identifying this library as the source of the update message. + */ + static broadCastUpdate (channel: BroadcastChannel, cacheName: string, url: string, source: string): void; +} + +/** + * ===== RangeRequestsNamespace ===== + */ + +declare class RangeRequestsNamespace { + /** + * The range request plugin makes it easy for a request with a 'Range' header to be fulfilled by a cached response. + * It does this by intercepting the cachedResponseWillBeUsed plugin callback and returning the appropriate subset of the cached response body. + */ + static readonly Plugin: IRangeRequestsPluginConstructor; + + /** + * Given a Request and Response objects as input, this will return a promise for a new Response. + * @param {Request} request - A request, which should contain a Range: header. + * @param {Response} originalResponse - An original response containing the full content. + * @returns {Promise} Either a 206 Partial Content response, with the response body set to the slice of + * content specified by the request's Range: header, or a 416 Range Not Satisfiable response if the conditions of + * the Range: header can't be met. + */ + static createPartialResponse (request: Request, originalResponse: Response): Promise; +} + +/** + * ===== Workbox Plugin ===== + */ +interface WorkboxPlugin { + /** + * Called before a Response is used to update a cache. You can alter the Response before it’s added to the cache or return null to avoid updating the cache at all. + * @param {CacheWillUpdatePluginContext} context + * @returns {Promise|Response|null} + */ + readonly cacheWillUpdate?: (context: CacheWillUpdatePluginContext) => Promise|Response|null; + + /** + * Called when a new entry is added to a cache or it’s updated. Useful if you wish to perform an action after a cache update. + * @param {CacheDidUpdatePluginContext} context + * @returns {void} + */ + readonly cacheDidUpdate?: (context: CacheDidUpdatePluginContext) => void; + + /** + * Before a cached Response is used to respond to a fetch event, this callback can be used to allow or block the Response from being used. + * @param {CacheResponseWillBeUsedPluginContext} context + * @returns {Promise|Response|null} + */ + readonly cachedResponseWillBeUsed?: (context: CacheResponseWillBeUsedPluginContext) => Promise|Response|null; + + /** + * This is called whenever a fetch event is about to be made. You can alter the Request in this callback. + * @param {RequestWillFetchPluginContext} context + * @returns {Request} + */ + readonly requestWillFetch?: (context: RequestWillFetchPluginContext) => Request; + + /** + * Called when a fetch event fails (note this is when the network request can’t be made at all and not when a request is a non-200 request). + * @param {FetchDidFailPluginContext} + * @returns {void} + */ + readonly fetchDidFail?: (context: FetchDidFailPluginContext) => void; +} + +interface CacheWillUpdatePluginContext { + readonly request: Request; + readonly response: Response; +} + +interface CacheDidUpdatePluginContext { + readonly cacheName: string; + readonly request: Request; + readonly oldResponse: Response; + readonly newResponse: Response; +} + +interface CacheResponseWillBeUsedPluginContext { + readonly cacheName: string; + readonly request: Request; + readonly matchOptions: any; + readonly cachedResponse: Response; +} + +interface RequestWillFetchPluginContext { + readonly request: Request; +} + +interface FetchDidFailPluginContext { + readonly originalRequest: Request; + readonly request: Request; + readonly error: Error; +} + +/** + * ===== WorkboxNamespace ===== + */ + +/** + * A ModulePathCallback function can be used to modify the modify the where Workbox modules are loaded. + * @param {string} moduleName - The name of the module to load (i.e. 'workbox-core', 'workbox-precaching' etc.). + * @param {boolean} debug - When true, dev builds should be loaded, otherwise load prod builds. + * @returns {string} This callback should return a path of module. This will be passed to importScripts(). + */ +type ModulePathCallback = (moduleName: string, debug: boolean) => string; + +interface IConfigOptions { + /** + * If true, dev builds are using, otherwise prod builds are used. By default, prod is used unless on localhost. + */ + debug: boolean; + + /** + * To avoid using the CDN with workbox-sw set the path prefix of where modules should be loaded from. For example modulePathPrefix: '/third_party/workbox/v3.0.0/'. + */ + modulePathPrefix: string; + + /** + * If defined, this callback will be responsible for determining the path of each workbox module. + */ + modulePathCb: ModulePathCallback; +} + +declare class WorkboxNamespace { + static readonly backgroundSync: typeof BackgroundSyncNamespace; + static readonly broadcastUpdate: typeof BroadcastUpdateNamespace; + static readonly cacheableResponse: typeof CacheableResponseNamespace; + static readonly core: typeof CoreNamespace; + static readonly expiration: typeof ExpirationNamespace; + static readonly googleAnalytics: typeof GoogleAnalyticsNamespace; + static readonly precaching: typeof PrecachingNamespace; + static readonly rangeRequests: typeof RangeRequestsNamespace; + static readonly routing: typeof RoutingNamespace; + static readonly strategies: typeof StrategiesNamespace; + static readonly streams: typeof StreamsNamespace; + + /** + * Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting(). + */ + static clientsClaim (): void; + + /** + * Load a Workbox module by passing in the appropriate module name. + * This is not generally needed unless you know there are modules that are dynamically used and you want to safe guard use of the module while the user may be offline. + * @param {string} moduleName + */ + static loadModule (moduleName: string): void; + + /** + * Updates the configuration options. You can specify whether to treat as a debug build and whether to use a CDN or a specific path when importing other workbox-modules + * @param {Partial} config + */ + static setConfig (config?: Partial): void; + + /** + * Force a service worker to become active, instead of waiting. This is normally used in conjunction with clientsClaim(). + */ + static skipWaiting (): void; +} + +export default WorkboxNamespace; diff --git a/types/workbox-sw/tsconfig.json b/types/workbox-sw/tsconfig.json new file mode 100644 index 0000000000..d6c2821525 --- /dev/null +++ b/types/workbox-sw/tsconfig.json @@ -0,0 +1,26 @@ +{ + "files": [ + "index.d.ts", + "workbox-sw-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es2017", + "lib": [ + "es2015", + "dom", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/workbox-sw/tslint.json b/types/workbox-sw/tslint.json new file mode 100644 index 0000000000..453ff1da24 --- /dev/null +++ b/types/workbox-sw/tslint.json @@ -0,0 +1,12 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-redundant-jsdoc-2": false, + "no-unnecessary-class": false, + "no-empty-interface": false, + "array-type": false, + "interface-name": false, + "space-before-function-paren": false + } +} diff --git a/types/workbox-sw/workbox-sw-tests.ts b/types/workbox-sw/workbox-sw-tests.ts new file mode 100644 index 0000000000..37855310d5 --- /dev/null +++ b/types/workbox-sw/workbox-sw-tests.ts @@ -0,0 +1,11 @@ +import WorkboxSW from "workbox-sw"; + +// $ExpectError +WorkboxSW.core.setLogLevel(5); // $ExpectType void + +WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $ExpectType Route + +// $ExpectError +WorkboxSW.precaching.precacheAndRoute(/foo/); + +WorkboxSW.precaching.precacheAndRoute(["some-resource.js"], {directoryIndex: "/"}); // $ExpectType void